Files
Oshima-Game/tools/build_xinyin_up_motion.py
2026-09-19 17:24:02 +08:00

340 lines
14 KiB
Python

from __future__ import annotations
import copy
import json
import math
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from build_xinyin_down_motion import checker, serializable_transform
from build_xinyin_up_assembly import FONT_PATH, LAYOUT, MANIFEST_PATH, PARTS_DIR, paste_part
ROOT = Path(r"C:\milimoe\osm-game")
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
OUTPUT_DIR = CHARACTER / "motion/up/v1"
PREVIEW_PATH = CHARACTER / "previews/xinyin-up-motion-validation-v1.png"
CANVAS_SIZE = (600, 760)
FRAME_SPECS = [
{
"name": "idle-inhale",
"label": "IDLE · INHALE",
"durationMs": 420,
"note": "肩背与头部轻微上提;画面左后方马尾略晚跟随。",
"body_y": -3,
"head_y": -4,
"hair": (-4, -22, -14),
"arm": (10, 153),
"cape": 7,
"coat": (-2, 2),
},
{
"name": "idle-neutral",
"label": "IDLE · NEUTRAL",
"durationMs": 260,
"note": "UP 装配 v1 的固定背面基准姿势。",
"body_y": 0,
"head_y": 0,
"hair": (-5, -20, -12),
"arm": (10, 154),
"cape": 8,
"coat": (0, 0),
},
{
"name": "idle-exhale",
"label": "IDLE · EXHALE",
"durationMs": 420,
"note": "肩背与头部下沉;软性部件收回,双脚基线保持不动。",
"body_y": 2,
"head_y": 3,
"hair": (-6, -18, -10),
"arm": (11, 155),
"cape": 9,
"coat": (2, -2),
},
{
"name": "throw-ready",
"label": "THROW · READY",
"durationMs": 150,
"note": "画面右侧持扇手上提,身体主轴仍保持背面。",
"body_y": 0,
"head_y": 0,
"torso_rotation": 1,
"hair": (-6, -23, -16),
"arm": (22, 151),
"cape": 22,
"coat": (-2, 3),
},
{
"name": "throw-windup",
"label": "THROW · WINDUP",
"durationMs": 110,
"note": "持扇臂收至头侧蓄势;画面左后方马尾与衣摆反向压缩。",
"body_y": 0,
"head_y": -1,
"torso_rotation": -3,
"head_rotation": -1,
"hair": (-8, -28, -24),
"arm": (30, -170),
"cape": 28,
"coat": (-5, 5),
},
{
"name": "throw-release",
"label": "THROW · RELEASE",
"durationMs": 90,
"note": "身体保持背面,持扇臂向画面右侧完全展开;张手和单枚脱手羽刃替换中性持握。",
"body_y": 0,
"head_y": -1,
"torso_rotation": 3,
"head_rotation": 1,
"hair": (-2, -10, -5),
"arm": (90, 90),
"cape": 78,
"coat": (6, -6),
"release": True,
},
{
"name": "throw-recover",
"label": "THROW · RECOVER",
"durationMs": 180,
"note": "手臂回收;马尾与衣摆越过中位后准备回到待机。",
"body_y": 1,
"head_y": 1,
"torso_rotation": 1,
"head_rotation": -1,
"hair": (-7, -16, -8),
"arm": (38, 151),
"cape": 34,
"coat": (3, -4),
},
]
def rotated_joint(record, target, scale, angle):
root = record["rootPivot"]["outputPixels"]
next_joint = record["nextJoint"]["outputPixels"]
dx = (next_joint["x"] - root["x"]) * scale
dy = (next_joint["y"] - root["y"]) * scale
radians = math.radians(angle)
return (
target[0] + math.cos(radians) * dx + math.sin(radians) * dy,
target[1] - math.sin(radians) * dx + math.cos(radians) * dy,
)
def load_parts():
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
records = {record["name"]: record for record in manifest["parts"]}
images = {name: Image.open(PARTS_DIR / record["file"]).convert("RGBA") for name, record in records.items()}
return records, images
def build_transforms(spec, records):
transforms = {entry["name"]: copy.deepcopy(entry) for entry in LAYOUT}
body_y = spec.get("body_y", 0)
head_y = spec.get("head_y", 0)
torso_rotation = spec.get("torso_rotation", 0)
head_rotation = spec.get("head_rotation", 0)
# Pelvis and legs stay locked to the ground. Breathing only affects the upper body.
transforms["torso-upper"]["y"] += body_y
transforms["torso-upper"]["rotation"] += torso_rotation
for name in ("shoulder-armor-a", "shoulder-armor-b"):
transforms[name]["y"] += body_y
for name in ("neck", "head-back", "hair-cap", "hair-nape-overlay", "hair-ornament-long"):
transforms[name]["y"] += head_y
for name in ("head-back", "hair-cap", "hair-nape-overlay", "hair-ornament-long"):
transforms[name]["rotation"] += head_rotation
left_coat_delta, right_coat_delta = spec["coat"]
for index in range(1, 5):
transforms[f"coat-panel-0{index}"]["rotation"] += left_coat_delta * (5 - index) / 4
for index in range(5, 9):
transforms[f"coat-panel-0{index}"]["rotation"] += right_coat_delta * (index - 4) / 4
# Relaxed B arm follows breathing but never joins the throw.
for name in ("outer-sleeve-cape-b", "upper-arm-b", "forearm-b", "hand-relaxed-b"):
transforms[name]["y"] += body_y
transforms["outer-sleeve-cape-b"]["rotation"] += torso_rotation * 0.5
transforms["upper-arm-b"]["rotation"] += torso_rotation * 0.5
root_angle, middle_angle, tip_angle = spec["hair"]
hair_root = transforms["ponytail-root"]
hair_root["x"] -= torso_rotation * 0.7
hair_root["y"] += head_y
hair_root["rotation"] = root_angle
hair_middle = transforms["ponytail-middle"]
hair_middle["x"] -= torso_rotation * 1.2
hair_middle["y"] += head_y * 0.7
hair_middle["rotation"] = middle_angle
hair_tip = transforms["ponytail-tip"]
hair_tip["x"] -= torso_rotation * 2.0
hair_tip["y"] += head_y * 0.4
hair_tip["rotation"] = tip_angle
upper_rotation, forearm_rotation = spec["arm"]
shoulder = (374 + torso_rotation * 0.8, 241 + body_y)
upper = transforms["upper-arm-a"]
upper.update({"x": shoulder[0], "y": shoulder[1], "rotation": upper_rotation})
elbow_joint = rotated_joint(records["upper-arm-a"], shoulder, upper["scale"], upper_rotation)
elbow = (elbow_joint[0] - 2, elbow_joint[1] - 7)
forearm = transforms["forearm-a"]
forearm_scale = 0.34 if spec.get("release") else 0.38
forearm.update({"x": elbow[0], "y": elbow[1], "rotation": forearm_rotation, "scale": forearm_scale})
wrist_joint = rotated_joint(records["forearm-a"], elbow, forearm_scale, forearm_rotation)
wrist = (wrist_joint[0] + 2, wrist_joint[1] - 4)
hand = transforms["hand-fan-grip-a"]
hand.update({"x": wrist[0], "y": wrist[1], "rotation": forearm_rotation - 147})
cape = transforms["outer-sleeve-cape-a"]
cape.update({"x": shoulder[0], "y": shoulder[1], "rotation": spec["cape"]})
if spec.get("release"):
hand["visible"] = False
return transforms, shoulder, elbow, wrist
def render_frame(spec, records, images):
transforms, shoulder, elbow, wrist = build_transforms(spec, records)
canvas = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
serialized = []
for entry in LAYOUT:
name = entry["name"]
transform = transforms[name]
serialized.append(serializable_transform(name, transform))
if not transform.get("visible", True):
continue
pivot = records[name]["rootPivot"]["outputPixels"]
paste_part(canvas, images[name], (pivot["x"], pivot["y"]), (transform["x"], transform["y"]), transform["scale"], transform["rotation"])
if spec.get("release"):
open_hand = {"x": wrist[0], "y": wrist[1], "rotation": 180, "scale": 0.27, "visible": True}
blade = {"x": min(CANVAS_SIZE[0] - 24, wrist[0] + 68), "y": wrist[1] - 8, "rotation": 90, "scale": 0.32, "visible": True}
for name, transform in (("hand-throw-open-a", open_hand), ("weapon-blade-single", blade)):
pivot = records[name]["rootPivot"]["outputPixels"]
paste_part(canvas, images[name], (pivot["x"], pivot["y"]), (transform["x"], transform["y"]), transform["scale"], transform["rotation"])
serialized.append(serializable_transform(name, transform))
joints = {
"Shoulder": [round(shoulder[0], 2), round(shoulder[1], 2)],
"Elbow": [round(elbow[0], 2), round(elbow[1], 2)],
"Wrist": [round(wrist[0], 2), round(wrist[1], 2)],
}
return canvas, serialized, joints
def make_preview(frames):
board = Image.new("RGB", (1560, 1050), (17, 21, 30))
draw = ImageDraw.Draw(board)
title_font = ImageFont.truetype(str(FONT_PATH), 38)
label_font = ImageFont.truetype(str(FONT_PATH), 21)
note_font = ImageFont.truetype(str(FONT_PATH), 17)
draw.text((42, 25), "心音|运行时 UP 动作验证 v1", font=title_font, fill=(242, 246, 252))
draw.text((44, 78), "严格背面身体 · 固定脚底基线 · 待机呼吸 3 帧 + 向画面右侧投掷 4 帧", font=note_font, fill=(151, 169, 198))
cells = [(42 + 378 * col, 120 + 455 * row) for row in range(2) for col in range(4)]
for (spec, frame), (x, y) in zip(frames, cells):
draw.rounded_rectangle((x, y, x + 352, y + 425), radius=14, fill=(25, 31, 43), outline=(65, 82, 112), width=2)
draw.text((x + 16, y + 13), spec["label"], font=label_font, fill=(241, 245, 252))
preview = frame.copy()
preview.thumbnail((324, 346), Image.Resampling.LANCZOS)
bg = checker((324, 346))
bg.paste(preview, ((324 - preview.width) // 2, (346 - preview.height) // 2), preview)
board.paste(bg, (x + 14, y + 52))
draw.text((x + 16, y + 402), f"{spec['durationMs']} ms", font=note_font, fill=(151, 169, 198))
draw.text((1176, 590), "验证重点", font=label_font, fill=(241, 245, 252))
notes = [
"• 身体主轴保持背面,不借侧身强化动作",
"• 双脚与地面原点在全部帧中锁定",
"• 画面右侧 A 手臂按肩—肘—腕链连接",
"• 释放帧使用张手与单枚脱手羽刃替换件",
]
for index, note in enumerate(notes):
draw.text((1178, 635 + index * 36), note, font=note_font, fill=(174, 188, 211))
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
board.save(PREVIEW_PATH, quality=95)
def main():
records, images = load_parts()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
frames = []
manifest_frames = []
baselines = []
bounds = []
edge_transparent = True
for spec in FRAME_SPECS:
frame, transforms, joints = render_frame(spec, records, images)
frame_path = OUTPUT_DIR / f"{spec['name']}.png"
frame.save(frame_path)
frames.append((spec, frame))
bbox = frame.getchannel("A").getbbox()
if bbox is None:
raise ValueError(f"Frame {spec['name']} is fully transparent")
bounds.append(bbox)
baselines.append(bbox[3] - 1)
alpha = frame.getchannel("A")
edges = [
alpha.crop((0, 0, CANVAS_SIZE[0], 1)),
alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])),
alpha.crop((0, 0, 1, CANVAS_SIZE[1])),
alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])),
]
edge_transparent = edge_transparent and all(edge.getbbox() is None for edge in edges)
manifest_frames.append({
"name": spec["name"],
"label": spec["label"],
"file": frame_path.name,
"durationMs": spec["durationMs"],
"note": spec["note"],
"joints": joints,
"transforms": transforms,
})
make_preview(frames)
manifest = {
"characterId": "02-xinyin",
"direction": "up",
"runtimeDirection": "up",
"version": 1,
"status": "art-motion-validated",
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels"},
"baseLayout": "assets/images/2d-game-characters/02-xinyin/assembled/up/assembly-layout-v1.json",
"sourceManifests": ["assets/images/2d-game-characters/02-xinyin/parts/up/v1/parts-manifest.json"],
"sequence": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral", "throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"],
"loopNotes": {
"idle": "inhale → neutral → exhale → neutral",
"throw": "ready → windup → release → recover",
},
"frames": manifest_frames,
"validation": {
"edgeTransparent": edge_transparent,
"baselineYByFrame": dict(zip((spec["name"] for spec in FRAME_SPECS), baselines)),
"baselineDeltaPixels": max(baselines) - min(baselines),
"visibleAlphaBoundsByFrame": {
spec["name"]: {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]}
for spec, bbox in zip(FRAME_SPECS, bounds)
},
"jointChains": [
"upper-arm-a → forearm-a → hand",
"ponytail-root / ponytail-middle / ponytail-tip with neutral-overlap offsets",
],
},
"warnings": [
"This is an art-side motion validation set, not an engine animation resource.",
"UP keeps the torso back-facing while the fan-side arm releases toward screen-right for readability.",
"Projectile and VFX aim remain free-angle at runtime; the body animation is four-cardinal.",
],
}
manifest_path = OUTPUT_DIR / "motion-manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
print(manifest_path)
print(PREVIEW_PATH)
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()