Files
windroost/tools/pack_animation_strip.py
T
wushenghua a0c590deec feat: add animated units, real touch input and the runtime economy loop
Continues the MVP work from the UI and numbers baseline.

Animation. The frame runs were already in the repository but had never been
packed for runtime use. pack_animation_strip.py now derives one shared scale
and one shared foot line from the union of every frame in a state, so the
character does not jitter between frames; H01 idle/attack, EG01 idle/hit and
B01 idle/hit are packed as transparent fixed-grid atlases. UnitView plays
them with the node origin on the foot line, loops idle, plays hit once and
falls back, and flashes on damage. Content-to-art bindings live in the
content fixture, so no character id is hardcoded in the HUD.

Touch. The previous HUD used gui_input callbacks, which is not proof of a
mobile input path. run_touch_test.sh now feeds InputEventScreenTouch through
Input.parse_input_event and checks that taps on the tap toggle, an enemy card
and the storm button produce the right events on the right tick. It also
caught a real bug: Godot emulates mouse presses from touches, so one tap was
firing both handlers; enemy taps are now debounced.

Economy. The paper model had the reward and upgrade curves but the runtime
only subtracted gold from a balance that was always zero. The scene now owns
permanent progress: victory grants the reward from the shared rules, upgrades
cost a growing amount, hero DPS rises per level, and the next battle is
created with the upgraded roster DPS. run_economy_loop_test.sh proves four
N01 clears pay for the first upgrade and that duplicate grants and losses
behave correctly. The economy pacing was left at four wins rather than
weakening it to satisfy the test.

tools/run_p2_checks.sh now runs 11 gates; all pass. PRODUCTION/38 records
P2-IMP-02/03 and P2-BAT-02 as PASS. Remaining P2 holds: profiler/visual
limit, shield-break and ultimate VFX, real-device safe area and performance.
2026-11-16 23:30:49 +08:00

153 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Pack an animation state into a fixed-grid, foot-aligned runtime atlas.
Why this exists
---------------
`chroma_key_atlas.py` normalises one cell at a time, so it is right for a
single frame per state but wrong for animation: every frame would get its own
scale and its own vertical placement, and the character would jitter on every
frame change.
This packer takes all frames of one state and gives them:
* one shared scale, derived from the union of every frame's alpha box;
* one shared foot line, so the character's feet never move between frames;
* a fixed cell grid, so the runtime can address frames by index.
The output atlas keeps transparency, so the runtime can composite it directly
over the battle background with nearest filtering.
Usage:
python3 tools/pack_animation_strip.py \
--character H01 --state idle \
--frames PRODUCTION/source/sprite_runs/H01/run/frames/idle \
--output-dir PRODUCTION/source/pixel_pilot/characters/H01
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from typing import Dict, List, Sequence, Tuple
from PIL import Image
FRAME_ORDER = ("frame-0", "frame-1", "frame-2", "frame-3", "frame-4", "frame-5", "frame-6")
def frame_files(folder: Path) -> List[Path]:
files = [item for item in folder.iterdir() if item.suffix.lower() == ".png"]
def sort_key(path: Path) -> Tuple[int, str]:
digits = "".join(ch for ch in path.stem if ch.isdigit())
return (int(digits) if digits else 999, path.stem)
return sorted(files, key=sort_key)
def union_alpha_box(images: Sequence[Image.Image]) -> Tuple[int, int, int, int]:
union: List[int] = [0, 0, 0, 0]
for image in images:
box = image.getchannel("A").getbbox()
if box is None:
continue
union[0] = min(union[0], box[0])
union[1] = min(union[1], box[1])
union[2] = max(union[2], box[2])
union[3] = max(union[3], box[3])
if union[2] <= union[0] or union[3] <= union[1]:
raise ValueError("no visible pixels in the supplied frames")
return (union[0], union[1], union[2], union[3])
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--character", required=True)
parser.add_argument("--state", required=True)
parser.add_argument("--frames", required=True, type=Path, help="directory holding the frame PNGs")
parser.add_argument("--output-dir", required=True, type=Path)
parser.add_argument("--canvas", type=int, default=128, help="logical cell size in pixels")
parser.add_argument("--fit", type=float, default=0.86, help="maximum art ratio inside the cell")
parser.add_argument("--fps", type=int, default=8)
parser.add_argument("--loop", action="store_true")
parser.add_argument("--resample", choices=("nearest", "lanczos"), default="nearest")
args = parser.parse_args()
files = frame_files(args.frames)
if not files:
raise SystemExit(f"no frame PNGs found in {args.frames}")
images = [Image.open(path).convert("RGBA") for path in files]
union = union_alpha_box(images)
canvas = args.canvas
art_w = union[2] - union[0]
art_h = union[3] - union[1]
scale = min((canvas * args.fit) / art_w, (canvas * args.fit) / art_h)
scaled_size = (max(1, round(art_w * scale)), max(1, round(art_h * scale)))
foot_y = round(canvas * 0.88)
resample = (
Image.Resampling.NEAREST
if args.resample == "nearest"
else Image.Resampling.LANCZOS
)
count = len(images)
atlas = Image.new("RGBA", (canvas * count, canvas), (0, 0, 0, 0))
entries: List[Dict[str, object]] = []
for index, (path, image) in enumerate(zip(files, images)):
cropped = image.crop(union)
resized = cropped.resize(scaled_size, resample)
offset_x = (canvas - scaled_size[0]) // 2
offset_y = foot_y - scaled_size[1]
frame = Image.new("RGBA", (canvas, canvas), (0, 0, 0, 0))
frame.alpha_composite(resized, (offset_x, offset_y))
atlas.alpha_composite(frame, (index * canvas, 0))
entries.append({
"name": path.stem,
"atlas_rect": [index * canvas, 0, canvas, canvas],
"cell_offset": [offset_x, offset_y],
"size": list(scaled_size),
})
args.output_dir.mkdir(parents=True, exist_ok=True)
name = f"{args.character}_{args.state}_anim"
atlas_path = args.output_dir / f"{name}.png"
atlas.save(atlas_path)
digest = hashlib.sha256(atlas_path.read_bytes()).hexdigest()
manifest = {
"schema": 1,
"status": "runtime",
"character_id": args.character,
"state": args.state,
"frame_count": count,
"fps": args.fps,
"loop": bool(args.loop),
"cell_size": [canvas, canvas],
"atlas_size": list(atlas.size),
"logical_canvas": [canvas, canvas],
"fit": args.fit,
"scale": round(scale, 6),
"foot_y": foot_y,
"resample": args.resample,
"source_frames": [str(path) for path in files],
"union_alpha_bbox": list(union),
"atlas_sha256": digest,
"frames": entries,
}
manifest_path = args.output_dir / f"{name}.manifest.json"
manifest_path.write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(
f"packed {args.character}/{args.state}: {count} frames, "
f"cell {canvas}px, art {scaled_size[0]}x{scaled_size[1]}, foot_y={foot_y} -> {atlas_path}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())