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

391 lines
15 KiB
Python

from __future__ import annotations
import copy
import json
import math
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(r"C:\milimoe\osm-game")
TOOLS_DIR = ROOT / "tools"
if str(TOOLS_DIR) not in sys.path:
sys.path.insert(0, str(TOOLS_DIR))
from build_xinyin_front_left_assembly import ( # noqa: E402
CORRECTION_DIR,
CORRECTION_MANIFEST_PATH,
FONT_PATH,
LAYOUT,
MANIFEST_PATH,
PARTS_DIR,
paste_part,
)
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
OUTPUT_DIR = CHARACTER / "motion/front-left/v1"
PREVIEW_PATH = CHARACTER / "previews/xinyin-front-left-motion-validation-v1.png"
CANVAS_SIZE = (600, 760)
ASSEMBLY_OFFSET_X = 50
CORRECTION_NAMES = {"upper-arm-a", "upper-arm-b", "ponytail-root", "ponytail-middle", "ponytail-tip"}
FRAME_SPECS = [
{
"name": "idle-inhale",
"label": "IDLE · INHALE",
"durationMs": 420,
"note": "胸腔与头部轻微上提;双臂随肩上移,马尾末端稍晚跟随。",
"body_y": -3,
"head_y": -4,
"hair": (1, -44, -43),
"arm": (14, 154),
"cape": 12,
"coat": (-2, 2),
},
{
"name": "idle-neutral",
"label": "IDLE · NEUTRAL",
"durationMs": 260,
"note": "前左装配 v4 的固定基准姿势;映射到运行时 RIGHT。",
"body_y": 0,
"head_y": 0,
"hair": (0, -48, -48),
"arm": (14, 154),
"cape": 14,
"coat": (0, 0),
},
{
"name": "idle-exhale",
"label": "IDLE · EXHALE",
"durationMs": 420,
"note": "胸腔与头部下沉;软性部件收回,脚底基线保持不动。",
"body_y": 2,
"head_y": 3,
"hair": (-1, -52, -55),
"arm": (15, 154),
"cape": 15,
"coat": (2, -2),
},
{
"name": "throw-ready",
"label": "THROW · READY",
"durationMs": 150,
"note": "持扇手上提,形成清楚预备轮廓;重心仍锁定在双脚。",
"body_y": 0,
"head_y": 0,
"torso_rotation": 1,
"hair": (1, -45, -42),
"arm": (35, 150),
"cape": 26,
"coat": (-2, 3),
},
{
"name": "throw-windup",
"label": "THROW · WINDUP",
"durationMs": 110,
"note": "持扇臂回收至头侧,马尾和衣摆向动作反方向蓄势。",
"body_y": 0,
"head_y": -1,
"torso_rotation": 3,
"hair": (3, -40, -35),
"arm": (-25, 170),
"cape": -10,
"coat": (-5, 5),
},
{
"name": "throw-release",
"label": "THROW · RELEASE",
"durationMs": 90,
"note": "持扇臂向右完全展开,张手与脱手羽扇替换中性持握手。",
"body_y": 0,
"head_y": -1,
"torso_rotation": -4,
"head_rotation": -2,
"hair": (5, -34, -27),
"arm": (90, 100),
"cape": 74,
"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": (-3, -56, -61),
"arm": (28, 158),
"cape": 22,
"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()}
correction_manifest = json.loads(CORRECTION_MANIFEST_PATH.read_text(encoding="utf-8"))
for record in correction_manifest["parts"]:
records[record["name"]] = record
images[record["name"]] = Image.open(CORRECTION_DIR / record["file"]).convert("RGBA")
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)
for name in ("torso-upper", "pelvis-hip-core", "shoulder-armor-a", "shoulder-armor-b"):
transforms[name]["y"] += body_y
transforms["torso-upper"]["rotation"] += torso_rotation
for name in ("neck", "head-face", "hair-front", "hair-ornament-long"):
transforms[name]["y"] += head_y
for name in ("head-face", "hair-front", "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
for name in ("outer-sleeve-cape-a", "upper-arm-a", "forearm-a", "hand-relaxed-a"):
transforms[name]["y"] += body_y
transforms["outer-sleeve-cape-a"]["rotation"] += torso_rotation * 0.5
transforms["upper-arm-a"]["rotation"] += torso_rotation * 0.5
hair_root_rotation, hair_middle_rotation, hair_tip_rotation = spec["hair"]
hair_root = transforms["ponytail-root"]
hair_root["x"] += torso_rotation * 0.7
hair_root["y"] += head_y
hair_root["rotation"] = hair_root_rotation
root_target = (hair_root["x"], hair_root["y"])
middle_joint = rotated_joint(records["ponytail-root"], root_target, hair_root["scale"], hair_root_rotation)
hair_middle = transforms["ponytail-middle"]
hair_middle.update({"x": middle_joint[0] - 3, "y": middle_joint[1] - 4, "rotation": hair_middle_rotation})
tip_joint = rotated_joint(
records["ponytail-middle"],
(hair_middle["x"], hair_middle["y"]),
hair_middle["scale"],
hair_middle_rotation,
)
hair_tip = transforms["ponytail-tip"]
hair_tip.update({"x": tip_joint[0] - 2, "y": tip_joint[1] - 4, "rotation": hair_tip_rotation})
upper_rotation, forearm_rotation = spec["arm"]
shoulder = (314 + torso_rotation * 0.8, 241 + body_y)
upper = transforms["upper-arm-b"]
upper.update({"x": shoulder[0], "y": shoulder[1], "rotation": upper_rotation})
elbow = rotated_joint(records["upper-arm-b"], shoulder, upper["scale"], upper_rotation)
forearm = transforms["forearm-b"]
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 = rotated_joint(records["forearm-b"], elbow, forearm_scale, forearm_rotation)
hand = transforms["hand-fan-grip-b"]
hand.update({"x": wrist[0], "y": wrist[1], "rotation": forearm_rotation - 160})
cape = transforms["outer-sleeve-cape-b"]
cape.update({"x": shoulder[0], "y": shoulder[1], "rotation": spec["cape"]})
if spec.get("release"):
hand["visible"] = False
return transforms, shoulder, elbow, wrist
def serializable_transform(name, transform):
return {
"Name": name,
"X": round(transform["x"] + ASSEMBLY_OFFSET_X, 2),
"Y": round(transform["y"], 2),
"Rotation": round(transform["rotation"], 2),
"Scale": transform["scale"],
"Visible": transform.get("visible", True),
}
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"] + ASSEMBLY_OFFSET_X, transform["y"]),
transform["scale"],
transform["rotation"],
)
if spec.get("release"):
open_hand = {
"x": wrist[0],
"y": wrist[1],
"rotation": 92,
"scale": 0.27,
"visible": True,
}
fan = {
"x": min(535, wrist[0] + 27),
"y": wrist[1] - 13,
"rotation": 82,
"scale": 0.30,
"visible": True,
}
for name, transform in (("weapon-fan-open", fan), ("hand-throw-open-b", open_hand)):
pivot = records[name]["rootPivot"]["outputPixels"]
paste_part(
canvas,
images[name],
(pivot["x"], pivot["y"]),
(transform["x"] + ASSEMBLY_OFFSET_X, transform["y"]),
transform["scale"],
transform["rotation"],
)
serialized.append(serializable_transform(name, transform))
joints = {
"Shoulder": [round(shoulder[0] + ASSEMBLY_OFFSET_X, 2), round(shoulder[1], 2)],
"Elbow": [round(elbow[0] + ASSEMBLY_OFFSET_X, 2), round(elbow[1], 2)],
"Wrist": [round(wrist[0] + ASSEMBLY_OFFSET_X, 2), round(wrist[1], 2)],
}
return canvas, serialized, joints
def checker(size, cell=18):
image = Image.new("RGB", size, (235, 239, 245))
draw = ImageDraw.Draw(image)
for y in range(0, size[1], cell):
for x in range(0, size[0], cell):
if (x // cell + y // cell) % 2:
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(215, 222, 231))
return image
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), "心音|运行时 RIGHT 动作验证 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 = ["• 双脚与影子区域不参与动作", "• 手臂按肩—肘—腕链自动连接", "• 三段马尾按根—中—末链自动连接", "• 释放帧使用张手与脱手羽扇替换件"]
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()
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": "front-left",
"runtimeDirection": "right",
"version": 1,
"status": "art-motion-validation",
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels", "assemblyOffsetX": ASSEMBLY_OFFSET_X},
"baseLayout": "assets/images/2d-game-characters/02-xinyin/assembled/front-left/assembly-layout-v4.json",
"sourceManifests": [
"assets/images/2d-game-characters/02-xinyin/parts/front-left/v1/parts-manifest.json",
"assets/images/2d-game-characters/02-xinyin/parts/front-left/rig-corrections-v1/rig-corrections-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-b → forearm-b → hand", "ponytail-root → ponytail-middle → ponytail-tip"],
},
"warnings": [
"This is an art-side motion validation set, not an engine animation resource.",
"Runtime RIGHT uses the legacy front-left art direction.",
"The release frame validates replacement-hand and detached-fan silhouette; timing remains tunable after engine integration.",
],
}
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()