files-game/tools/name_card_faces.py
2026-10-01 17:22:18 -04:00

113 lines
4 KiB
Python
Executable file

#!/usr/bin/env python3
"""Renames exported card fronts (front-4985.png, ...) to card-name file names.
The card export writes one front per card copy, numbered in cards.csv row order. This matches
them up by sorting the numbers, names each file the way CardFaces.slug does ("Execute: Force
Reboot" -> execute-force-reboot.png), and gives each face the card-face import settings. A face
that already exists is replaced, keeping its .import file (and so its uid).
tools/name_card_faces.py # show what would be renamed
tools/name_card_faces.py --apply # rename
tools/name_card_faces.py --csv PATH --dir PATH
"""
import argparse
import csv
import re
import sys
from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
DEFAULT_CSV = Path.home() / "Troglodyte-Chamber/files-tcg/decks/files-deck-1/cards.csv"
DEFAULT_DIR = PROJECT / "assets/cards"
IMPORT = """[remap]
importer="texture"
type="CompressedTexture2D"
[params]
compress/mode=2
compress/high_quality=true
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=true
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=0
"""
def slug(name: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--csv", type=Path, default=DEFAULT_CSV)
ap.add_argument("--dir", type=Path, default=DEFAULT_DIR)
ap.add_argument("--apply", action="store_true", help="rename the files (default: only show the plan)")
args = ap.parse_args()
with args.csv.open(newline="") as f:
rows = list(csv.DictReader(f))
# One export per copy, so a card with Count 2 has two fronts.
names = [r["Name"] for r in rows for _ in range(int(r.get("Count") or 1))]
fronts = sorted(args.dir.glob("front-*.png"), key=lambda p: int(re.search(r"\d+", p.stem).group()))
if len(fronts) != len(names):
print(f"{len(fronts)} fronts in {args.dir}, but {args.csv} has {len(names)} card copies. "
"Export every card, in CSV order, then run this again.", file=sys.stderr)
return 1
done: set[str] = set()
for front, name in zip(fronts, names):
target = args.dir / f"{slug(name)}.png"
if target.name in done:
# A later copy of a card that's already named.
print(f"{front.name} -> (copy of {name}, removed)")
if args.apply:
front.unlink()
front.with_suffix(".png.import").unlink(missing_ok=True)
continue
done.add(target.name)
replaced = " (replaces the old face)" if target.exists() else ""
print(f"{front.name} -> {target.name}{replaced}")
if not args.apply:
continue
front.replace(target)
stale = front.with_suffix(".png.import")
target_import = target.with_suffix(".png.import")
if target_import.exists():
stale.unlink(missing_ok=True)
elif stale.exists():
# Godot already imported the front: keep its uid, use the card-face settings.
uid = re.search(r'^uid="[^"]+"$', stale.read_text(), re.M)
text = IMPORT.replace('type="CompressedTexture2D"\n', f'type="CompressedTexture2D"\n{uid.group()}\n') if uid else IMPORT
target_import.write_text(text)
stale.unlink()
else:
target_import.write_text(IMPORT)
if not args.apply:
print("\nNothing renamed yet. Run with --apply to rename.")
return 0
if __name__ == "__main__":
sys.exit(main())