246 lines
15 KiB
Python
246 lines
15 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
|
|
ROOT = Path(r"C:\milimoe\osm-game")
|
|
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
|
SOURCE_DIR = CHARACTER / "source/down"
|
|
DIAGNOSTIC_DIR = CHARACTER / "diagnostics"
|
|
OUTPUT_DIR = CHARACTER / "parts/down/v1"
|
|
PREVIEW = CHARACTER / "previews/xinyin-down-extracted-parts-v1.png"
|
|
MANIFEST = OUTPUT_DIR / "parts-manifest.json"
|
|
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
|
PADDING = 10
|
|
ALPHA_THRESHOLD = 16
|
|
|
|
|
|
SHEETS = {
|
|
"core": {
|
|
"source": SOURCE_DIR / "xinyin-down-core-parts-sheet-v1.png",
|
|
"diagnostic": DIAGNOSTIC_DIR / "xinyin-down-core-parts-v1-components.json",
|
|
"expected": 17,
|
|
},
|
|
"soft": {
|
|
"source": SOURCE_DIR / "xinyin-down-soft-parts-sheet-v2.png",
|
|
"diagnostic": DIAGNOSTIC_DIR / "xinyin-down-soft-parts-v2-components.json",
|
|
"expected": 24,
|
|
},
|
|
}
|
|
|
|
|
|
def part(sheet, component_id, name, label, category, pivot, next_joint, parent, layer, note):
|
|
return {
|
|
"sheet": sheet,
|
|
"componentId": component_id,
|
|
"name": name,
|
|
"labelZh": label,
|
|
"category": category,
|
|
"pivot": pivot,
|
|
"next": next_joint,
|
|
"parent": parent,
|
|
"layer": layer,
|
|
"note": note,
|
|
}
|
|
|
|
|
|
# A = screen-left / character-right / fan hand side. B = screen-right / character-left / relaxed hand side.
|
|
PARTS = [
|
|
part("core", 1, "torso-upper", "上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "正面主躯干;不含手臂与肩甲"),
|
|
part("core", 2, "pelvis-hip-core", "骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根候选;双腿和衣摆挂接于此"),
|
|
part("core", 3, "head-face", "头部与面部", "body", (.50, .91), None, "neck", 30, "严格正面;不含前发"),
|
|
part("core", 4, "shoulder-armor-a", "肩甲 A/画面左", "armor", (.72, .24), None, "torso-upper", 20, "持扇手侧;固定于躯干"),
|
|
part("core", 5, "shoulder-armor-b", "肩甲 B/画面右", "armor", (.28, .24), None, "torso-upper", 20, "放松手侧;固定于躯干"),
|
|
part("core", 6, "neck", "颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接头部"),
|
|
part("core", 8, "upper-arm-a", "上臂 A/画面左", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "持扇手侧;不含肩甲与袖披"),
|
|
part("core", 9, "upper-arm-b", "上臂 B/画面右", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "放松手侧;不含肩甲与袖披"),
|
|
part("core", 10, "forearm-a", "前臂 A/画面左", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "持扇手侧肘到腕"),
|
|
part("core", 11, "forearm-b", "前臂 B/画面右", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "放松手侧肘到腕"),
|
|
part("core", 7, "hand-fan-grip-a", "持扇手 A", "hand", (.50, .88), None, "forearm-a", 18, "画面左侧;含三羽持握形态"),
|
|
part("core", 12, "hand-relaxed-b", "放松手 B", "hand", (.50, .08), None, "forearm-b", 18, "画面右侧;腕点位于上端"),
|
|
part("core", 13, "hand-throw-open-a", "投掷张手 A", "hand", (.18, .18), None, "forearm-a", 18, "持扇手侧动作替换件"),
|
|
part("core", 14, "thigh-a", "大腿 A/画面左", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面左髋点到膝点"),
|
|
part("core", 15, "thigh-b", "大腿 B/画面右", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面右髋点到膝点"),
|
|
part("core", 16, "shin-boot-a", "小腿与靴 A/画面左", "leg", (.50, .05), None, "thigh-a", -7, "画面左;膝点位于上端"),
|
|
part("core", 17, "shin-boot-b", "小腿与靴 B/画面右", "leg", (.50, .05), None, "thigh-b", -7, "画面右;膝点位于上端"),
|
|
part("soft", 5, "hair-front", "前发与双侧鬓", "hair", (.50, .12), None, "head-face", 35, "位于面部之前"),
|
|
part("soft", 6, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-face", -90, "位于头部之后;马尾根父节点"),
|
|
part("soft", 1, "ponytail-root", "马尾根部", "hair", (.48, .10), (.46, .88), "hair-cap", -96, "含银花冠;根部到第一连接点"),
|
|
part("soft", 2, "ponytail-middle", "马尾中段", "hair", (.50, .08), (.50, .90), "ponytail-root", -95, "上下端预留重叠"),
|
|
part("soft", 4, "ponytail-tip", "马尾末端", "hair", (.50, .08), None, "ponytail-middle", -94, "末端链节"),
|
|
part("soft", 3, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-face", 42, "画面右侧独立装饰层"),
|
|
part("soft", 8, "outer-sleeve-cape-a", "外袖披 A/画面左", "cloth", (.50, .08), None, "upper-arm-a", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
|
part("soft", 7, "outer-sleeve-cape-b", "外袖披 B/画面右", "cloth", (.50, .08), None, "upper-arm-b", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
|
part("soft", 10, "coat-panel-01", "衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "中性八片之一"),
|
|
part("soft", 11, "coat-panel-02", "衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "中性八片之一"),
|
|
part("soft", 9, "coat-panel-03", "衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中性八片之一"),
|
|
part("soft", 12, "coat-panel-04", "衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中性八片之一"),
|
|
part("soft", 13, "coat-panel-05", "衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中性八片之一"),
|
|
part("soft", 16, "coat-panel-06", "衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中性八片之一"),
|
|
part("soft", 15, "coat-panel-07", "衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "中性八片之一"),
|
|
part("soft", 17, "coat-panel-08", "衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "中性八片之一"),
|
|
part("soft", 22, "coat-panel-alt-09", "衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作轮廓替换件"),
|
|
part("soft", 14, "front-drape", "中央腰前布", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "不含独立替换流苏"),
|
|
part("soft", 18, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面右侧腰部"),
|
|
part("soft", 19, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
|
part("soft", 20, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
|
part("soft", 21, "weapon-fan-open", "三羽展开扇", "weapon", (.50, .88), None, "hand-fan-grip-a", 50, "无手;与持扇手分层装配"),
|
|
part("soft", 24, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"),
|
|
part("soft", 23, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"),
|
|
]
|
|
|
|
|
|
def load_labels(source_path: Path, diagnostic_path: Path):
|
|
rgba = np.array(Image.open(source_path).convert("RGBA"))
|
|
alpha = rgba[:, :, 3]
|
|
labels_image = Image.fromarray(np.where(alpha >= ALPHA_THRESHOLD, 255, 0).astype(np.uint8), "L").copy()
|
|
diagnostic = json.loads(diagnostic_path.read_text(encoding="utf-8-sig"))
|
|
for component in diagnostic["components"]:
|
|
current = np.array(labels_image)
|
|
y = component["y"]
|
|
x0 = component["x"]
|
|
x1 = x0 + component["width"]
|
|
candidates = np.flatnonzero(current[y, x0:x1] == 255)
|
|
if not len(candidates):
|
|
raise RuntimeError(f"No flood-fill seed for {source_path.name} component {component['id']}")
|
|
ImageDraw.floodfill(labels_image, (x0 + int(candidates[0]), y), component["id"], thresh=0)
|
|
labels = np.array(labels_image)
|
|
for _ in range(8):
|
|
pending = np.argwhere(labels == 255)
|
|
if not len(pending):
|
|
break
|
|
changed = 0
|
|
for y, x in pending:
|
|
neighbours = labels[max(0, y - 1) : min(labels.shape[0], y + 2), max(0, x - 1) : min(labels.shape[1], x + 2)]
|
|
valid = neighbours[(neighbours > 0) & (neighbours < 255)]
|
|
if len(valid):
|
|
values, counts = np.unique(valid, return_counts=True)
|
|
labels[y, x] = values[np.argmax(counts)]
|
|
changed += 1
|
|
if not changed:
|
|
break
|
|
return rgba, labels, diagnostic
|
|
|
|
|
|
def joint_record(normalized, width, height):
|
|
if normalized is None:
|
|
return None
|
|
return {
|
|
"contentNormalized": {"x": normalized[0], "y": normalized[1]},
|
|
"outputPixels": {
|
|
"x": round(PADDING + width * normalized[0], 2),
|
|
"y": round(PADDING + height * normalized[1], 2),
|
|
},
|
|
}
|
|
|
|
|
|
def draw_cross(draw, x, y, color, radius=7, width=3):
|
|
draw.line((x - radius, y, x + radius, y), fill=color, width=width)
|
|
draw.line((x, y - radius, x, y + radius), fill=color, width=width)
|
|
|
|
|
|
def main():
|
|
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
|
|
loaded = {key: load_labels(value["source"], value["diagnostic"]) for key, value in SHEETS.items()}
|
|
for key, (_, labels, diagnostic) in loaded.items():
|
|
expected = SHEETS[key]["expected"]
|
|
if len(diagnostic["components"]) != expected:
|
|
raise RuntimeError(f"Expected {expected} components for {key}")
|
|
if any(not np.any(labels == component_id) for component_id in range(1, expected + 1)):
|
|
raise RuntimeError(f"Missing labeled component in {key}")
|
|
|
|
manifest_parts = []
|
|
exported = []
|
|
for spec in PARTS:
|
|
rgba, labels, diagnostic = loaded[spec["sheet"]]
|
|
component = diagnostic["components"][spec["componentId"] - 1]
|
|
x, y, width, height = (component[k] for k in ("x", "y", "width", "height"))
|
|
crop = rgba[y : y + height, x : x + width].copy()
|
|
mask = labels[y : y + height, x : x + width] == spec["componentId"]
|
|
crop[~mask] = 0
|
|
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
|
|
output[PADDING : PADDING + height, PADDING : PADDING + width] = crop
|
|
image = Image.fromarray(output, "RGBA")
|
|
prefix = "down-core" if spec["sheet"] == "core" else "down-soft"
|
|
filename = f"{prefix}-c{spec['componentId']:02d}-{spec['name']}.png"
|
|
image.save(OUTPUT_DIR / filename)
|
|
record = {
|
|
"sourceSheet": spec["sheet"],
|
|
"componentId": spec["componentId"],
|
|
"name": spec["name"],
|
|
"labelZh": spec["labelZh"],
|
|
"category": spec["category"],
|
|
"file": filename,
|
|
"parent": spec["parent"],
|
|
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
|
|
"outputSize": {"width": image.width, "height": image.height},
|
|
"rootPivot": joint_record(spec["pivot"], width, height),
|
|
"nextJoint": joint_record(spec["next"], width, height),
|
|
"suggestedLayer": spec["layer"],
|
|
"notes": spec["note"],
|
|
}
|
|
manifest_parts.append(record)
|
|
exported.append((spec, record, image))
|
|
|
|
manifest = {
|
|
"characterId": "02-xinyin",
|
|
"characterNameZh": "汐月心音",
|
|
"direction": "down",
|
|
"version": 1,
|
|
"status": "extracted-unvalidated",
|
|
"sources": {
|
|
"core": "assets/images/2d-game-characters/02-xinyin/source/down/xinyin-down-core-parts-sheet-v1.png",
|
|
"soft": "assets/images/2d-game-characters/02-xinyin/source/down/xinyin-down-soft-parts-sheet-v2.png",
|
|
},
|
|
"padding": PADDING,
|
|
"alphaExtraction": {"connectivity": 8, "alphaThreshold": ALPHA_THRESHOLD, "minimumComponentArea": 80, "mode": "connected-component-mask"},
|
|
"coordinateSystem": {"origin": "top-left", "xPositive": "right", "yPositive": "down", "units": "pixels", "jointBasis": "content bounds before export padding"},
|
|
"sideConvention": {"A": "screen-left / character-right / fan-hand side", "B": "screen-right / character-left / relaxed-hand side"},
|
|
"warnings": [
|
|
"A/B ownership is frozen by screen side for the strict-front DOWN direction and must not be mirrored.",
|
|
"Pivots, layers, and parent links are authoring recommendations until the first neutral assembly is validated.",
|
|
"The source pelvis contains neutral waist accessories; standalone pouch, front drape, and tassels are replacement layers and may be excluded from the neutral assembly.",
|
|
"Soft sheet v1 is a rejected crowded layout; extraction uses soft sheet v2 only.",
|
|
],
|
|
"partCount": len(manifest_parts),
|
|
"parts": manifest_parts,
|
|
}
|
|
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
|
|
columns, cell_width, cell_height = 6, 390, 300
|
|
rows = (len(exported) + columns - 1) // columns
|
|
sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), (20, 24, 33))
|
|
draw = ImageDraw.Draw(sheet)
|
|
title_font = ImageFont.truetype(str(FONT_PATH), 18)
|
|
meta_font = ImageFont.truetype(str(FONT_PATH), 13)
|
|
for index, (spec, record, image) in enumerate(exported):
|
|
col, row = index % columns, index // columns
|
|
cell_x, cell_y = col * cell_width, row * cell_height
|
|
draw.rectangle((cell_x + 8, cell_y + 8, cell_x + cell_width - 9, cell_y + cell_height - 9), outline=(63, 78, 104), width=2)
|
|
scale = min(1.0, 270 / image.width, 200 / image.height)
|
|
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
|
|
draw_x = cell_x + (cell_width - resized.width) // 2
|
|
draw_y = cell_y + 42 + (200 - resized.height) // 2
|
|
sheet.paste(resized, (draw_x, draw_y), resized)
|
|
root = record["rootPivot"]["outputPixels"]
|
|
draw_cross(draw, draw_x + root["x"] * scale, draw_y + root["y"] * scale, (255, 87, 115))
|
|
if record["nextJoint"]:
|
|
nxt = record["nextJoint"]["outputPixels"]
|
|
draw_cross(draw, draw_x + nxt["x"] * scale, draw_y + nxt["y"] * scale, (69, 211, 255))
|
|
code = "C" if spec["sheet"] == "core" else "S"
|
|
draw.text((cell_x + 16, cell_y + 12), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
|
|
draw.text((cell_x + 16, cell_y + 263), f"{spec['labelZh']} | parent: {spec['parent']}", font=meta_font, fill=(155, 174, 203))
|
|
sheet.save(PREVIEW)
|
|
print(f"Exported {len(exported)} parts")
|
|
print(MANIFEST)
|
|
print(PREVIEW)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|