Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
perf(motion-anchor): the fine search reads a row of shifts at once, to the values one patch at a time gives
Soohong Kim76c583d7658e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4437977..1927e9a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased- **New: `video-loop --overlap-wrap off` turns the overlapped wrap off alone.** Each frame the overlapped wrap makes is RIFE's frame read with its sixteen single passes, 34 calls of the binary: where RIFE runs on a CPU that is minutes a frame (on two CPU cores with the augmentation off, 160 to 174 s for a frame of a 960 × 960 synthetic walker), and a wrap refused at its first frame costs minutes a run, so a caller that stops the loop at a deadline stopped it before the loop could fail on its own seam. With `--overlap-wrap off` (the default stays `on`) nothing is read or made for the wrap: the report's `wrap_overlap` says `skipped: "turned off (--overlap-wrap off)"` with no `tries` and `calls` 0, a `warning:` line says the overlapped wrap was not made, and the seam gate refuses the cut as filmed (`video-loop: loop seam ratio … exceeds …`). Nothing else changes: the jump repair, the eased retime and the gate run as with it on, and `--repair off` still turns it off with them.-- **Tests** — `tests/video/test_loop_overlap.py` (with the overlapped wrap off, the front walker whose tail swings on its own beat has nothing read for its wrap, records it turned off and fails on its seam with the warning line; the closed wrap is the same for the default and an explicit `on`; `video-loop`'s argv carries `--overlap-wrap off` with no RIFE installed, `on` is the default and another word is refused).+- **Faster: the motion anchor's fine search reads a row of shifts at once, to the same values.** `video-loop --anchor motion-auto` corrects every two-step cut its seam gate tries before one is taken (up to four, `local_cycle.SEAM_TRIES`) and then the cut it takes, and each correction runs the fine search six times (`motion_anchor._register`: 29 × 57 shifts, two masked regions). The search read each shift's masked patch alone, numpy reducing a patch a pixel row at a time, and on a CPU that was most of a walk's cut. It now gathers the patches of a row of side-by-side shifts together, a block of mask pixels at a time (`motion_anchor.ROW_BLOCK`), and runs the operations one patch read alone takes in the same order — a patch's mean sums its pixels one after the other, its other two sums run over that patch alone — so every cost is the same value, and the match, the report, the cut and the frames are the same bytes as before.+- **Tests** — `tests/video/test_loop_overlap.py` (with the overlapped wrap off, the front walker whose tail swings on its own beat has nothing read for its wrap, records it turned off and fails on its seam with the warning line; the closed wrap is the same for the default and an explicit `on`; `video-loop`'s argv carries `--overlap-wrap off` with no RIFE installed, `on` is the default and another word is refused); `tests/video/test_motion_anchor.py` (the fine search against one patch at a time, kept in the test as it was: the same match, costs, search-boundary measurement or none, compared by repr, on the walker, shifts that lay a region off the frame, the search boundary, noise with a flat half or a hole, and a flat frame, with a region past one block of mask pixels; a 960 cut corrected in under half the time this host takes one patch at a time).## v2.45.1 - An eased stretch that stops the legs is refused; the loop keeps the flow repairdiff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 95c9a87..b21f006 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -981,7 +981,10 @@ far the wrap is from joining the same point of the walk, in frames, the worst ovwhose seam the gate will pass is taken, read as the gate reads it before anything is cut(`loop.seam_on_cells`: the cut corrected as it will be, its wrap over its step on the analysisthumbnail; `step_count.seam_gate.tried`): the correction of one cut can leave a jump at its wrap that- no reading of the clip shows. A part on a beat of its own — a tail, a staff — that closes on no cut of+ no reading of the clip shows. Each reading is a whole correction, six fine searches of the motion+ anchor, and the cut taken is corrected once more, so a gate that tries all four corrects five cuts;+ the search reads a row of its shifts at once, to the values one patch at a time gives ([loop+ review](loop-review.md#explicit-xy-motion-correction)). A part on a beat of its own — a tail, a staff — that closes on no cut oftwo steps leaves every one with a wrap that jumps: the first is cut, still two steps; where the gatewould refuse its wrap, the frames beside it are made again from the clip's frames a cycle apart ([theoverlapped wrap](#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes),diff --git a/docs/loop-review.md b/docs/loop-review.mdindex bb12cdb..7bd65cd 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -232,6 +232,15 @@ is `round((m-v)*(L-1)/L)`. One integer XY ramp runs from zero to that endpoint;it does not pin each frame or remove the original bob. Empty/flat regions andsearch-boundary matches are errors, never a fallback to another anchor.+The fine search (`motion_anchor._register`, 29 × 57 shifts, both regions) reads a row+of side-by-side shifts at once: their masked patches gathered together, a block of+mask pixels at a time (`ROW_BLOCK`), then the operations one patch read alone takes,+in the same order — its mean sums its pixels one after the other, its other two sums+run over that patch alone — so each cost is the same value, and the match, the report+and the frames the same bytes, as reading one patch at a time. `--anchor motion-auto`+corrects every two-step cut its seam gate tries this way, so the search is most of a+walk's cut on a CPU ([loop repair](loop-repair.md#the-step-count--two-steps-read-off-the-clips-crossings)).+Cycle PNGs preserve the supplied keyed pixels (no additional speck removal), withcommon transparent padding to avoid clipping. Strip scaling, GIF palette conversionand output frame-density settings still apply. The sidecar/report records regions,diff --git a/sprite_gen/video/motion_anchor.py b/sprite_gen/video/motion_anchor.pyindex 509ef0e..d22fc72 100644--- a/sprite_gen/video/motion_anchor.py+++ b/sprite_gen/video/motion_anchor.py@@ -16,6 +16,7 @@ from sprite_gen._deps import npREGION_WEIGHTS = (0.7, 0.3)SEARCH_RADIUS = (14, 28)COARSE_SEARCH = 64+ROW_BLOCK = 1024 # mask pixels a block of one row of shifts takes at a time (`_row_costs`)Box = tuple[int, int, int, int]@@ -85,26 +86,94 @@ def _references(image: np.ndarray, regions: list[Box]) -> list[tuple]:return references+def _shift_blocks(moving: np.ndarray, count: int) -> np.ndarray:+ """Every pixel of `moving` with the `count - 1` after it on the flat image, a view (nothing copied): the block of a+ region's pixel holds it under `count` side-by-side shifts, the last shift first, and stays in the pixel's row while+ no shift lays the region past the frame."""+ height, width, channels = moving.shape+ _, pixel, channel = moving.strides+ return np.lib.stride_tricks.as_strided(moving, (height * width - count + 1, count, channels), (pixel, pixel, channel),+ writeable=False)+++def _row_costs(reference: tuple, blocks: np.ndarray, at: np.ndarray, scratch: tuple) -> list[float | None]:+ """The masked NCC cost of the reference at each of a row of side-by-side shifts, the last shift first, None where it+ reads none (a patch of one value, or of no energy).++ `blocks[at]` (`_shift_blocks`) is every shift's patch at once, a mask pixel at a time. Each cost is the one a patch+ read alone has, value for value: the patch's mean sums its pixels one after the other in the mask's row order (a+ reduce over the leading axis, as `patch.mean(axis=0)` does on one patch, carried from block to block), and its two+ other sums each run over that patch alone, laid out as one patch is. A block of ROW_BLOCK pixels at a time keeps the+ work in cache, and the scratch arrays are `_register`'s, made once.+ """+ _, _, feature, norm = reference+ block, laid, squares, products = scratch+ n, count = len(at), blocks.shape[1]+ total = high = low = None+ for s in range(0, n, ROW_BLOCK):+ c = min(ROW_BLOCK, n - s)+ part = block[1:c + 1]+ part[...] = blocks[at[s:s + c]]+ high = part.max(axis=0) if high is None else np.maximum(high, part.max(axis=0))+ low = part.min(axis=0) if low is None else np.minimum(low, part.min(axis=0))+ if total is None:+ total = np.add.reduce(part, axis=0)+ else:+ block[0] = total+ total = np.add.reduce(block[:c + 1], axis=0)+ mean = np.true_divide(total, np.intp(n), out=total, casting="unsafe")+ # The centered patches one after the other, a pixel copied as its bytes.+ pixels = laid[:count * n].reshape(count, n)+ for s in range(0, n, ROW_BLOCK):+ c = min(ROW_BLOCK, n - s)+ part = block[:c]+ part[...] = blocks[at[s:s + c]]+ np.subtract(part, mean, out=part)+ pixels[:, s:s + c] = part.view(laid.dtype)[:, :, 0].T+ patches = pixels.view(block.dtype).reshape(count, n, block.shape[2])+ squares, products = squares[:n], products[:n]+ textured = (high - low).any(axis=1)+ costs = []+ for k in range(count):+ if not textured[k]:+ costs.append(None)+ continue+ patch = patches[k]+ denominator = norm * float(np.sqrt(np.sum(np.multiply(patch, patch, out=squares))))+ costs.append(1 - float(np.sum(np.multiply(feature, patch, out=products)) / denominator)+ if denominator > 1e-12 else None)+ return costs++def _register(references: list[tuple], moving: np.ndarray, center: tuple[int, int]) -> dict:cx, cy = centerrx, ry = SEARCH_RADIUS+ moving = np.ascontiguousarray(moving)+ height, width, channels = moving.shape+ # The shifts that lay every region inside the frame; any other reads nothing.+ lo = max(cx - rx, *(x1 - width for (_, _, x1, _), *_ in references))+ hi = min(cx + rx, *(x0 for (x0, _, _, _), *_ in references))candidates = []- for dy in range(cy - ry, cy + ry + 1):- for dx in range(cx - rx, cx + rx + 1):- costs = []- for (x0, y0, x1, y1), mask, reference, norm in references:- if x0 - dx < 0 or y0 - dy < 0 or x1 - dx > moving.shape[1] or y1 - dy > moving.shape[0]:- break- patch = moving[y0 - dy:y1 - dy, x0 - dx:x1 - dx][mask]- if not np.ptp(patch, axis=0).any():- break- patch = patch - patch.mean(axis=0)- denominator = norm * float(np.sqrt(np.sum(patch * patch)))- if denominator <= 1e-12:- break- costs.append(1 - float(np.sum(reference * patch) / denominator))- if len(costs) == 2:- candidates.append((sum(w * c for w, c in zip(REGION_WEIGHTS, costs)), dx, dy, costs))+ if lo <= hi:+ count = hi - lo + 1+ blocks = _shift_blocks(moving, count)+ # Each region's mask pixels in row order, as offsets on the flat image from its box's corner.+ offsets = [rows * width + cols for rows, cols in (np.nonzero(mask) for _, mask, _, _ in references)]+ most = max(len(at) for at in offsets)+ scratch = (np.empty((ROW_BLOCK + 1, count, channels), moving.dtype),+ np.empty(count * most, np.dtype((np.void, moving.strides[1]))),+ np.empty((most, channels), moving.dtype), np.empty((most, channels), moving.dtype))+ for dy in range(cy - ry, cy + ry + 1):+ if any(y0 - dy < 0 or y1 - dy > height for (_, y0, _, y1), *_ in references):+ continue+ rows = []+ for reference, at in zip(references, offsets):+ x0, y0, _, _ = reference[0]+ rows.append(_row_costs(reference, blocks, (y0 - dy) * width + x0 - hi + at, scratch)[::-1])+ for dx, costs in zip(range(lo, hi + 1), zip(*rows)):+ if None not in costs:+ costs = list(costs)+ candidates.append((sum(w * c for w, c in zip(REGION_WEIGHTS, costs)), dx, dy, costs))if not candidates:raise ValueError("motion anchor found no measurable match inside the search window")candidates.sort()