# h3-game-sprites

Adopt this skill: https://proskills.md/skills/other/gary149-h3-game-sprites-skills-h3-game-sprites

Page: https://proskills.md/skills/other/gary149-h3-game-sprites-skills-h3-game-sprites
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/h3-game-sprites/SKILL.md
size: 9710
sha: 82e8b38538403c7c91674a4bfecbd094c8cb3799
upstream: https://github.com/gary149/h3-game-sprites/blob/main/skills/h3-game-sprites/SKILL.md

````text
---
name: h3-game-sprites
description: Build 2D game sprite sheets by generating motion with MiniMax H3 (Hailuo) video, then cutting the footage into validated chroma-keyed sprite frames - the Mortal Kombat method with a video model instead of filmed actors. Covers the character-still recipe, the idle-pin trick that keeps every move on-model and loopable, per-move clip briefs, frame extraction with keying and numeric QC, seamless walk-cycle detection, and the atlas/render math that keeps a character planted and correctly sized in an engine. Use this whenever the user wants game sprites, a sprite sheet, an animated 2D game character, a fighting/platformer/beat-em-up character, wants to turn AI video into game animation frames, or wants a character animated for a game - even if they never say H3, Hailuo, or "sprite". Also use it for chroma-keying generated video to transparent frames, choosing keyframes from footage, and debugging sprites that jitter, float, sink, or change size between animations.
license: MIT
compatibility: Requires ffmpeg, Python 3 with Pillow and numpy, and an OPENROUTER_API_KEY with credit for video and image generation.
---

# H3 → Game Sprites

Mortal Kombat filmed actors and digitized the footage into sprites. Do the same
with H3 as the actor: one 5 s clip per move (~$0.64), cut down to 8–16 pose
extremes, keyed to transparency, validated with numbers rather than vibes.

Read the **`h3-video`** skill for H3 API mechanics (submitting, polling, frame
pinning, the parallel runner). This skill is the sprite layer on top of it.

## Why a 5-second clip becomes a quarter-second move

The video is source footage, not gameplay. 5 s at 24 fps is ~120 frames; a game
move needs 8–16. H3's slow, deliberate performance is an advantage — more
in-betweens to choose from, less blur per frame. Game timing (startup, active,
recovery) is authored separately in frame data and never inherited from the clip.

## 1. The character still

Generate with `scripts/gen_still.py` (Nano Banana, ~$0.07, `--batch` for parallel
style probes). The prompt must nail four things:

- **Side view facing right, full body including feet, centered, feet planted on
  an invisible ground line.** Cropped feet make a character you cannot anchor.
- **Flat solid magenta `#FF00FF`, edge to edge, no gradient, no cast shadow, no
  ground line.** This is your chroma key.
- **Clean cel: no film grain, no dust, no scratches, no paper texture, no
  vignette.** Beautiful grain destroys the key — say so explicitly, because
  style prompts tend to add it.
- Bold outlines and flat fills survive downscaling to sprite size.

Style choice is a motion question, not a taste question: some styles H3 simply
won't animate. Probe several looks, then spend one clip motion-testing the
finalist before committing to a full move set. Ink wash, claymation, rubber-hose
and photoreal move well; flat vector and paper cutouts risk freezing.

Extra end-pose stills (KO, downed) are generated from the idle as a reference
image. Say **"EXACTLY ONE character, completely alone, no second figure, no
duplicate"** — asking for "knocked out" while showing a standing reference
reliably returns both a standing and a lying character in one frame.

## 2. Clip briefs, one per move

**The idle pin.** Every move clip sets `first_frame = last_frame = the idle
still`. This buys three things at once: the character cannot drift off-model
(H3 keeps identity only when it is anchored in a locked frame), the animation
returns exactly to neutral so it loops, and moves chain cleanly in a state
machine. Moves that end elsewhere (KO) pin their own end frame instead.

Use the beat structure from `h3-video`, plus these sprite-specific guards —
each one was learned by getting the opposite:

```
The character's hands and feet stay their normal size at all times - NO
ballooning, NO growing fists; limbs may stretch but hands and feet keep
constant scale.
Camera locked on a tripod, no zoom, no pan, no cut.
The background stays a perfectly flat uniform solid magenta at all times - no
gradient, no cast shadow, no ground line, nothing else enters the frame.
The character stays centered on the same ground level and does not travel
across the frame; everything not described stays static.
Audio: SFX only. NEVER generate music, melody, score or musical tones.
```

- **Walks are briefed in place** ("as if on a treadmill") — the engine moves the
  transform, so a sprite that travels fights the engine.
- Hit-stun and KO react to "an invisible blow", since no opponent is in frame.
- Cartoon models love exaggeration. Unforbidden, fists balloon on impact frames.

A basic set — idle, walk forward, walk back, jump, crouch, punch, kick, block,
hit-stun, KO — is ~$6.50 and submits as one parallel batch. Consider skipping
the back-walk clip and playing the forward cycle in reverse (a classic 2D
fighter trick): asked for a backward stride, H3 tends to give a wary sway.

## 3. Decompose and validate

```bash
python3 scripts/sprite_cut.py clips/v_punch.mp4 sprites/punch --frames 12
python3 scripts/sprite_cut.py clips/v_walk.mp4  sprites/walk  --frames 8 --loop
```

Writes `keyed/*.png` (RGBA), `strip.png`, `anim.gif` (pose preview at source
pacing) and `report.json`.

**Keyframes are picked by cumulative motion arc-length** — equal steps of
accumulated frame-to-frame change, so frames concentrate where the action is.
Uniform sampling looks mushy, and picking local motion maxima over-samples the
idle bounce at the head of the clip.

**`--loop` for cycles.** Whole-clip picks include the start-up and the settle
back to idle, which is exactly why a walk visibly resets instead of looping.
Loop mode finds the closest-matching frame pair inside the sustained middle of
the clip and samples between them, giving a true seam.

Read the summary before trusting anything:

| metric | what it tells you |
|---|---|
| `worst_bg_purity` | ~1.0 means every pixel is confidently background or character; lower means key leak |
| `loop_diff` | move returns to its start pose (or, in loop mode, the cycle seam) |
| `first_vs_last_baseline` | feet end where they began, in px |
| `baseline_drift_px` | feet wandering — large is right for a jump, suspicious for a stance |

Despill note: do not blend the fringe toward the off-channel, which visibly
tints the character. Clamp the key channels against the off-channel instead, as
the script does.

## 4. Atlas: one global scale

**The trap.** Scaling each frame to a fixed on-screen height is the obvious
thing and it is wrong: a crouch or jump tuck has a *smaller* bounding box, so
per-frame normalization renders it **bigger** than standing. Derive one scale
from the idle frame and apply it to every frame of every move.

```bash
python3 scripts/build_atlas.py sprites/ atlas.json \
    --moves idle,walk,jump,crouch,punch,kick,block --ref idle --height 340
```

Frames are stored trimmed, at global scale, with offsets to a shared anchor:
`footOffset` (feet vs the ground line), `anchorOffset` (stance-center column
inside the crop), `driftX` (this frame's drift from the canonical center).

**The anchor X comes from the ankle-region centroid, not the bbox center** — a
big arm or tail swing moves the bbox, and centering on it makes the character
slide sideways between poses.

The script prints per-move on-screen heights. Crouch and jump-tuck must be
*shorter* than idle; if they are taller, per-frame scaling has crept back in.

## 5. Render

```js
ctx.translate(x + f.driftX, GROUND_Y + jumpY);
ctx.scale(facing, 1);              // player 2 is a flip, never a generative mirror
const foot = state === 'jump' ? 0 : f.footOffset;   // engine arc supplies the lift
ctx.drawImage(img, -f.anchorOffset, foot - img.height, f.w, f.h);
```

Two real bugs live in those four lines. `drawImage`'s y is the **top** edge
while `footOffset` positions the **feet**, so dropping `- img.height` sinks the
character through the floor. And if the engine authors a jump arc, adding the
frame's baked-in air offset on top double-lifts it.

Frame data stays separate from pixels — durations per frame, a loop flag, and
for held states an enter/hold/release split so a key can be held:

```js
punch:  { frames:[0..11], durations:[35,35,45,50,...], loop:false }
crouch: { enterFrames:[0,1,2], holdFrame:3, releaseFrames:[4..7], hold:true }
```

Roughly 35–70 ms per frame for attacks (fast startup, slower recovery) against
~150 ms for idle. Tune feel here; never regenerate video for timing.

## 6. Verify with pixels, in a browser

Asserting on atlas metadata is not verification — it passes happily while the
render is broken. Measure the character on the actual canvas:

```js
// drive the loop deterministically: requestAnimationFrame freezes in unfocused tabs
const drive = (n, codes) => {
  for (const c in keys) delete keys[c];
  for (const c of codes) keys[c] = true;
  for (let i = 0; i < n; i++) tick(g, keys, 16.7);
  draw();
};
// then getImageData, find the non-background bbox, compare against GROUND_Y
```

Confirm: idle feet sit on the ground line, crouch is shorter *and still
planted*, jump lifts without resizing, landing returns to exactly idle.

Chrome extensions cannot open `file://` URLs — serve the page with
`python3 -m http.server` and drive localhost.

## Costs and habits

Still ~$0.07, 5 s clip $0.64, a 10-move fighter ~$7, failed jobs free. Retakes
are per-move, never the whole set, so diagnose before rerolling: a wrong-looking
character means the locked frames were wrong, not the prompt. Keep superseded
assets rather than deleting them — an earlier take is often the only surviving
copy of a pose you end up wanting back.
````

## File: skills/h3-game-sprites/scripts/build_atlas.py
size: 4024
sha: 96422277be534a9cd7c26bf81a5c9c60f613fffa
upstream: https://github.com/gary149/h3-game-sprites/blob/main/skills/h3-game-sprites/scripts/build_atlas.py

```text
#!/usr/bin/env python3
"""Pack keyed sprite frames into one atlas at a SINGLE global scale.

    python3 build_atlas.py sprites/ atlas.json --moves idle,walk_fwd,punch \
        --ref idle --height 340

The bug this exists to prevent: scaling each frame to a fixed on-screen height.
A crouch or a jump tuck has a SMALLER bounding box, so per-frame normalization
renders it BIGGER than the standing pose. One scale is derived from the
reference (idle) frame and applied to every frame of every move; poses then
differ in size the way they should.

Each frame carries offsets to a shared anchor instead of being pre-centered:
  footOffset   feet position relative to the reference ground line
  anchorOffset the stance-center column inside this crop
  driftX       this frame's stance-center drift from the canonical one

Draw with (canvas):
  ctx.translate(x + f.driftX, GROUND_Y + jumpY);
  ctx.scale(facing, 1);
  ctx.drawImage(img, -f.anchorOffset, f.footOffset - img.height, f.w, f.h);
drawImage's y is the TOP edge, so subtracting the height is what puts the FEET
on footOffset. Omit it and the character sinks through the floor.
"""
import argparse, base64, io, json, os
import numpy as np
from PIL import Image

def stats(im):
    """bbox, feet baseline, and a stance anchor x taken from the centroid of the
    bottom ~22% of the mask (ankles) rather than the bbox center -- otherwise a
    big arm or tail swing shifts the whole character sideways between poses."""
    a = np.asarray(im)[..., 3] > 0
    ys, xs = np.nonzero(a)
    bbox = (int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1)
    thresh = ys.max() - int((ys.max() - ys.min()) * 0.22)
    leg = ys >= thresh
    return bbox, int(ys.max()), float(xs[leg].mean() if leg.any() else xs.mean())

def picks_for(d):
    rep = json.load(open(os.path.join(d, "report.json")))["summary"]
    return rep["picked"]

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("sprites_dir")
    ap.add_argument("out_json")
    ap.add_argument("--moves", required=True, help="comma-separated move names")
    ap.add_argument("--ref", default="idle", help="move whose first frame sets the scale")
    ap.add_argument("--height", type=int, default=340, help="on-screen px for the reference pose")
    args = ap.parse_args()

    moves = [m.strip() for m in args.moves.split(",") if m.strip()]
    frame_path = lambda m, i: os.path.join(args.sprites_dir, m, "keyed", f"f{i + 1:04d}.png")

    ref_i = picks_for(os.path.join(args.sprites_dir, args.ref))[0]
    ref_bbox, ref_base, ref_anchor = stats(Image.open(frame_path(args.ref, ref_i)))
    scale = args.height / (ref_bbox[3] - ref_bbox[1])
    print(f"reference {args.ref}[{ref_i}]: scale {scale:.4f}, ground {ref_base}, anchor_x {ref_anchor:.1f}")

    atlas = {}
    for m in moves:
        frames = []
        for i in picks_for(os.path.join(args.sprites_dir, m)):
            im = Image.open(frame_path(m, i))
            bbox, base, anchor = stats(im)
            crop = im.crop(bbox)
            w, h = max(1, round(crop.width * scale)), max(1, round(crop.height * scale))
            buf = io.BytesIO()
            crop.resize((w, h), Image.LANCZOS).save(buf, "PNG", optimize=True)
            frames.append({
                "b64": base64.b64encode(buf.getvalue()).decode(), "w": w, "h": h,
                "footOffset": round((base - ref_base) * scale),
                "anchorOffset": round((anchor - bbox[0]) * scale),
                "driftX": round((anchor - ref_anchor) * scale),
            })
        atlas[m] = frames
        hs = [f["h"] for f in frames]
        print(f"{m:12s} {len(frames):3d} frames   on-screen height {min(hs)}-{max(hs)}px")

    json.dump(atlas, open(args.out_json, "w"))
    print(f"\nwrote {args.out_json} ({os.path.getsize(args.out_json) // 1024} KB)")
    print(f"sanity: crouch/tuck poses must be SHORTER than {args.ref} "
          f"({args.height}px). Taller means per-frame scaling crept back in.")

if __name__ == "__main__":
    main()
```

## File: skills/h3-game-sprites/scripts/gen_still.py
size: 3681
sha: c552952284294d1346f091d3d9f503cf8add331e
upstream: https://github.com/gary149/h3-game-sprites/blob/main/skills/h3-game-sprites/scripts/gen_still.py

```text
#!/usr/bin/env python3
"""Generate a character/pose still with Nano Banana on OpenRouter.

    python3 gen_still.py "a boxer, side view ..." out.jpg
    python3 gen_still.py "$(cat pose.txt)" ko.jpg --ref idle.jpg --aspect 3:4
    python3 gen_still.py --batch shots.json --outdir probes/

--ref attaches reference images (style/identity); repeat for several. Batch mode
takes [{"name": ..., "prompt": ..., "refs": [...]}, ...] and runs in parallel,
which is how you probe many styles at once for the price of a coffee.

Reads OPENROUTER_API_KEY. ~$0.07/image. Nano Banana returns JPEG bytes even when
you ask for PNG, so the extension is chosen by sniffing the magic bytes.
"""
import argparse, base64, json, os, sys, urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed

API = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "google/gemini-3.1-flash-image"

def durl(path):
    raw = open(path, "rb").read()
    mime = "image/jpeg" if raw[:3] == b"\xff\xd8\xff" else "image/png"
    return f"data:{mime};base64," + base64.b64encode(raw).decode()

def generate(prompt, refs, aspect, key):
    content = [{"type": "text", "text": prompt}]
    for r in refs or []:
        content.append({"type": "image_url", "image_url": {"url": durl(r)}})
    body = json.dumps({
        "model": MODEL, "modalities": ["image", "text"],
        "image_config": {"aspect_ratio": aspect},
        "messages": [{"role": "user", "content": content}],
    }).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    last = None
    for _ in range(3):
        try:
            with urllib.request.urlopen(req, timeout=180) as r:
                resp = json.load(r)
            url = resp["choices"][0]["message"]["images"][0]["image_url"]["url"]
            return base64.b64decode(url.split(",", 1)[1])
        except Exception as e:
            last = e
    raise RuntimeError(f"generation failed: {last}")

def save(data, path):
    root, ext = os.path.splitext(path)
    if not ext:
        ext = ".jpg" if data[:3] == b"\xff\xd8\xff" else ".png"
    path = root + ext
    open(path, "wb").write(data)
    return path

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("prompt", nargs="?")
    ap.add_argument("out", nargs="?")
    ap.add_argument("--ref", action="append", default=[])
    ap.add_argument("--aspect", default="3:4")
    ap.add_argument("--batch", help="JSON list of {name, prompt, refs}")
    ap.add_argument("--outdir", default=".")
    args = ap.parse_args()
    key = os.environ.get("OPENROUTER_API_KEY")
    if not key:
        raise SystemExit("OPENROUTER_API_KEY not set")

    if args.batch:
        shots = json.load(open(args.batch))
        os.makedirs(args.outdir, exist_ok=True)
        fails = []
        with ThreadPoolExecutor(max_workers=6) as ex:
            futs = {ex.submit(generate, s["prompt"], s.get("refs"),
                              s.get("aspect", args.aspect), key): s["name"] for s in shots}
            for fut in as_completed(futs):
                name = futs[fut]
                try:
                    p = save(fut.result(), os.path.join(args.outdir, name))
                    print(f"OK   {name} -> {p}")
                except Exception as e:
                    print(f"FAIL {name}: {e}")
                    fails.append(name)
        sys.exit(1 if fails else 0)

    if not (args.prompt and args.out):
        raise SystemExit("need PROMPT and OUT, or --batch")
    print("wrote", save(generate(args.prompt, args.ref, args.aspect, key), args.out))

if __name__ == "__main__":
    main()
```

## File: skills/h3-game-sprites/scripts/sprite_cut.py
size: 7259
sha: a5c78168b81eadff4874fb389f82eb49fae5734e
upstream: https://github.com/gary149/h3-game-sprites/blob/main/skills/h3-game-sprites/scripts/sprite_cut.py

```text
#!/usr/bin/env python3
"""Decompose a generated video clip into validated, chroma-keyed sprite frames.

    python3 sprite_cut.py clip.mp4 out/ --frames 12
    python3 sprite_cut.py walk.mp4 out/ --frames 8 --loop      # seamless cycle

Writes out/keyed/*.png (RGBA), strip.png, strip_preview.jpg, anim.gif and
report.json (per-frame metrics + summary). Read the summary before trusting
anything: worst_bg_purity ~1.0 means the key is clean, loop_diff near 0 means
the move returns to its starting pose.
"""
import argparse, json, os, subprocess
import numpy as np
from PIL import Image

def extract(video, tmpdir):
    os.makedirs(tmpdir, exist_ok=True)
    subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", video,
                    os.path.join(tmpdir, "f%04d.png")], check=True)
    return sorted(f for f in os.listdir(tmpdir) if f.endswith(".png"))

def key_frame(img, color):
    """RGBA with the backdrop removed, plus the background mask.

    Despill clamps the key channels against the off-channel rather than
    blending toward it -- blending visibly tints the character.
    """
    a = np.asarray(img.convert("RGB")).astype(np.float32)
    r, g, b = a[..., 0], a[..., 1], a[..., 2]
    if color == "magenta":
        score, off = r + b - 2 * g, g
        bg = (score > 120) & (r > 90) & (b > 90)
    else:  # green
        score, off = 2 * g - r - b, np.maximum(r, b)
        bg = (score > 120) & (g > 90)
    alpha = np.where(bg, 0, 255).astype(np.uint8)
    cap = off * 1.18 + 30
    if color == "magenta":
        a[..., 0], a[..., 2] = np.minimum(r, cap), np.minimum(b, cap)
    else:
        a[..., 1] = np.minimum(g, cap)
    out = np.dstack([a.clip(0, 255).astype(np.uint8), alpha])
    return Image.fromarray(out, "RGBA"), bg

def metrics(rgba, bgmask):
    al = np.asarray(rgba)[..., 3] > 0
    ys, xs = np.nonzero(al)
    if len(xs) == 0:
        return None
    return {
        "baseline": int(ys.max()),            # lowest opaque row = feet
        "top": int(ys.min()),
        "cx": round(float(xs.mean()), 1),
        "height": int(ys.max() - ys.min()),
        "coverage": round(float(al.mean()), 4),
        "bg_purity": round(float(bgmask.mean() + al.mean()), 4),
    }

def pick_arclength(energy, n):
    """Equal steps of cumulative motion, so frames land on pose extremes.
    Uniform sampling looks mushy; local-maxima picking over-samples idle."""
    cum = np.cumsum(energy)
    if cum[-1] <= 0:
        return sorted(set(np.linspace(0, len(energy) - 1, n).round().astype(int).tolist()))
    targets = np.linspace(0, cum[-1], n)
    return sorted({int(np.argmin(np.abs(cum - t))) for t in targets}
                  | {0, len(energy) - 1})

def pick_loop(small, n, lo_frac=0.2, hi_frac=0.85, min_gap=12, max_gap=45):
    """Find the frame pair that matches most closely (the seam of a cycle) and
    sample inside it. Whole-clip picks include the start-up and the settle back
    to idle, which is what makes a walk visibly reset instead of loop."""
    total = len(small)
    idxs = range(int(total * lo_frac), int(total * hi_frac))
    best = None
    for i in idxs:
        for j in idxs:
            if not (min_gap <= j - i <= max_gap):
                continue
            d = float(np.abs(small[i] - small[j]).mean())
            if best is None or d < best[0]:
                best = (d, i, j)
    if best is None:
        return None, sorted(set(np.linspace(0, total - 1, n).round().astype(int).tolist()))
    d, i, j = best
    return {"i": i, "j": j, "diff": round(d, 3)}, \
        sorted({i + round(k * (j - i) / n) for k in range(n)})

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("outdir")
    ap.add_argument("--frames", type=int, default=12)
    ap.add_argument("--loop", action="store_true", help="extract a seamless cycle (walks)")
    ap.add_argument("--key", default="magenta", choices=["magenta", "green"])
    args = ap.parse_args()

    od = args.outdir
    raw, keyed = os.path.join(od, "raw"), os.path.join(od, "keyed")
    os.makedirs(keyed, exist_ok=True)
    names = extract(args.video, raw)

    report, small = [], []
    for i, n in enumerate(names):
        rgba, bgmask = key_frame(Image.open(os.path.join(raw, n)), args.key)
        rgba.save(os.path.join(keyed, n))
        m = metrics(rgba, bgmask)
        m["frame"] = i
        report.append(m)
        s = rgba.resize((max(1, rgba.width // 8), max(1, rgba.height // 8)))
        small.append(np.asarray(s).astype(np.int16))

    energy = [0.0] + [float(np.abs(small[i] - small[i - 1]).mean())
                      for i in range(1, len(small))]
    for m, e in zip(report, energy):
        m["motion"] = round(e, 2)

    loop_info = None
    if args.loop:
        loop_info, picks = pick_loop(small, args.frames)
    else:
        picks = pick_arclength(energy, args.frames)
    picks = picks[:args.frames]

    summary = {
        "frames": len(names), "picked": picks, "loop": loop_info,
        "baseline_drift_px": max(m["baseline"] for m in report) - min(m["baseline"] for m in report),
        "centroid_drift_px": round(max(m["cx"] for m in report) - min(m["cx"] for m in report), 1),
        "height_var_px": max(m["height"] for m in report) - min(m["height"] for m in report),
        # in loop mode this is the cycle seam (frame i vs frame j); otherwise
        # it is how closely the move returns to the pose it started from
        "loop_diff": round(loop_info["diff"] if loop_info
                           else float(np.abs(small[picks[0]] - small[picks[-1]]).mean()), 2),
        "worst_bg_purity": min(m["bg_purity"] for m in report),
        "first_vs_last_baseline": abs(report[picks[0]]["baseline"] - report[picks[-1]]["baseline"]),
    }

    # strip: uniform cells, feet on a common baseline
    cells = [Image.open(os.path.join(keyed, names[i])) for i in picks]
    boxes = [c.getbbox() for c in cells]
    cw = max(b[2] - b[0] for b in boxes) + 16
    ch = max(b[3] - b[1] for b in boxes) + 16
    strip = Image.new("RGBA", (cw * len(cells), ch), (0, 0, 0, 0))
    for j, (c, b) in enumerate(zip(cells, boxes)):
        crop = c.crop(b)
        strip.paste(crop, (j * cw + (cw - crop.width) // 2, ch - 8 - crop.height), crop)
    strip.save(os.path.join(od, "strip.png"))
    prev = Image.new("RGB", strip.size, (24, 26, 32))
    prev.paste(strip, (0, 0), strip)
    prev.thumbnail((1800, 1800))
    prev.save(os.path.join(od, "strip_preview.jpg"), quality=88)

    # GIF at source pacing (a preview of poses, not of game timing)
    gif, durs = [], []
    for j, i in enumerate(picks):
        f = Image.open(os.path.join(keyed, names[i]))
        bg = Image.new("RGB", f.size, (24, 26, 32))
        bg.paste(f, (0, 0), f)
        bg.thumbnail((420, 560))
        gif.append(bg)
        nxt = picks[j + 1] if j + 1 < len(picks) else picks[0] + len(names)
        durs.append(max(1, (nxt - i)) * 1000 // 24)
    gif[0].save(os.path.join(od, "anim.gif"), save_all=True,
                append_images=gif[1:], duration=durs, loop=0)

    json.dump({"summary": summary, "frames": report},
              open(os.path.join(od, "report.json"), "w"), indent=1)
    print(json.dumps(summary, indent=1))

if __name__ == "__main__":
    main()
```

## File: README.md
upstream: https://github.com/gary149/h3-game-sprites/blob/main/README.md

````text
# h3-game-sprites

An [Agent Skill](https://agentskills.io) for turning AI-generated video into 2D game sprite sheets.

Mortal Kombat (1992) filmed actors and digitized the footage into sprites. This does the
same thing with a video model as the actor: one short clip per move, cut down to its pose
extremes, chroma-keyed to transparency, and packed into an atlas you can drop into an
engine. A character with eight moves costs about $5 and lands in an afternoon.

<p align="center">
  <img src="examples/punch.gif" width="220" alt="Animated punch, cut from a single generated clip">
</p>

<p align="center">
  <img src="examples/punch-strip.jpg" width="760" alt="Twelve keyed sprite frames selected from 124 video frames">
</p>

## What it covers

- The character-still recipe: side view, planted feet, flat magenta backdrop, and the
  "no grain, no dust, no vignette" clause that keeps the chroma key clean.
- The **idle pin**: setting a move clip's first *and* last frame to the same idle still, so
  the character cannot drift off-model, every animation returns to neutral, and moves chain
  in a state machine.
- Clip briefs, including the guards that stop cartoon models ballooning fists on impact and
  the in-place ("treadmill") walk phrasing that keeps the engine in charge of movement.
- Frame extraction, keying with a despill that does not tint the character, and keyframe
  selection by cumulative motion arc-length rather than uniform sampling.
- Seamless walk-cycle detection, because whole-clip keyframes include the start-up and the
  settle back to idle, which is what makes a walk visibly reset instead of loop.
- The atlas and rendering math: one global scale (never per-frame normalization), anchoring
  from the ankle centroid, and the `drawImage` offset that decides whether your character
  stands on the floor or sinks through it.

## Install

Copy the skill folder into wherever your agent looks for skills. For Claude Code:

```bash
git clone https://github.com/gary149/h3-game-sprites
cp -R h3-game-sprites/skills/h3-game-sprites ~/.claude/skills/
```

The format is portable across [skills-compatible agents](https://agentskills.io/clients);
adjust the destination directory to match your client.

## Requirements

The local half of the pipeline (keying, keyframe selection, atlas building) needs only
`ffmpeg` and Python 3 with `Pillow` and `numpy`. `sprite_cut.py` and `build_atlas.py` take
an ordinary video file, so they work regardless of what produced it.

Generation needs a video model and an image model, and neither is pinned to one vendor.
H3 / Hailuo 3 is served by aggregators such as OpenRouter and fal, and by MiniMax directly.
The character still can come from whichever image model you prefer, or from an illustrator,
as long as it follows the pose and flat-backdrop recipe in the skill. Budget roughly
$0.60-0.70 per five-second clip and a few cents per still, varying by provider.

The bundled `gen_still.py` is a convenience, not a constraint: it defaults to Nano Banana
(`google/gemini-3.1-flash-image`) through OpenRouter and reads `OPENROUTER_API_KEY`. Point
the endpoint and model constants at the top of the file somewhere else, or skip the script
and bring your own still.

## Scripts

| Script | Does |
| --- | --- |
| `scripts/gen_still.py` | Generate character and pose stills, with reference images and a parallel batch mode for style probes |
| `scripts/sprite_cut.py` | Extract, chroma-key, pick keyframes, emit a strip, a GIF and a metrics report; `--loop` finds a seamless cycle |
| `scripts/build_atlas.py` | Pack frames into an atlas at one global scale with shared anchors |

Each runs standalone, so the pipeline is usable without an agent driving it:

```bash
python3 scripts/sprite_cut.py clips/punch.mp4 sprites/punch --frames 12
python3 scripts/sprite_cut.py clips/walk.mp4  sprites/walk  --frames 8 --loop
python3 scripts/build_atlas.py sprites/ atlas.json --moves idle,walk,punch --ref idle
```

## Verifying, not vibing

Every stage emits numbers you can check: key purity per frame, how closely a move returns
to its starting pose, feet drift, and on-screen pose heights. The guidance leans on this
hard, because the failure modes here are visual and quiet. A sprite that renders at the
wrong scale, or one that hangs below the floor, will pass any assertion written against
atlas metadata alone. Measure the rendered canvas.

## License

MIT
````
