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): regions read on the cut follow the loop aligned from it; a stretch floor by direction; the bend and the seam written down

Soohong Kimd82f3d867c27
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index e5f9143..7acf6e0 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -719,11 +719,22 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-
loop's frame rate, so the aligned cycle lasts L*/fps seconds. `strip.json` gains
`cycle_align` (`from`, `to`, `between`, `taken`, `made_by_rife`, `made_at`, `smear` and/or
`nearest_at`, `drawings`, `retake`, `turned_by`, `turned_on`, `view`, `start_foot`, `start_foot_source`, `strikes`, the seam ratio of the rebuilt
- cells, and the re-verified GIF/WebP).
+ cells, `cells_from`, `origin`, and the re-verified GIF/WebP).
+- **Where every cell is from**: `cycle_align.cells_from` holds, per cell of the rebuilt strip,
+ `{"source": i}` — frame i of `cycle.source/`, taken as filmed (a turn, a snap, or the nearer
+ frame), as many times as it is taken — or `{"between": [i, j], "t": t}`, a frame made between
+ two. The report's loop rows carry it too.
- **The cut as filmed is kept** in `cycle.source/` on the first alignment, and every later
alignment reads from there: running it again, or at another length, never resamples a
resampled loop. Every loop of the set is resampled before any is rewritten, so a loop that
- cannot be made leaves the set as it was.
+ cannot be made leaves the set as it was. The first alignment also records the strip as cut,
+ before anything is rewritten (`cycle_align.origin`: its file's sha256 — `follow.source.png`'s
+ where a follow-through moved it —, cell size, scale, crop origin, `sample_indices`, each cell's
+ pixels by sha256, and the body's motion as `video-follow` reads it there, `reading`), and every
+ later alignment keeps it as it is. A loop aligned before this record existed has none, and gets
+ none: its cut is no longer there to read. With `cells_from` it lets a follow-through whose
+ regions were read on the cut be carried to the aligned loop (`video-follow --read-on`,
+ docs/video-pipeline.md section 6). Neither record changes a pixel of the strip, GIF or WebP.
- Loops at different frame rates are refused (one length in frames would mean different
durations), and so is a loop cut before `cell_height_cap` was recorded (cut it again).
@@ -742,7 +753,8 @@ or whose state was not aligned, is named in that state's `feet_unused` and a war
Cutting a loop again with `video-loop` removes its `cycle.source/`, so the next alignment reads
the new cut. An alignment also clears a follow-through (`video-follow`, which moved the old
cells): `follow.source.png` and the strip's `follow` record are removed and the loop's row says
-`follow_cleared`; run `video-follow` again after it.
+`follow_cleared`; run `video-follow` again after it, with `--read-on` naming the strip the regions
+were read on.
How much RIFE that is, on the 2026-10-03 sets (the experiment's `finalize.py`): resampling to
the median made 18 of 21 frames for a Lite side loop of 27, 20 of 21 for a back-diagonal loop of
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 17b6c3d..bb9a162 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -1101,7 +1101,8 @@ bounce. `video-follow` puts that follow-through back on a cut loop:
```bash
sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [--region …] \
- [--gain 2.5] [--on-fold refuse|lower] [--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] \
+ [--read-on <sha256>] [--stretch-floor D]
```
- **The region** is an ellipse over the part in the strip's first cell, in cell pixels
@@ -1180,9 +1181,71 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-
sits 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); a
- new cut with `video-loop` removes them too. Run `video-follow` again after either.
+ new cut with `video-loop` removes them too. Run `video-follow` again after either — with
+ `--read-on` where the regions were read on the cut (below).
- A one-shot (`kind: one-shot`) is refused: the follow-through is a loop's steady state.
+#### Regions read on the cut, followed on the aligned loop — `--read-on`
+
+The regions are where somebody looked: in the first cell of the strip they were read on. An
+alignment turns a loop to start on a foot strike, so its first cell is another; given the same
+regions, `video-follow` reads the motion again from that cell 0 and the regions land on another
+place of the body, and a stretched loop moves them by a motion read anew. `--read-on <sha256>`
+names the strip they were read on — its file's sha256, as cut, before any follow-through (64
+lowercase hexadecimal digits; anything else is refused before anything is read):
+
+- **`same`**: it is this loop's strip as cut (`follow.source.png` once a follow-through moved it).
+ The follow-through is the one without `--read-on`, byte for byte, and the record says so.
+- **`transported`**: it is the cut this loop was aligned from. `video-cycle-align` records that cut
+ the first time it aligns the loop (`cycle_align.origin`: its sha256, cell size, scale and crop
+ origin, each cell's pixels by sha256, and the body's motion as `video-follow` reads it there),
+ keeps it on every later alignment, and records where each cell of the new strip is from
+ (`cycle_align.cells_from`: `{"source": i}`, a frame of `cycle.source/`, or `{"between": [i, j],
+ "t": t}`, a frame made between two). Each cell is carried by the cut's reading of the cut's cell it
+ is, the regions stay where they were read (the cut's cell 0), and the damped mass is solved on
+ this loop's order, length and frame time: a turned loop gives the cut's follow-through cell for
+ cell, a stretched one gives the new cycle's offsets on the cut's motion, duplicates and all.
+- **`uncertain`**, refused: the cut is the one, but a cell was made between two of its frames
+ (RIFE, or any `between`), or a cell is not the cut's cell pixel for pixel — a crop or a scale
+ changed and nothing records how, or a cell was drawn again since. A made cell has no reading of
+ its own, and none is taken from the nearer frame by rounding.
+- **`no-match`**, refused: neither — another clip, another cut, a strip nothing here was cut or
+ aligned from. Locate the regions again on this strip.
+
+A refusal writes nothing but the strip as cut kept beside the loop, as on any refusal. Without
+`--read-on` nothing of this is read or written, and the record holds no new key. With it the record
+carries `read_on` (`sha256`, `relation`; for `transported` also `policy` and `cut_cells`, the cut's
+cell each cell is) and `carry_basis`. The printed summary carries `read_on` (the relation).
+
+#### A least area each move leaves — `--stretch-floor D`
+
+The fold rule keeps a region from folding, and so lets the region's steepest pixel take nearly
+nothing of the source: a line there is drawn across many pixels. `--stretch-floor D` (0 to under
+1) asks every region's move to leave each pixel at least D of its area. The weight's steepest
+slope is π/2 over each radius, so a move (ox, oy) leaves 1 − (π/2)·hypot(ox/rx, oy/ry) of a
+pixel's area, read by the way the region moves (the fold rule reads the smaller radius whichever
+way it moves). Each region takes the largest gain, in steps of 0.01, that keeps D in every cell
+— **and never one above the fold rule's**: where the direction would allow more (a region moving
+along its long axis) the fold rule's gain stands, so a floor only ever lowers. Under it the fold
+rule's handling stands: a region the floor takes under 1 is held and named, the strip is refused
+when every region is, and `--on-fold refuse` refuses a move under the floor. There is no default:
+without `--stretch-floor` the fold rule alone decides, byte for byte. A floor the move already
+keeps draws the same strip, GIF and WebP. The record carries `stretch` (`policy`, `floor`, and per
+region `per_gain` — the area a unit of gain takes at its worst cell, `least_cell` —, `rule_gain`,
+`floor_gain`, `gain`, `held`, `least_area`, `under_measured`) and `carry_basis`; a lowered or held
+region is named on stderr with what lowered it, the fold or the floor. On a loop aligned from the
+cut, give `--read-on` too: the floor is then read on the cut's motion, so a turned loop is lowered,
+held or refused as the cut is.
+
+The floor holds the stretch, and only the stretch: what a move also does to a line — it tilts it,
+and where two regions overlap it bends it at their seam — lowers only as the gain lowers.
+`video-follow-inspect` writes all three (below).
+
+What carries a region into a cell is the lay of the body's outline (`carry_basis: {"reading":
+"outline-lay", "region": "unverified"}`). Two strips whose alpha is the same in every cell are
+carried alike, whatever moved inside the outline; whose pixels are inside a carried ellipse is not
+read, and nothing here moves a region on a guess of it.
+
### Inspecting a follow-through — `video-follow-inspect`
The ellipse is given in the first cell, where somebody looked. Into every other cell it is carried
@@ -1193,7 +1256,7 @@ which no count of colours finds. The engine does not read what a pixel belongs t
```bash
sprite-gen video-follow-inspect --loop-dir set/front-run/loop --region 136,164,60,50 [--region …] \
- [--gain 2.5] [--on-fold refuse|lower] [--freq 2.4] [--zeta 0.6] \
+ [--gain 2.5] [--on-fold refuse|lower] [--freq 2.4] [--zeta 0.6] [--read-on <sha256>] [--stretch-floor D] \
--out-dir inspect/front-run [--scale 2] [--columns 8]
```
@@ -1212,20 +1275,22 @@ sprite-gen video-follow-inspect --loop-dir set/front-run/loop --region 136,164,6
pixels they are. Saying which cells hold the part alone is for a person or a model that looks
at the board of the cells as cut, and for a second reader apart from the first.
`video-follow` takes no such list: it moves every cell.
-- **`follow-inspect.json`** (`kind: video-follow-inspection`, `schema_version: 1`):
+- **`follow-inspect.json`** (`kind: video-follow-inspection`, `schema_version: 2`):
| key | what it holds |
|---|---|
- | `input_id` | one sha256 over what the answer is read from: the strip's sha256, the meta's `cut_sha256`, the regions, the settings, the policy and the engine's version |
+ | `input_id` | one sha256 over what the answer is read from: the schema version, the strip's sha256, the meta's `cut_sha256`, the regions, the settings, the policy and the engine's version |
| `inputs.strip` | `file`, `sha256`, `bytes`: the strip as cut that was read |
| `inputs.meta` | `file`, `sha256`, `bytes`: `<name>.strip.json` as read; `cut_sha256`: its sha256 without the `follow` record `video-follow` adds (keys sorted, no spaces); `follow_recorded` |
| `inputs.cut` | `frames`, `w`, `h`, `delay_ms`, as read from the meta |
- | `inputs.regions`, `inputs.settings` | the ellipses in the order given; `gain`, `on_fold`, `freq_hz`, `zeta` |
- | `inputs.policy`, `inputs.engine` | the way the motion is read and a region moved, by name (`follow.POLICY`) with the constants it is fixed by; the engine's `name` and `version` |
+ | `inputs.regions`, `inputs.settings` | the ellipses in the order given; `gain`, `on_fold`, `freq_hz`, `zeta`, `read_on` and `stretch_floor` (null where not asked) |
+ | `inputs.policy`, `inputs.engine` | the way the motion is read and a region moved, by name (`follow.POLICY`) with the constants it is fixed by, and the ways a reading is carried (`transport`) and a floor kept (`stretch_floor`), by name; the engine's `name` and `version` |
| `follow` | the follow-through as `video-follow` records it in the strip's meta, without `gif` and `webp` |
- | `regions[i]` | `index`, `ellipse` as given, `radius_px`, `gain` (0 when held), `held`, `gain_limit`; over all cells the largest `reach_px` and `fold_ratio`, the least `jacobian_min`, the sum of `changed_px`; `ring`, its colour on the boards |
- | `cells[k]` | `index`, `carry_px` (across, down), `changed_px`, `jacobian_min`, `box` (x0, y0, x1, y1: the cell's picture on both boards) and `regions[i]` |
- | `cells[k].regions[i]` | `ellipse`: the region carried (centre plus `carry_px`, the radii as given); `offset_px` (across, down) and `reach_px`: the region's own move in that cell, 0 when held; `fold_ratio`; `jacobian_min` and `jacobian_min_at` (x, y); `ellipse_px`, `solid_px`; `changed_px`; `ownership` |
+ | `carry_basis` | `{"reading": "outline-lay", "region": "unverified"}`: what carries a region, and that whose pixels it holds is not read |
+ | `regions[i]` | `index`, `ellipse` as given, `radius_px`, `gain` (0 when held), `held`, `gain_limit`; over all cells the largest `reach_px`, `fold_ratio`, `bend` and `bend_deg`, the least `jacobian_min`, the sum of `changed_px`; `ring`, its colour on the boards |
+ | `seams` | per pair of moving regions that meet in some cell (`regions`: [i, j]), the largest seam: `jump`, `deg`, the `cell` and the point `at` (x, y) |
+ | `cells[k]` | `index`, `carry_px` (across, down), `changed_px`, `jacobian_min`, `seams` (as above, per pair that meets in that cell), `box` (x0, y0, x1, y1: the cell's picture on both boards) and `regions[i]` |
+ | `cells[k].regions[i]` | `ellipse`: the region carried (centre plus `carry_px`, the radii as given); `offset_px` (across, down) and `reach_px`: the region's own move in that cell, 0 when held; `fold_ratio`; `jacobian_min` and `jacobian_min_at` (x, y); `bend` and `bend_deg`; `ellipse_px`, `solid_px`; `changed_px`; `ownership` |
| `boards` | `scale`, `columns`, `size`, `ground`; `source` and `moved`, each `file`, `sha256` (the PNG file) and `pixels_sha256` (its pixels) |
- **`carry_px`** is how far the cell's body lies from the first cell's, in whole pixels: what
@@ -1243,10 +1308,25 @@ sprite-gen video-follow-inspect --loop-dir set/front-run/loop --region 136,164,6
Where regions overlap the move is the larger one's, so a region's numbers there are what is
drawn in its ellipse, not its own move alone. `changed_px` counts the pixels whose RGBA the
move changes; outside every carried ellipse it changes none.
+- **A move does three things to the picture, and each is written apart.** It stretches it — the
+ least area, `jacobian_min` (D), the one `--stretch-floor` holds. It tilts a line: the move's
+ steepest slope, |offset|·π/(2·smaller radius), `bend` (G), with `bend_deg` = atan G — the same
+ number as `fold_ratio`, named for what it does: at 1 a line tilts 45°, and a region `--on-fold
+ lower` lowered moves just under it. A round region moving along a radius has G = 1 − D, but a
+ region moving along its long axis keeps D high while G stays near 1, so neither stands for the
+ other. And where two regions overlap, `video-follow` moves each pixel by the larger of their
+ weighted moves (by the larger weight where they move by one gain), so across the curve where the
+ two are equal the move's gradient jumps from one region's to the other's and a straight line
+ bends there: `seams`, the largest jump on that curve — the norm of the difference of the two
+ gradients, each the offset times the weight's gradient — and its angle `deg`. It is looked for
+ along rows a quarter pixel apart, between points inside both ellipses where the larger move
+ changes hands, and found there by halving. A held region has no seam. Quality is read from these
+ three, not from `fold.ratio`; a floor lowers the bend and the seam only as it lowers the gain.
- **The record names what it was read from.** It holds no path, no time and nothing of the
machine: the same loop asked the same way writes the same record, byte for byte, anywhere.
`input_id` is the same before and after `video-follow` is run on the loop, and another after a
- new cut, an alignment, a changed region or setting, or another engine version — what somebody
+ new cut, an alignment, a changed region or setting (`read_on` and `stretch_floor` among them), or
+ another engine version — what somebody
saw on one cut's boards is not evidence for another cut. `--scale` and `--columns` change the
boards and their sha256, not `input_id` and not a number of the record but the `box`es.
`pixels_sha256` is over a board's pixels (RGB, row by row), so another PNG writer gives the same
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.py
index e53c60f..9195fa5 100644
--- a/sprite_gen/video/align.py
+++ b/sprite_gen/video/align.py
@@ -25,6 +25,14 @@ The loop directories are `video-loop` output directories. Their first alignment
as filmed in `cycle.source/`; every later alignment reads from there, so running it again — or
with another length — never resamples a resampled loop.
+Every alignment records where each cell of the new strip is from (`cycle_align.cells_from`): a frame
+of `cycle.source/` (`{"source": i}`, as many times as it is taken) or a frame made between two of them
+(`{"between": [i, j], "t": t}`). The first also records the strip as cut (`cycle_align.origin`,
+`follow.cut_origin`: its sha256, cell size, scale and crop origin, its cells, and the body's motion as
+`video-follow` reads it there), and every later one keeps it: regions somebody located on the cut's
+first cell are carried to the aligned loop by these two (`video-follow --read-on`), not read again on a
+first cell that is another. Neither changes a pixel of the strip, the GIF or the WebP.
+
Resampling to one length assumes every loop holds one cycle. A loop that holds two (a cut that
took two strides as one) would come out walking twice as fast as the rest, and pixels cannot tell
it from a loop of one stride whose two steps look alike. So each loop is screened first
@@ -73,6 +81,7 @@ from sprite_gen._deps import np
from sprite_gen.gen import handedness as handed_mod
from sprite_gen.spec.runio import atomic_write_text
from sprite_gen.util.gif_utils import save_clean_gif
+from sprite_gen.video import follow as follow_mod
from sprite_gen.video import held as held_mod
from sprite_gen.video import legs as legs_mod
from sprite_gen.video import loop as loop_mod
@@ -173,8 +182,10 @@ def _retake_line(name: str, r: dict[str, Any]) -> str:
def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interpolate | None,
- *, between: str = DEFAULT_BETWEEN) -> tuple[list[Image.Image], dict[str, Any]]:
- """`frames` as one cycle, resampled to `length` frames at times k·L/length (offset 0).
+ *, between: str = DEFAULT_BETWEEN, cells_from: list[dict[str, Any]] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:
+ """`frames` as one cycle, resampled to `length` frames at times k·L/length (offset 0). Where `cells_from` is a
+ list, where each frame came from is appended to it: `{"source": i}` for a frame of `frames` taken as it is, `{"between":
+ [i, j], "t": t}` for one made between two.
A time between two source frames is made by `interpolate`, with what it added and the outline it
lost measured (`rife.smear`) and judged (`faults`); `between` auto keeps a made frame with no
@@ -195,13 +206,13 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Inter
t = k * count / length
i = int(np.floor(t))
frac = t - i
- nearer = frames[(i + (frac >= 0.5)) % count]
+ nearer = (i + (frac >= 0.5)) % count
if frac < SNAP:
- out.append(frames[i % count])
+ taken: dict[str, Any] = {"source": i % count}
elif frac > 1 - SNAP:
- out.append(frames[(i + 1) % count])
+ taken = {"source": (i + 1) % count}
elif between == "nearest":
- out.append(nearer)
+ taken = {"source": nearer}
nearest_at.append(k)
else:
if interpolate is None:
@@ -211,9 +222,12 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Inter
measure = rife_mod.smear(made, a, b)
wrong = faults(measure)
keep = between == "rife" or not wrong
- out.append(made if keep else nearer)
+ taken = {"between": [i % count, (i + 1) % count], "t": round(frac, 4)} if keep else {"source": nearer}
(made_at if keep else nearest_at).append(k)
smears.append({"at": k, "method": "rife" if keep else "nearest", **measure, "faults": wrong})
+ out.append(made if "between" in taken else frames[taken["source"]])
+ if cells_from is not None:
+ cells_from.append(taken)
facts: dict[str, Any] = {"from": count, "to": length, "between": between, "taken": length - len(made_at),
"made_by_rife": len(made_at), "made_at": made_at}
if between != "rife":
@@ -559,9 +573,23 @@ def _source_frames(loop_dir: Path) -> list[Image.Image]:
return [Image.open(f).convert("RGBA") for f in files]
+def origin_of(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str, Any] | None:
+ """The strip as cut that this loop is aligned from (`follow.cut_origin`), read before anything is rewritten: on a
+ loop never aligned its strip now (`follow.source.png` where a follow-through moved it); on a loop aligned before,
+ the origin its first alignment recorded, kept as it is — None where that alignment recorded none (the cut is no
+ longer there to read)."""
+ if "cycle_align" in meta:
+ return meta["cycle_align"].get("origin")
+ source = loop_dir / loop_mod.FOLLOW_SOURCE
+ strip = source if source.exists() else loop_dir / f"{meta_path.name[: -len('.strip.json')]}.strip.png"
+ return follow_mod.cut_origin(strip.read_bytes(), meta)
+
+
def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list[Image.Image], fps: float,
- record: dict[str, Any]) -> dict[str, Any]:
- """Write the aligned cycle, strip, GIF and WebP over the loop's own, at the loop's own cell size rules."""
+ record: dict[str, Any], *, cells_from: list[dict[str, Any]] | None = None,
+ origin: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Write the aligned cycle, strip, GIF and WebP over the loop's own, at the loop's own cell size rules. `cells_from`
+ says where each of `frames` is from; the record keeps it per cell of the strip, with the cut's `origin`."""
name = meta_path.name[: -len(".strip.json")]
cycle_dir = loop_dir / "cycle"
cycle_dir.mkdir(exist_ok=True)
@@ -590,6 +618,10 @@ def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list
adjacent = float(np.abs(flat[1:] - flat[:-1]).mean())
seam = float(np.abs(flat[-1] - flat[0]).mean())
record["seam_ratio"] = round(seam / adjacent, 4) if adjacent > 0 else None
+ if origin is not None:
+ record["origin"] = origin
+ if cells_from is not None: # per cell of the strip, which may hold fewer of the frames than the cycle (`sample_indices`)
+ record["cells_from"] = [cells_from[i] for i in strip_meta["sample_indices"]]
merged["cycle_align"] = record
strip.save(loop_dir / f"{name}.strip.png")
atomic_write_text(meta_path, json.dumps(merged, indent=2) + "\n")
@@ -748,11 +780,17 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
interpolate = found
return interpolate(a, b, t)
- # Every loop is resampled before any is rewritten: a loop that cannot be made leaves the set as it was.
+ # Every loop is resampled before any is rewritten: a loop that cannot be made leaves the set as it was. The cut
+ # each is aligned from is read first, while its strip is still the cut's.
+ origins = [origin_of(d, meta_path, meta) for d, meta_path, meta, _ in loops]
aligned = []
for i, ((d, *_), frames, view) in enumerate(zip(loops, sources, views or [None] * len(loops))):
+ # which frame of cycle.source/ each of `frames` is: all of them, or the one cycle `--cycles` took out
+ index = ([(taken[i]["start"] + k) % taken[i]["from"] for k in range(taken[i]["length"])] if i in taken
+ else list(range(len(frames))))
+ provenance: list[dict[str, Any]] = []
try:
- out, facts = resample(frames, target, lazy, between=between)
+ out, facts = resample(frames, target, lazy, between=between, cells_from=provenance)
strike = foot_strike(out, view=view, foot=start_foot, given=told.get(i))
except rife_mod.RifeNotInstalled as exc:
raise rife_mod.RifeNotInstalled(f"{d}: {exc}") from exc
@@ -774,11 +812,15 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
record["nearest_at"] = sorted((k - start) % target for k in facts["nearest_at"])
if "smear" in facts:
record["smear"] = sorted(({**m, "at": (m["at"] - start) % target} for m in facts["smear"]), key=lambda m: m["at"])
- aligned.append((out[start:] + out[:start], record))
+ provenance = [{"source": index[p["source"]]} if "source" in p else {"between": [index[j] for j in p["between"]], "t": p["t"]}
+ for p in provenance]
+ aligned.append((out[start:] + out[:start], record, provenance[start:] + provenance[:start]))
rows = []
- for (d, meta_path, meta, _), (out, record) in zip(loops, aligned):
- merged = _rebuild(d, meta_path, meta, out, fps, record)
- rows.append({"dir": str(d), "name": meta_path.name[: -len(".strip.json")], **{k: v for k, v in record.items() if k not in ("gif", "webp")},
+ for (d, meta_path, meta, _), (out, record, provenance), origin in zip(loops, aligned, origins):
+ merged = _rebuild(d, meta_path, meta, out, fps, record, cells_from=provenance, origin=origin)
+ # The report names where each cell is from; the cut's own record stays in the strip's meta.
+ rows.append({"dir": str(d), "name": meta_path.name[: -len(".strip.json")],
+ **{k: v for k, v in record.items() if k not in ("gif", "webp", "origin")},
"strip": {k: merged[k] for k in ("frames", "w", "h", "body_h", "delay_ms")}})
warnings = [_fault_line(r["name"], m) for r in rows for m in r.get("smear", []) if m["faults"]]
retakes = [{"dir": r["dir"], "name": r["name"], **r["retake"]} for r in rows if r["retake"]]
diff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.py
index 510cca4..2ba5931 100644
--- a/sprite_gen/video/follow.py
+++ b/sprite_gen/video/follow.py
@@ -36,14 +36,39 @@ The strip as it was before is kept as `follow.source.png` beside it; running the
reads from there, so a second follow-through never moves a moved strip. `video-loop` (a new
cut) and `video-cycle-align` (a new cycle) remove it, and the alignment records that the
follow-through was cleared. docs/video-pipeline.md section 6.
+
+The regions are where somebody looked: in the first cell of the strip they were read on. An alignment
+turns a loop to start elsewhere, and its first cell is then another; read again there, the motion is
+taken from another cell 0 and the regions land on another place of the body. `--read-on <sha256>` names
+the strip (as cut, before any follow-through) the regions were read on. That strip is this loop's own —
+`same`, read as ever — or the cut this loop was aligned from (`video-cycle-align` records it, with its
+reading and where every new cell is from): then the cut's reading is carried to each cell from the cut's
+cell it is, the regions stay where they were read, and the damped mass is solved on the new order, length
+and frame time (`transported`). A cell the alignment made between two of the cut's, or one that is not
+the cut's cell pixel for pixel (a crop or a scale changed, and nothing records how), has no reading to
+carry: refused `uncertain`, never carried by the nearest whole cell. Any other strip is refused
+`no-match`. Without `--read-on` nothing of this is read or written.
+
+`--stretch-floor D` asks every region's move to leave each pixel at least D of its area. The weight's
+steepest slope is π/2 over each radius, so a move (ox, oy) leaves 1 − (π/2)·hypot(ox/rx, oy/ry) of it —
+by the way the region moves, where the fold rule reads the smaller radius whichever way it moves. Each
+region takes the largest gain, in steps of GAIN_STEP, that keeps the floor in every cell, and never one
+above what the fold rule gave it: the floor only lowers. Under it the fold rule's handling stands (under 1
+held, every region held refused; `--on-fold refuse` refuses). The record names the floor and its policy.
+
+What carries a region is the lay of the body's outline (`carry_basis`): whose pixels are inside the
+carried ellipse is not read, and nothing here moves a region on a guess of it.
"""
from __future__ import annotations
import argparse
+import hashlib
+import io
import json
import math
import os
+import re
import shutil
import sys
import tempfile
@@ -73,6 +98,15 @@ HARMONICS = 6 # of the cycle, for the body's motion: a step's shape, not its no
ALPHA_SOLID = 128
WORN_FROM, WORN_TO = 0.25, 0.5 # of the body's depth in the first cell: the levels its silhouette is worn down to
SOURCE = loop_mod.FOLLOW_SOURCE
+# How a reading made on the cut is carried to a loop aligned from it (`--read-on`): per whole cell of the cut, by the
+# alignment's record of where each cell is from, and only to a cell that is that cell pixel for pixel.
+TRANSPORT_POLICY = "cut-reading/whole-cell/1"
+# How `--stretch-floor` reads a region's least area: the cos² weight's closed form, by direction, never above the
+# fold rule's gain.
+STRETCH_POLICY = "stretch-floor/cos2-direction/1"
+# What carries a region into a cell: the lay of the body's outline. Whose pixels the carried ellipse holds is not read.
+CARRY_BASIS = {"reading": "outline-lay", "region": "unverified"}
+READ_ON = re.compile(r"[0-9a-f]{64}") # a strip's sha256, as `--read-on` names it
def parse_region(text: str) -> tuple[float, float, float, float]:
@@ -85,6 +119,13 @@ def parse_region(text: str) -> tuple[float, float, float, float]:
return cx, cy, rx, ry
+def parse_read_on(text: str) -> str:
+ if not READ_ON.fullmatch(text):
+ raise argparse.ArgumentTypeError(f"--read-on wants the sha256 of the strip the regions were read on (64 lowercase "
+ f"hexadecimal digits), got {text!r}")
+ return text
+
+
def _run_depth(solid: np.ndarray, axis: int) -> np.ndarray:
"""Per solid pixel, how far along `axis` the nearest clear pixel is (1 beside one; past the cell's edge is clear)."""
m = np.moveaxis(solid, axis, -1)
@@ -238,6 +279,109 @@ def body_motion(cells: list[Image.Image]) -> tuple[np.ndarray, np.ndarray, int,
height0, [worn[0], worn[-1]])
+def _cells(strip: Image.Image, n: int, w: int, h: int) -> list[Image.Image]:
+ return [strip.crop((k * w, 0, (k + 1) * w, h)) for k in range(n)]
+
+
+def _cell_sha256(cell: Image.Image) -> str:
+ """One cell's pixels, RGBA row by row: a cell drawn alike is the same one, whatever wrote its file."""
+ return hashlib.sha256(cell.tobytes()).hexdigest()
+
+
+def cut_origin(strip_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:
+ """What `video-cycle-align` keeps of a loop's strip as cut when it first aligns it (`cycle_align.origin`), so a
+ follow-through whose regions were read on that cut can be carried to the aligned loop (`--read-on`): the strip's
+ sha256 (the file's bytes, as `--read-on` names it), its cell size, scale and crop origin, which frame of the
+ cycle each of its cells is (`sample_indices`), each cell's pixels by sha256, and the body's motion as read on
+ it (`reading`: per cell how far its body lies from cell 0's, across and down, by `POLICY`). A strip whose body
+ cannot be read keeps `reading` None and says why. Reads the bytes given and nothing else."""
+ strip = Image.open(io.BytesIO(strip_bytes)).convert("RGBA")
+ n, w, h = int(meta["frames"]), int(meta["w"]), int(meta["h"])
+ rect, samples = meta.get("source_rect"), meta.get("sample_indices")
+ origin: dict[str, Any] = {
+ "strip_sha256": hashlib.sha256(strip_bytes).hexdigest(), "frames": n, "w": w, "h": h, "scale": meta.get("scale"),
+ "crop_origin": None if rect is None else list(rect[:2]),
+ # A cut made before its strip recorded the frames it took holds every frame of its cycle, or it was subsampled
+ # and which ones is not known.
+ "sample_indices": list(samples) if samples is not None else (list(range(n)) if n == meta.get("cycle_frames") else None),
+ }
+ if strip.size != (w * n, h):
+ return origin | {"cells_sha256": None, "reading": None,
+ "reading_why": f"the strip is {strip.size[0]}x{strip.size[1]}, its meta says {w * n}x{h}"}
+ cells = _cells(strip, n, w, h)
+ origin["cells_sha256"] = [_cell_sha256(cell) for cell in cells]
+ try:
+ rows, cols, height0, worn = body_motion(cells)
+ except ValueError as exc:
+ return origin | {"reading": None, "reading_why": str(exc)}
+ origin["reading"] = {"policy": POLICY, "carry_px": [[c, r] for c, r in zip(cols.tolist(), rows.tolist())],
+ "body_px": height0, "body_worn_px": worn}
+ return origin
+
+
+def read_on_relation(meta: dict[str, Any], strip_sha256: str, read_on: str, *, verb: str = VERB) -> str:
+ """How the strip the regions were read on (`read_on`) stands to this loop: its own strip as cut (`same`), or the
+ cut it was aligned from (`transported`); refused `no-match` otherwise."""
+ if read_on == strip_sha256:
+ return "same"
+ origin = (meta.get("cycle_align") or {}).get("origin")
+ if origin is not None and origin.get("strip_sha256") == read_on:
+ return "transported"
+ aligned_from = f"the cut it was aligned from ({origin['strip_sha256']})" if origin else "a cut it was aligned from (none is recorded)"
+ raise SystemExit(f"{verb}: --read-on {read_on}: no-match — the regions were read on a strip that is neither this loop's "
+ f"strip as cut ({strip_sha256}) nor {aligned_from}; locate them again on this strip")
+
+
+def transported_motion(meta: dict[str, Any], cells: list[Image.Image], read_on: str, *,
+ verb: str = VERB) -> tuple[np.ndarray, np.ndarray, int, list[int], list[int]]:
+ """The cut's reading carried to `cells`, the strip of a loop aligned from the cut `read_on` names: per cell how far
+ the body of the cut's cell it is lies from the cut's cell 0 (down, then across, as `body_motion` gives them), the
+ body's height and wear as read on the cut, and which cell of the cut each cell is.
+
+ The alignment records where each cell is from (`cycle_align.cells_from`). A cell made between two of the cut's
+ has no reading, and is not given its nearer one's; a cell the record calls the cut's must be that cell pixel for
+ pixel, so a crop, a scale or a drawing changed since — and not recorded as a transform — is caught here. Either
+ is refused `uncertain`."""
+ record = meta.get("cycle_align") or {}
+ origin, cells_from = record["origin"], record.get("cells_from")
+
+ def uncertain(why: str) -> SystemExit:
+ return SystemExit(f"{verb}: --read-on {read_on} is the cut this loop was aligned from, but uncertain: {why}; the "
+ "reading is not carried — only a whole cell of the cut carries it, and none is taken by rounding")
+
+ reading = origin.get("reading")
+ if reading is None:
+ raise uncertain(f"the cut's reading was not recorded ({origin.get('reading_why')})")
+ if reading.get("policy") != POLICY:
+ raise uncertain(f"the cut was read as {reading.get('policy')}, and this engine reads as {POLICY}")
+ if not isinstance(cells_from, list) or len(cells_from) != len(cells):
+ raise uncertain(f"the alignment records where {len(cells_from) if isinstance(cells_from, list) else 'no'} cells are "
+ f"from, and the strip has {len(cells)}")
+ for k, entry in enumerate(cells_from):
+ if "source" not in entry:
+ i, j = entry["between"]
+ raise uncertain(f"cell {k} is made between the cut's frames {i} and {j} (t {entry['t']:g})")
+ (w, h), rect = cells[0].size, meta.get("source_rect")
+ now = (w, h, meta.get("scale"), None if rect is None else list(rect[:2]))
+ then = (origin["w"], origin["h"], origin["scale"], origin["crop_origin"])
+ if now != then:
+ raise uncertain(f"the cut's crop or scale changed (cells {then[0]}x{then[1]} at scale {then[2]} from {then[3]}, now "
+ f"{w}x{h} at scale {now[2]} from {now[3]}) and no transform is recorded")
+ frames, digests = origin["sample_indices"], origin["cells_sha256"]
+ cut_cells = []
+ for k, (cell, entry) in enumerate(zip(cells, cells_from)):
+ i = entry["source"]
+ if frames is None or i not in frames:
+ raise uncertain(f"cell {k} is frame {i} of the cut's cycle, which the cut's strip does not hold")
+ j = frames.index(i)
+ if _cell_sha256(cell) != digests[j]:
+ raise uncertain(f"cell {k} is not the cut's cell {j} as drawn: its pixels differ")
+ cut_cells.append(j)
+ carry = reading["carry_px"]
+ return (np.asarray([carry[j][1] for j in cut_cells], float), np.asarray([carry[j][0] for j in cut_cells], float),
+ int(reading["body_px"]), list(reading["body_worn_px"]), cut_cells)
+
+
def follow_offsets(motion: np.ndarray, fps: float, *, freq: float, zeta: float, gain: float) -> np.ndarray:
"""The part's offset from where the body carries it, per cell, in the cycle's steady state."""
n = len(motion)
@@ -275,6 +419,28 @@ def lowered_gain(gain: float, reach_per_gain: float, radius: float) -> float:
return min(gain, round(steps * GAIN_STEP, 2))
+def stretch_per_gain(radii: tuple[float, float], across: np.ndarray, down: np.ndarray) -> tuple[float, int]:
+ """How much of a pixel's area a region's move takes per unit of gain, at its worst cell, and that cell: the cos²
+ weight is steepest at π/2 over each radius, so a move (ox, oy) leaves 1 − (π/2)·hypot(ox/rx, oy/ry) of the area
+ (`across`, `down`: the move at gain 1, per cell)."""
+ rx, ry = radii
+ per_cell = (math.pi / 2) * np.hypot(across / rx, down / ry)
+ k = int(np.argmax(per_cell))
+ return float(per_cell[k]), k
+
+
+def floor_gain(gain: float, per_gain: float, floor: float) -> float:
+ """The largest gain, in steps of GAIN_STEP and no more than `gain`, whose move leaves `floor` of a pixel's area or
+ more (1 − gain · `per_gain` ≥ `floor`)."""
+ if per_gain <= 0 or 1 - gain * per_gain >= floor:
+ return gain
+ steps = math.floor((1 - floor) / per_gain / GAIN_STEP) + 1
+ # The step count is rounded from floats: the one test that decides is the area left at the gain written.
+ while steps > 0 and 1 - round(steps * GAIN_STEP, 2) * per_gain < floor:
+ 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)
@@ -354,6 +520,8 @@ class Request:
freq: float
zeta: float
on_fold: str
+ read_on: str | None = None # the sha256 of the strip as cut the regions were read on; None: this strip's, as ever
+ stretch_floor: float | None = None # the least area a moved pixel keeps; None: the fold rule alone
@property
def strip_path(self) -> Path:
@@ -365,7 +533,8 @@ class Request:
def read_request(loop_dir: Path, regions: list[tuple[float, float, float, float]], *, gain: float = GAIN_DEFAULT,
- freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, on_fold: str = "refuse", verb: str = VERB) -> Request:
+ freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, on_fold: str = "refuse", verb: str = VERB,
+ read_on: str | None = None, stretch_floor: float | None = None) -> Request:
loop_dir = loop_dir.expanduser().resolve()
# The numbers go into the record, which is JSON, and into the cells' arithmetic: a numpy number from a
# caller (an int64 has no JSON form) is read as the float the command line gives, so every caller of the
@@ -387,7 +556,15 @@ def read_request(loop_dir: Path, regions: list[tuple[float, float, float, float]
raise SystemExit(f"{verb}: --gain must be 0 or more, --freq and --zeta above 0")
if on_fold not in ON_FOLD_MODES:
raise SystemExit(f"{verb}: unknown --on-fold {on_fold!r}; expected one of {', '.join(ON_FOLD_MODES)}")
- return Request(loop_dir, name, meta_path, meta_bytes, meta, regions, gain, freq, zeta, on_fold)
+ if read_on is not None and not READ_ON.fullmatch(str(read_on)):
+ raise SystemExit(f"{verb}: --read-on wants the sha256 of the strip the regions were read on (64 lowercase "
+ f"hexadecimal digits), got {read_on!r}")
+ if stretch_floor is not None:
+ stretch_floor = float(stretch_floor)
+ if not 0 <= stretch_floor < 1: # a NaN is neither
+ raise SystemExit(f"{verb}: --stretch-floor is the least area a moved pixel keeps, at least 0 and under 1; got {stretch_floor:g}")
+ return Request(loop_dir, name, meta_path, meta_bytes, meta, regions, gain, freq, zeta, on_fold,
+ None if read_on is None else str(read_on), stretch_floor)
@dataclass(frozen=True, eq=False)
@@ -417,9 +594,14 @@ class Answer:
dy: np.ndarray
reach: float
groups: list[tuple[list[tuple[float, float, float, float]], tuple[np.ndarray, np.ndarray]]]
+ read_on: dict[str, Any] | None = None # how the strip the regions were read on stands to this one (`--read-on`)
+ stretch: dict[str, Any] | None = None # the floor asked, and what it did to each region (`--stretch-floor`)
def carry(self, k: int) -> tuple[float, float]:
- """How far cell k's body lies from cell 0's, across and down: every region's ellipse is carried by it."""
+ """How far cell k's body lies from cell 0's, across and down: every region's ellipse is carried by it. Carried
+ from the cut, the cells' motion is already from the cut's cell 0, where the regions were read."""
+ if self.read_on is not None and self.read_on["relation"] == "transported":
+ return self.cols[k], self.rows[k]
return self.cols[k] - self.cols[0], self.rows[k] - self.rows[0]
def moves_in(self, k: int) -> list[tuple[list[tuple[float, float, float, float]], tuple[float, float]]]:
@@ -450,27 +632,41 @@ class Answer:
| ({} if len(set(self.gains)) == 1 else {"gain": g, "held": hold})
for radius, ratio, g, hold in zip(self.radii, self.ratios, self.gains, self.held)],
},
- }
+ } | ({} if self.read_on is None else {"read_on": self.read_on}) | ({} if self.stretch is None else {"stretch": self.stretch}) \
+ | ({} if self.read_on is None and self.stretch is None else {"carry_basis": dict(CARRY_BASIS)})
-def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str = VERB) -> Answer:
+def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str = VERB,
+ strip_sha256: str | None = None) -> Answer:
"""The answer to `request` on `strip`, the loop's strip as cut (an RGBA picture; `strip_name` names its file
- in a refusal). Reads nothing else and writes nothing."""
+ in a refusal, `strip_sha256` is its file's, read where the request names the strip its regions were read on).
+ Reads nothing else and writes nothing."""
meta, regions = request.meta, request.regions
gain, freq, zeta, on_fold = request.gain, request.freq, request.zeta, request.on_fold
n, w, h = int(meta["frames"]), int(meta["w"]), int(meta["h"])
if strip.size != (w * n, h):
raise SystemExit(f"{verb}: {strip_name} is {strip.size[0]}x{strip.size[1]}, the strip meta says {w * n}x{h}; "
"cut the loop again (video-loop)")
+ cells = _cells(strip, n, w, h)
+ read_on = None
+ if request.read_on is not None:
+ if strip_sha256 is None:
+ raise ValueError("solve: a request with read_on needs the strip's sha256")
+ read_on = {"sha256": request.read_on, "relation": read_on_relation(meta, strip_sha256, request.read_on, verb=verb)}
for cx, cy, rx, ry in regions:
if not (0 <= cx < w and 0 <= cy < h):
raise SystemExit(f"{verb}: --region centre {cx:g},{cy:g} is outside the {w}x{h} cell")
- cells = [strip.crop((k * w, 0, (k + 1) * w, h)) for k in range(n)]
fps = 1000.0 / float(meta["delay_ms"])
- try:
- rows, cols, height0, worn = body_motion(cells)
- except ValueError as exc:
- raise SystemExit(f"{verb}: {exc}") from exc
+ if read_on is not None and read_on["relation"] == "transported":
+ # The cut's own reading, cell for cell: the regions are where they were read, on the cut's cell 0, and the
+ # damped mass answers that motion in this loop's order, length and frame time.
+ rows, cols, height0, worn, cut_cells = transported_motion(meta, cells, request.read_on, verb=verb)
+ read_on |= {"policy": TRANSPORT_POLICY, "cut_cells": cut_cells}
+ else:
+ try:
+ rows, cols, height0, worn = body_motion(cells)
+ except ValueError as exc:
+ raise SystemExit(f"{verb}: {exc}") from exc
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)))
@@ -500,6 +696,10 @@ def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str =
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 {gains[k]:g}); give the region larger radii")
gains = [0.0 if hold else g for g, hold in zip(gains, held)]
+ stretch = None
+ if request.stretch_floor is not None:
+ gains, held, stretch = _keep_floor(request, radii, gains, held, (follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=1.0),
+ follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=1.0)), verb)
# One move per gain: a region's offset is its gain times the answer at gain 1. The strip's `gain`
# is the largest any region moves by, and `dx_px`/`dy_px` and `reach_px` are that gain's.
moves = {g: (follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=g), follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=g))
@@ -511,19 +711,52 @@ def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str =
ratios = [0.0 if hold else fold_ratio(reaches[g], radius) for radius, g, hold in zip(radii, gains, held)]
groups = [([r for r, rg, hold in zip(regions, gains, held) if rg == g and not hold], move) for g, move in moves.items()]
return Answer(request, cells, cols, rows, height0, worn, requested, reach_requested, reach_per_gain, radii, gains, held,
- ratios, moves, reaches, gain, dx, dy, reach, groups)
+ ratios, moves, reaches, gain, dx, dy, reach, groups, read_on, stretch)
+
+
+def _keep_floor(request: Request, radii: list[float], gains: list[float], held: list[bool],
+ move: tuple[np.ndarray, np.ndarray], verb: str) -> tuple[list[float], list[bool], dict[str, Any]]:
+ """The fold rule's gains (`gains`, 0 where `held`) lowered where a region's move would leave a pixel less than
+ `--stretch-floor` of its area (`move`: across and down per cell at gain 1), and the record of it. A region is never
+ raised; one the floor takes under GAIN_MEASURED is held as the fold rule holds one, and the strip is refused when
+ every region is — or, under `--on-fold refuse`, when the floor lowers any."""
+ floor, requested = request.stretch_floor, request.gain
+ per = [stretch_per_gain((rx, ry), *move) for _, _, rx, ry in request.regions]
+ floored = [floor_gain(requested, q, floor) for q, _ in per]
+ lowered = [g if hold else min(g, f) for g, f, hold in zip(gains, floored, held)]
+ by_floor = [not hold and g < rule for g, rule, hold in zip(lowered, gains, held)]
+ if any(by_floor) and request.on_fold == "refuse":
+ least = min(1 - requested * q for (q, _), by in zip(per, by_floor) if by)
+ raise SystemExit(f"{verb}: --gain {requested:g} leaves a moved pixel {least:.3f} of its area, under --stretch-floor {floor:g}; "
+ "lower --gain, pass --on-fold lower or give the region larger radii")
+ now_held = [hold or (by and g < GAIN_MEASURED) for hold, by, g in zip(held, by_floor, lowered)]
+ if all(now_held):
+ k = radii.index(max(radii))
+ raise SystemExit(f"{verb}: --stretch-floor {floor:g} leaves every region held: to keep it each would move under --gain "
+ f"{GAIN_MEASURED:g} (the mass as measured; the largest region at {lowered[k]:g}); lower the floor or give "
+ "the regions larger radii")
+ final = [0.0 if hold else g for g, hold in zip(lowered, now_held)]
+ return final, now_held, {
+ "policy": STRETCH_POLICY, "floor": floor,
+ "regions": [{"per_gain": round(q, 6), "least_cell": cell, "rule_gain": rule, "floor_gain": f, "gain": g, "held": hold,
+ "least_area": 1.0 if hold else round(1 - g * q, 4), "under_measured": not hold and g < GAIN_MEASURED}
+ for (q, cell), rule, f, g, hold in zip(per, gains, floored, final, now_held)],
+ }
def 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,
- on_fold: str = "refuse") -> dict[str, Any]:
- request = read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold)
+ on_fold: str = "refuse", read_on: str | None = None, stretch_floor: float | None = None) -> dict[str, Any]:
+ request = read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, read_on=read_on,
+ stretch_floor=stretch_floor)
loop_dir, name, meta_path, meta = request.loop_dir, request.name, request.meta_path, request.meta
strip_path = request.strip_path
source = request.source_path
if not source.exists():
shutil.copyfile(strip_path, source)
- answer = solve(request, Image.open(source).convert("RGBA"), strip_name=source.name)
+ data = source.read_bytes()
+ answer = solve(request, Image.open(io.BytesIO(data)).convert("RGBA"), strip_name=source.name,
+ strip_sha256=hashlib.sha256(data).hexdigest())
cells = answer.cells
n, (w, h) = len(cells), cells[0].size
out = [answer.moved(k) for k in range(n)]
@@ -586,6 +819,16 @@ def add_request_arguments(parser: argparse.ArgumentParser) -> None:
"named in the record, and the strip is refused only when every region is")
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("--read-on", type=parse_read_on, default=None, metavar="SHA256",
+ help="the sha256 of the strip as cut (before any follow-through) the regions were read on: this loop's own is "
+ "read as without it (relation same); the cut this loop was aligned from (video-cycle-align records it) has "
+ "its reading carried cell for cell (transported); a made cell or a cell geometry nothing records is "
+ "refused uncertain, any other strip no-match. Without it nothing of this is read or written")
+ parser.add_argument("--stretch-floor", type=float, default=None, metavar="D",
+ help="the least area, 0 to under 1, a moved pixel keeps, read by the way each region moves: each region takes "
+ "the largest gain that keeps it, never above the fold rule's; under it the fold rule's handling stands "
+ f"(held under {GAIN_MEASURED:g}, every region held refused; --on-fold refuse refuses). No default: without "
+ "it the fold rule alone")
def add_arguments(parser: argparse.ArgumentParser) -> None:
@@ -596,6 +839,18 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
def fold_notes(record: dict[str, Any], verb: str = VERB) -> list[str]:
"""What to say of a record whose gain was lowered or whose regions were held, a line each."""
fold, notes = record["fold"], []
+ if "stretch" in record: # a floor was asked: each region says what lowered it, the fold or the floor
+ floor = record["stretch"]["floor"]
+ for (cx, cy, rx, ry), entry, folded in zip(record["regions"], record["stretch"]["regions"], fold["regions"]):
+ name = f"--region {cx:g},{cy:g},{rx:g},{ry:g}"
+ if entry["held"]:
+ why = (f"folds at --gain {folded['gain_limit']:g}" if entry["rule_gain"] == 0 else
+ f"keeps --stretch-floor {floor:g} only at --gain {entry['floor_gain']:g}")
+ notes.append(f"{verb}: {name} {why}, under {GAIN_MEASURED:g} (the mass as measured): it is held, and does not move")
+ elif entry["gain"] != record["gain_requested"]:
+ by = f"--stretch-floor {floor:g}" if entry["gain"] < entry["rule_gain"] else "the fold"
+ notes.append(f"{verb}: {name} moves at --gain {entry['gain']:g}, lowered from {record['gain_requested']:g} by {by}")
+ return notes
if "held" in fold["regions"][0]: # the regions took gains of their own
for (cx, cy, rx, ry), entry in zip(record["regions"], fold["regions"]):
name = f"--region {cx:g},{cy:g},{rx:g},{ry:g}"
@@ -615,13 +870,16 @@ 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]
- on_fold=str(kwargs.get("on_fold") or "refuse"))
+ on_fold=str(kwargs.get("on_fold") or "refuse"), read_on=kwargs.get("read_on"), # type: ignore[arg-type]
+ stretch_floor=kwargs.get("stretch_floor")) # type: ignore[arg-type]
fold = result["fold"]
own = "held" in fold["regions"][0] # the regions took gains of their own
for note in fold_notes(result):
print(note, file=sys.stderr)
print(json.dumps({k: result[k] for k in ("strip", "regions", "gain", "gain_requested", "on_fold", "body_bob_px", "reach_px")}
| ({"region_gains": [entry["gain"] for entry in fold["regions"]]} if own else {})
+ | ({"read_on": result["read_on"]["relation"]} if "read_on" in result else {})
+ | ({"stretch_floor": result["stretch"]["floor"]} if "stretch" in result else {})
| ({"board": result["board"]} if "board" in result else {}), ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/video/follow_inspect.py b/sprite_gen/video/follow_inspect.py
index 1e39a3a..d23fb58 100644
--- a/sprite_gen/video/follow_inspect.py
+++ b/sprite_gen/video/follow_inspect.py
@@ -23,6 +23,13 @@ was already written, the strip itself where none was) and solves it with the sam
- `follow-inspect.source.png`, every cell of the strip as cut with each region's carried ellipse ringed;
- `follow-inspect.moved.png`, the same cells as `video-follow` would write them, ringed alike.
+A move does three things to the picture, and the record (schema 2) writes each apart. It stretches it: the least
+area a pixel takes (`jacobian_min`, D). It tilts a line: the move's steepest slope, |offset|·π/(2·smaller radius)
+(`bend`, G, and `bend_deg` = atan G) — the old `fold_ratio` is this number, and at 1 a line tilts 45°. And where
+two regions overlap, the larger move takes over across a curve and the slope jumps there: per pair, the largest
+jump on that curve (`seams`: the norm of the difference of the two moves' gradients, and its angle). A floor on
+the area (`--stretch-floor`) holds D up and lowers G and the seam only with it.
+
The two boards are apart so that whoever says what is inside an ellipse can read the cells as cut alone,
without the answer beside them. The record holds no path, no time and nothing of the machine: the same loop
asked the same way writes the same record. `input_id` does not change when `video-follow` is run on the loop
@@ -52,12 +59,15 @@ from sprite_gen.video import follow
VERB = "video-follow-inspect"
KIND = "video-follow-inspection"
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2 # 2: the bend and the seams beside the least area; the read_on and the stretch floor asked
RECORD, SOURCE_BOARD, MOVED_BOARD = "follow-inspect.json", "follow-inspect.source.png", "follow-inspect.moved.png"
UNKNOWN = "unknown" # what is inside a carried ellipse: the engine does not read it
SCALE_DEFAULT = 2 # board pixels per cell pixel: at 2 or more a ring covers no cell pixel whole
COLUMNS_DEFAULT = 8
PLACES = 4 # decimals of the offsets, ratios and areas: under what two machines' FFTs differ by
+DEGREES = 2 # decimals of an angle
+SEAM_STEP = 0.25 # px between the points along each row where a seam is looked for, before it is found by halving
+SEAM_HALVINGS = 30
GROUND = (128, 128, 128) # under a cell's clear pixels
BETWEEN = (32, 32, 32) # between the cells, and under their numbers
INK = (255, 255, 255) # a cell's number
@@ -92,10 +102,65 @@ def _engine_version() -> str:
def policy() -> dict[str, Any]:
- """The way the motion is read and a region moved: its name and the numbers it is fixed by."""
+ """The way the motion is read and a region moved: its name and the numbers it is fixed by; the way a reading
+ is carried from a cut (`--read-on`) and a floor kept (`--stretch-floor`), by name."""
return {"name": follow.POLICY, "harmonics": follow.HARMONICS, "alpha_solid": follow.ALPHA_SOLID,
"worn": [follow.WORN_FROM, follow.WORN_TO], "gain_measured": follow.GAIN_MEASURED, "gain_step": follow.GAIN_STEP,
- "weight": "cos2"}
+ "weight": "cos2", "transport": follow.TRANSPORT_POLICY, "stretch_floor": follow.STRETCH_POLICY}
+
+
+def _degrees(slope: float) -> float:
+ return round(math.degrees(math.atan(slope)), DEGREES)
+
+
+def _weight_and_gradient(x: np.ndarray, y: np.ndarray, ellipse: tuple[float, float, float, float]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """A region's weight at points (x, y) — cos² of the ellipse's own radius, 0 at its rim and outside — and the
+ weight's gradient there, across and down."""
+ cx, cy, rx, ry = ellipse
+ u, v = (x - cx) / rx, (y - cy) / ry
+ r = np.hypot(u, v)
+ inside = r < 1
+ weight = np.where(inside, np.cos(r * math.pi / 2) ** 2, 0.0)
+ slope = np.where(inside & (r > 0), -(math.pi / 2) * np.sin(math.pi * r) / np.where(r > 0, r, 1.0), 0.0)
+ return weight, slope * u / rx, slope * v / ry
+
+
+def seam(a: tuple[float, float, float, float], b: tuple[float, float, float, float], move_a: tuple[float, float],
+ move_b: tuple[float, float], one_gain: bool) -> tuple[float, list[float]] | None:
+ """Where two overlapping regions, carried into a cell and moved by their own offsets, meet: `video-follow` moves a
+ pixel by the larger of their weighted moves (by the larger weight where they move by one gain), so across the
+ curve where the two are equal the move's gradient jumps from one region's to the other's, and a straight line
+ bends there. The largest jump on that curve — the norm of the difference of the two gradients (each the offset
+ times its weight's gradient) — and the point it is at; None where no such curve is inside both.
+
+ The curve is looked for along rows SEAM_STEP apart, between points SEAM_STEP apart inside both ellipses where the
+ larger move changes hands, and found there by halving."""
+ xs = np.arange(int((max(a[0] + a[2], b[0] + b[2]) - min(a[0] - a[2], b[0] - b[2])) / SEAM_STEP) + 1) * SEAM_STEP + min(a[0] - a[2], b[0] - b[2])
+ ys = np.arange(int((max(a[1] + a[3], b[1] + b[3]) - min(a[1] - a[3], b[1] - b[3])) / SEAM_STEP) + 1) * SEAM_STEP + min(a[1] - a[3], b[1] - b[3])
+ reach_a, reach_b = (1.0, 1.0) if one_gain else (math.hypot(*move_a), math.hypot(*move_b))
+
+ def larger(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ wa, wb = _weight_and_gradient(x, y, a)[0], _weight_and_gradient(x, y, b)[0]
+ return reach_a * wa - reach_b * wb, (wa > 0) & (wb > 0)
+
+ yy, xx = np.meshgrid(ys, xs, indexing="ij")
+ difference, both = larger(xx, yy)
+ above = difference > 0
+ rows, cols = np.nonzero(both[:, :-1] & both[:, 1:] & (above[:, :-1] != above[:, 1:]))
+ if not len(rows):
+ return None
+ lo, hi, y, left = xs[cols], xs[cols + 1], ys[rows], above[rows, cols]
+ for _ in range(SEAM_HALVINGS): # the two ellipses' common part is convex: every midpoint is inside both
+ mid = (lo + hi) / 2
+ same_side = (larger(mid, y)[0] > 0) == left
+ lo, hi = np.where(same_side, mid, lo), np.where(same_side, hi, mid)
+ x = (lo + hi) / 2
+ _, ax, ay = _weight_and_gradient(x, y, a)
+ _, bx, by = _weight_and_gradient(x, y, b)
+ (oax, oay), (obx, oby) = move_a, move_b
+ jump = np.sqrt((oax * ax - obx * bx) ** 2 + (oax * ay - obx * by) ** 2 + (oay * ax - oby * bx) ** 2 + (oay * ay - oby * by) ** 2)
+ k = int(np.argmax(jump))
+ return float(jump[k]), [round(float(x[k]), 3), round(float(y[k]), 3)]
def jacobian(move_x: np.ndarray, move_y: np.ndarray) -> np.ndarray:
@@ -186,10 +251,12 @@ def _png(board: np.ndarray) -> bytes:
def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]], out_dir: Path, *,
gain: float = follow.GAIN_DEFAULT, freq: float = follow.FREQ_DEFAULT, zeta: float = follow.ZETA_DEFAULT,
- on_fold: str = "refuse", scale: int = SCALE_DEFAULT, columns: int = COLUMNS_DEFAULT) -> dict[str, Any]:
+ on_fold: str = "refuse", scale: int = SCALE_DEFAULT, columns: int = COLUMNS_DEFAULT,
+ read_on: str | None = None, stretch_floor: float | None = None) -> dict[str, Any]:
"""The record of what `video-follow` asked the same way does to the loop, written with its two boards into
`out_dir`. The loop directory is read and not written."""
- request = follow.read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, verb=VERB)
+ request = follow.read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, verb=VERB,
+ read_on=read_on, stretch_floor=stretch_floor)
out_dir = out_dir.expanduser().resolve()
if out_dir == request.loop_dir or request.loop_dir in out_dir.parents:
raise SystemExit(f"{VERB}: --out-dir {out_dir} is in the loop directory; an inspection writes nothing there")
@@ -199,7 +266,8 @@ def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]
# The strip as cut, as `video-follow` reads it; it keeps one beside the loop on its first run, and this does not.
strip_path = request.source_path if request.source_path.exists() else request.strip_path
strip_bytes = strip_path.read_bytes()
- answer = follow.solve(request, Image.open(io.BytesIO(strip_bytes)).convert("RGBA"), strip_name=strip_path.name, verb=VERB)
+ answer = follow.solve(request, Image.open(io.BytesIO(strip_bytes)).convert("RGBA"), strip_name=strip_path.name, verb=VERB,
+ strip_sha256=_sha256(strip_bytes))
n, (w, h) = len(answer.cells), answer.cells[0].size
yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
cells, source_tiles, moved_tiles = [], [], []
@@ -211,22 +279,33 @@ def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]
field = follow.move_field(xx, yy, answer.moves_in(k), carry)
area = None if field is None else jacobian(field[1], field[2])
masks = [follow.region_weight(xx, yy, region, carry) > 0 for region in request.regions]
- entries = []
+ entries, offsets = [], []
for i, ((cx, cy, rx, ry), radius, g, hold, mask) in enumerate(zip(request.regions, answer.radii, answer.gains,
answer.held, masks)):
dx, dy = (0.0, 0.0) if hold else (float(answer.moves[g][0][k]), float(answer.moves[g][1][k]))
+ offsets.append((dx, dy))
least, at = _least(area, mask)
+ bend = follow.fold_ratio(math.hypot(dx, dy), radius) # the move's steepest slope: G
entries.append({
"index": i, "ellipse": [round(cx + float(carry[0]), 6), round(cy + float(carry[1]), 6), rx, ry],
"offset_px": [round(dx, PLACES) + 0.0, round(dy, PLACES) + 0.0], "reach_px": round(math.hypot(dx, dy), PLACES),
- "fold_ratio": round(follow.fold_ratio(math.hypot(dx, dy), radius), PLACES),
+ "fold_ratio": round(bend, PLACES),
"jacobian_min": round(least, PLACES), "jacobian_min_at": at,
+ "bend": round(bend, PLACES), "bend_deg": _degrees(bend),
"ellipse_px": int(mask.sum()), "solid_px": int((mask & solid).sum()), "changed_px": int((mask & changed).sum()),
"ownership": UNKNOWN,
})
+ seams = []
+ moving = [i for i, hold in enumerate(answer.held) if not hold]
+ for i in moving:
+ for j in (j for j in moving if j > i):
+ found = seam(*(tuple(entries[m]["ellipse"]) for m in (i, j)), offsets[i], offsets[j], answer.gains[i] == answer.gains[j])
+ if found is not None:
+ seams.append({"regions": [i, j], "jump": round(found[0], PLACES), "deg": _degrees(found[0]), "at": found[1]})
cells.append({
"index": k, "carry_px": [float(carry[0]), float(carry[1])], "changed_px": int(changed.sum()),
"jacobian_min": 1.0 if area is None or not area.size else round(float(area.min()), PLACES), "regions": entries,
+ "seams": seams,
})
source_tiles.append(_tile(answer.cells[k], masks, scale))
moved_tiles.append(_tile(moved, masks, scale))
@@ -245,7 +324,8 @@ def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]
"cut_sha256": cut_sha256, "follow_recorded": "follow" in meta},
"cut": {"frames": n, "w": w, "h": h, "delay_ms": float(meta["delay_ms"])},
"regions": [list(region) for region in request.regions],
- "settings": {"gain": request.gain, "on_fold": request.on_fold, "freq_hz": request.freq, "zeta": request.zeta},
+ "settings": {"gain": request.gain, "on_fold": request.on_fold, "freq_hz": request.freq, "zeta": request.zeta,
+ "read_on": request.read_on, "stretch_floor": request.stretch_floor},
"policy": policy(),
"engine": {"name": "sprite-gen", "version": _engine_version()},
}
@@ -254,18 +334,27 @@ def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]
"strip_sha256": inputs["strip"]["sha256"], "cut_sha256": cut_sha256,
"regions": inputs["regions"], "settings": inputs["settings"],
}))
+ pairs: dict[tuple[int, int], dict[str, Any]] = {}
+ for cell in cells: # per pair of regions, the largest seam of any cell, the first cell on a tie
+ for found in cell["seams"]:
+ key = tuple(found["regions"])
+ if key not in pairs or found["jump"] > pairs[key]["jump"]:
+ pairs[key] = {"regions": found["regions"], "jump": found["jump"], "deg": found["deg"], "cell": cell["index"], "at": found["at"]}
record = {
"kind": KIND, "schema_version": SCHEMA_VERSION, "input_id": input_id, "inputs": inputs,
"follow": answer.record(),
+ "carry_basis": dict(follow.CARRY_BASIS),
"regions": [{
"index": i, "ellipse": list(region), "radius_px": radius, "gain": g, "held": hold,
"gain_limit": None if (limit := follow.gain_limit(answer.reach_per_gain, radius)) is None else round(limit, 3),
"reach_px": max(cell["regions"][i]["reach_px"] for cell in cells),
"fold_ratio": max(cell["regions"][i]["fold_ratio"] for cell in cells),
"jacobian_min": min(cell["regions"][i]["jacobian_min"] for cell in cells),
+ "bend": max(cell["regions"][i]["bend"] for cell in cells), "bend_deg": max(cell["regions"][i]["bend_deg"] for cell in cells),
"changed_px": sum(cell["regions"][i]["changed_px"] for cell in cells),
"ring": list(RINGS[i % len(RINGS)]),
} for i, (region, radius, g, hold) in enumerate(zip(request.regions, answer.radii, answer.gains, answer.held))],
+ "seams": [pairs[key] for key in sorted(pairs)],
"cells": cells,
"boards": {
"scale": scale, "columns": columns, "size": [int(source_board.shape[1]), int(source_board.shape[0])],
@@ -295,7 +384,8 @@ def run(**kwargs: object) -> int:
record = inspect_loop(Path(str(kwargs["loop_dir"])), list(kwargs["region"]), out_dir, # type: ignore[arg-type]
gain=float(kwargs.get("gain", follow.GAIN_DEFAULT)), freq=float(kwargs.get("freq", follow.FREQ_DEFAULT)), # type: ignore[arg-type]
zeta=float(kwargs.get("zeta", follow.ZETA_DEFAULT)), on_fold=str(kwargs.get("on_fold") or "refuse"), # type: ignore[arg-type]
- scale=int(kwargs.get("scale", SCALE_DEFAULT)), columns=int(kwargs.get("columns", COLUMNS_DEFAULT))) # type: ignore[call-overload]
+ scale=int(kwargs.get("scale", SCALE_DEFAULT)), columns=int(kwargs.get("columns", COLUMNS_DEFAULT)), # type: ignore[call-overload]
+ read_on=kwargs.get("read_on"), stretch_floor=kwargs.get("stretch_floor")) # type: ignore[arg-type]
for note in follow.fold_notes(record["follow"], VERB):
print(note, file=sys.stderr)
out_dir = out_dir.expanduser().resolve()
diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.py
index 6422fb8..3f564b5 100644
--- a/tests/video/test_follow_inspect.py
+++ b/tests/video/test_follow_inspect.py
@@ -306,9 +306,10 @@ def test_what_the_answer_is_asked_with_is_in_the_id_and_how_the_boards_are_drawn
lower = others[3]
assert (lower['cells'], lower['regions'], lower['boards']) == (base['cells'], base['regions'], base['boards'])
assert lower['inputs']['settings'] == base['inputs']['settings'] | {'on_fold': 'lower'}
- assert base['inputs']['settings'] == {'gain': 2.5, 'on_fold': 'refuse', 'freq_hz': 2.4, 'zeta': 0.6}
+ assert base['inputs']['settings'] == {'gain': 2.5, 'on_fold': 'refuse', 'freq_hz': 2.4, 'zeta': 0.6, 'read_on': None, 'stretch_floor': None}
assert base['inputs']['policy'] == {'name': follow.POLICY, 'harmonics': 6, 'alpha_solid': 128, 'worn': [0.25, 0.5],
- 'gain_measured': 1.0, 'gain_step': 0.01, 'weight': 'cos2'}
+ 'gain_measured': 1.0, 'gain_step': 0.01, 'weight': 'cos2',
+ 'transport': follow.TRANSPORT_POLICY, 'stretch_floor': follow.STRETCH_POLICY}
# Numbers from a caller are read as the command line's.
for kind in (np.int64, np.float32, int):
given = follow_inspect.inspect_loop(loop_dir, np.asarray([CHEST], dtype=kind), tmp_path/f'kind-{kind.__name__}', gain=kind(2.5) if kind is np.float32 else 2.5)
@@ -441,7 +442,8 @@ def test_the_command_takes_what_video_follow_takes(tmp_path, capsys):
assert (out/FILES[0]).samefile(printed['record']) and printed['input_id'] == record['input_id'] and printed['cells'] == N
assert printed['ownership'] == 'unknown' and printed['held'] == [] and printed['region_gains'] == [region['gain'] for region in record['regions']]
assert [(out/record['boards'][name]['file']).samefile(printed['boards'][name]['path']) for name in ('source', 'moved')] == [True, True]
- assert record['boards']['columns'] == 6 and record['inputs']['settings'] == {'gain': 50.0, 'on_fold': 'lower', 'freq_hz': 2.5, 'zeta': 0.5}
+ assert record['boards']['columns'] == 6 and record['inputs']['settings'] == {'gain': 50.0, 'on_fold': 'lower', 'freq_hz': 2.5, 'zeta': 0.5,
+ 'read_on': None, 'stretch_floor': None}
lines = said.strip().splitlines()
assert lines and all(line.startswith('video-follow-inspect: --gain 50 folds ') and 'lowered to --gain ' in line for line in lines)
assert follow_inspect.main([*asked, '--out-dir', str(tmp_path/'direct')]) == 0