277 lines
13 KiB
Python
277 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Build the Ravenous Roll20 sheet from the Ravenous Typst source data."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import hashlib
|
|
import html
|
|
import json
|
|
import re
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
import yaml
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DATA = ROOT / "ravenous_typst" / "data" / "src"
|
|
TEMPLATES = ROOT / "src"
|
|
BUILD = ROOT / "build"
|
|
BUILD_CONFIG = ROOT / "ravenous_typst" / "data" / "config" / "build.yaml"
|
|
|
|
|
|
def slug(value: str) -> str:
|
|
import unicodedata
|
|
|
|
plain = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode()
|
|
return re.sub(r"[^a-z0-9]+", "_", plain.lower()).strip("_")
|
|
|
|
|
|
def read_character_data() -> dict:
|
|
path = DATA / "character_sheet.yaml"
|
|
if not path.exists():
|
|
raise SystemExit("Missing Ravenous source data. Initialize ravenous_typst submodule first.")
|
|
with path.open(encoding="utf-8") as stream:
|
|
return yaml.safe_load(stream)
|
|
|
|
|
|
def read_glossary_labels() -> dict[str, str]:
|
|
labels: dict[str, str] = {
|
|
"cl_sgA": "Sang immaculé", "cl_sgM": "Sang bestial", "cl_sgS": "Sang honni",
|
|
"cl_no_cost": "Aethéré", "jauge": "Jauge", "sangressence": "Sangressence",
|
|
}
|
|
for path in sorted((DATA / "glossaries").glob("*.yaml")):
|
|
with path.open(encoding="utf-8") as stream:
|
|
entries = yaml.safe_load(stream) or []
|
|
for entry in entries:
|
|
if not isinstance(entry, dict) or "key" not in entry:
|
|
continue
|
|
label = entry.get("short")
|
|
if not isinstance(label, str):
|
|
label = entry.get("long")
|
|
if isinstance(label, str):
|
|
labels.setdefault(entry["key"], label)
|
|
return labels
|
|
|
|
|
|
def _replace_balanced_calls(text: str, macro: str, renderer) -> str:
|
|
marker = f"#{macro}("
|
|
while marker in text:
|
|
start = text.find(marker)
|
|
depth = 1
|
|
quote = None
|
|
index = start + len(marker)
|
|
while index < len(text) and depth:
|
|
char = text[index]
|
|
if quote:
|
|
if char == quote and text[index - 1] != "\\":
|
|
quote = None
|
|
elif char in "\"'":
|
|
quote = char
|
|
elif char == "(":
|
|
depth += 1
|
|
elif char == ")":
|
|
depth -= 1
|
|
index += 1
|
|
if depth:
|
|
break
|
|
arguments = text[start + len(marker):index - 1]
|
|
text = text[:start] + renderer(arguments) + text[index:]
|
|
return text
|
|
|
|
|
|
def translate_typst(text: str, glossary: dict[str, str]) -> str:
|
|
"""Turn the subset of Typst markup used by school TSVs into chat-safe text."""
|
|
characteristics = {"force": "Force", "agi": "Agilité", "per": "Perception", "int": "Intelligence", "vol": "Volonté", "psy": "Psy", "chance": "Chance", "cha": "Charisme"}
|
|
text = re.sub(r"#inline_help\[([^]]*)]", r"Note : \1", text)
|
|
text = re.sub(r"#footnote\[([^]]*)]", r"(Note : \1)", text)
|
|
text = _replace_balanced_calls(text, "ddlvl", lambda args: "DD " + args.split(",", 1)[0].strip())
|
|
text = _replace_balanced_calls(text, "resist", lambda args: "Résistance " + args.split(",", 1)[0].strip())
|
|
text = _replace_balanced_calls(text, "marques", lambda args: "Marque " + args.replace("[", "").replace("]", ""))
|
|
text = _replace_balanced_calls(text, "gls", lambda args: (re.search(r'display\s*:\s*"([^"]+)"', args) or re.search(r'"([^"]+)"', args)).group(1))
|
|
def weapon(args: str) -> str:
|
|
fields = dict((key, value.strip().strip("[]\"")) for key, value in re.findall(r'(name|damage|rmax|range|aspect|arbreak|armor_pierce|am|precision|protection|integrity|actions)\s*:\s*(\[[^]]*]|"[^\"]*"|[^,]+)', args))
|
|
labels = {"damage":"dégâts","rmax":"RMax","range":"portée","aspect":"zone","arbreak":"brise-armure","armor_pierce":"perce-armure","am":"anti-matériel","precision":"précision","protection":"protection","integrity":"intégrité","actions":"actions"}
|
|
name = fields.pop("name", "Attaque")
|
|
values = [f"{labels.get(key, key)} {value}" for key, value in fields.items() if value]
|
|
return f"{name} ({' · '.join(values)})" if values else name
|
|
text = _replace_balanced_calls(text, "weapon-pill", weapon)
|
|
def aoe(args: str) -> str:
|
|
values = [f"{key.replace('repositionning', 'repositionnement').replace('parry', 'parade').replace('dodge', 'esquive')} {value}" for key, value in re.findall(r'(\w+)\s*:\s*"([^\"]*)"', args)]
|
|
return "Défense de zone" + (" (" + " · ".join(values) + ")" if values else "")
|
|
text = _replace_balanced_calls(text, "aoe_thresholds", aoe)
|
|
text = re.sub(r"#cr\.([A-Za-z_]+)", lambda match: characteristics.get(match.group(1), match.group(1).replace("_", " ").title()), text)
|
|
text = re.sub(r"@([A-Za-z_][A-Za-z0-9_]*)(?::(?:short|long|pl))?", lambda match: glossary.get(match.group(1), match.group(1).replace("_", " ")), text)
|
|
text = re.sub(r"#([A-Za-z_][A-Za-z0-9_-]*)", lambda match: match.group(1).replace("_", " ").replace("-", " "), text)
|
|
text = text.replace("[", "").replace("]", "").replace("_", "")
|
|
return re.sub(r"\s+", " ", text).strip()
|
|
|
|
|
|
def read_schools(max_tier_exclusive: int, glossary: dict[str, str]) -> dict[str, list[dict[str, str]]]:
|
|
schools: dict[str, list[dict[str, str]]] = {}
|
|
for path in sorted((DATA / "schools").glob("*.tsv")):
|
|
techniques: list[dict[str, str]] = []
|
|
tier = ""
|
|
headers: list[str] | None = None
|
|
with path.open(encoding="utf-8-sig", newline="") as stream:
|
|
for row in csv.reader(stream, delimiter="\t"):
|
|
row += [""] * (16 - len(row))
|
|
first = row[0].strip()
|
|
if first.startswith("Tier "):
|
|
tier = first.removeprefix("Tier ").strip()
|
|
headers = None
|
|
elif first == "Technique":
|
|
headers = row
|
|
elif headers and first and tier.isdigit() and int(tier) < max_tier_exclusive:
|
|
item = dict(zip(headers, row))
|
|
techniques.append({
|
|
"name": first,
|
|
"level": item.get("Niv", "").strip(),
|
|
"tier": tier,
|
|
"type": item.get("Type", "").strip(),
|
|
"blood": item.get("Sang", "").strip(),
|
|
"gauge": item.get("Jauge", "").strip(),
|
|
"other": translate_typst(item.get("Autre", "").strip(), glossary),
|
|
"effect": translate_typst(item.get("Effet", "").strip(), glossary),
|
|
})
|
|
schools[path.stem] = techniques
|
|
return schools
|
|
|
|
|
|
def read_build_config() -> dict:
|
|
with BUILD_CONFIG.open(encoding="utf-8") as stream:
|
|
return yaml.safe_load(stream)
|
|
|
|
|
|
def skills_from_data(data: dict) -> list[dict[str, str]]:
|
|
skills: list[dict[str, str]] = []
|
|
defaults = {
|
|
"Parade": "force", "Esquive": "agilite", "Encaissement": "force",
|
|
"Initiative": "perception", "Sens commun": "charisme",
|
|
"Négociation": "charisme", "Traque": "perception", "Survie": "perception",
|
|
"Dépeçage": "intelligence", "Médecine": "intelligence",
|
|
}
|
|
for category in data["competences"]:
|
|
for entry in category.get("entries", []):
|
|
name = entry["name"]
|
|
key = slug(name)
|
|
characteristic = defaults.get(name, "agilite" if category["name"] == "Athlétisme" else "intelligence")
|
|
skills.append({"id": key, "name": name, "category": category["name"], "characteristic": characteristic, "description": entry.get("description", "")})
|
|
return skills
|
|
|
|
|
|
def skill_rows(skills: list[dict[str, str]]) -> str:
|
|
rows = []
|
|
category = None
|
|
for skill in skills:
|
|
if skill["category"] != category:
|
|
category = skill["category"]
|
|
rows.append(f'<div class="skill-category"><span>◆</span>{html.escape(category)}</div>')
|
|
rows.append(f'''<div class="skill-row" title="{html.escape(skill['description'])}">
|
|
<button class="skill-roll" type="action" name="act_skill_{skill['id']}" title="Tester {html.escape(skill['name'])}" aria-label="Tester {html.escape(skill['name'])}"></button>
|
|
<span class="skill-name">{html.escape(skill['name'])}</span>
|
|
<select name="attr_{skill['id']}_characteristic">{characteristic_options(skill['characteristic'])}</select>
|
|
<input type="number" name="attr_{skill['id']}" value="0" min="0">
|
|
<input type="number" name="attr_{skill['id']}_temp" value="0">
|
|
<input type="hidden" name="attr_{skill['id']}_effect" value="0"><output name="attr_{skill['id']}_total">0</output>
|
|
</div>''')
|
|
return "\n".join(rows)
|
|
|
|
|
|
def technique_options(schools: dict[str, list[dict[str, str]]]) -> tuple[str, dict[str, dict[str, str]]]:
|
|
options = []
|
|
indexed: dict[str, dict[str, str]] = {}
|
|
for school, techniques in schools.items():
|
|
children = []
|
|
for index, technique in enumerate(techniques):
|
|
key = f"{school}:{index}"
|
|
indexed[key] = {**technique, "school": school}
|
|
label = f"T{technique['tier']} · {technique['name']} {technique['level']}"
|
|
children.append(f'<option value="{key}">{html.escape(label.strip())}</option>')
|
|
options.append(f'<optgroup label="{html.escape(school.replace("_", " ").title())}">{"".join(children)}</optgroup>')
|
|
return "".join(options), indexed
|
|
|
|
|
|
CHARACTERISTICS = ["force", "agilite", "perception", "intelligence", "volonte", "psy", "chance", "charisme"]
|
|
|
|
|
|
def characteristic_options(selected: str) -> str:
|
|
labels = dict(zip(CHARACTERISTICS, ["Force", "Agilité", "Perception", "Intelligence", "Volonté", "Psy", "Chance", "Charisme"]))
|
|
return "".join(f'<option value="{key}"{" selected" if key == selected else ""}>{label}</option>' for key, label in labels.items())
|
|
|
|
|
|
def render(template: str, replacements: dict[str, str]) -> str:
|
|
for key, value in replacements.items():
|
|
template = template.replace("{{" + key + "}}", value)
|
|
missing = re.findall(r"\{\{[A-Z][A-Z0-9_]+\}\}", template)
|
|
if missing:
|
|
raise RuntimeError(f"Unresolved template markers: {missing}")
|
|
return template
|
|
|
|
|
|
def target_options(skills: list[dict[str, str]], include_empty: bool = False) -> str:
|
|
empty = '<option value="">— aucune —</option>' if include_empty else ""
|
|
characteristics = "".join(
|
|
f'<option value="{key}">{label}</option>'
|
|
for key, label in zip(CHARACTERISTICS, ["Force", "Agilité", "Perception", "Intelligence", "Volonté", "Psy", "Chance", "Charisme"])
|
|
)
|
|
skill_options = "".join(f'<option value="{item["id"]}">{html.escape(item["name"])}</option>' for item in skills)
|
|
return empty + f'<optgroup label="Caractéristiques">{characteristics}</optgroup><optgroup label="Compétences">{skill_options}</optgroup>'
|
|
|
|
|
|
def skill_target_options(skills: list[dict[str, str]]) -> str:
|
|
return '<option value="">— aucune —</option>' + "".join(
|
|
f'<option value="{item["id"]}">{html.escape(item["name"])}</option>' for item in skills
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--check", action="store_true", help="fail when build/ differs from generated output")
|
|
args = parser.parse_args()
|
|
data = read_character_data()
|
|
config = read_build_config()
|
|
max_tier_exclusive = int(config["build"]["max_tier_exclusive"])
|
|
schools = read_schools(max_tier_exclusive, read_glossary_labels())
|
|
skills = skills_from_data(data)
|
|
technique_select, techniques = technique_options(schools)
|
|
generated = {
|
|
"ravenous.html": render((TEMPLATES / "ravenous.html").read_text(encoding="utf-8"), {
|
|
"SKILL_ROWS": skill_rows(skills),
|
|
"TECHNIQUE_OPTIONS": technique_select,
|
|
"CHARACTERISTIC_OPTIONS": characteristic_options("agilite"),
|
|
"TARGET_OPTIONS": target_options(skills),
|
|
"TARGET_OPTIONS_EMPTY": target_options(skills, include_empty=True),
|
|
"SKILL_TARGET_OPTIONS_EMPTY": skill_target_options(skills),
|
|
"TECHNIQUES_JSON": json.dumps(techniques, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/"),
|
|
"SKILLS_JSON": json.dumps(skills, ensure_ascii=False, separators=(",", ":")),
|
|
}),
|
|
"ravenous.css": (TEMPLATES / "ravenous.css").read_text(encoding="utf-8"),
|
|
"translation.json": (TEMPLATES / "translation.json").read_text(encoding="utf-8"),
|
|
"sheet.json": (TEMPLATES / "sheet.json").read_text(encoding="utf-8"),
|
|
}
|
|
digest = hashlib.sha256("".join(generated.values()).encode()).hexdigest()[:12]
|
|
generated["build-info.json"] = json.dumps({
|
|
"source": "ravenous_typst/data/src", "schools": len(schools), "max_tier_exclusive": max_tier_exclusive,
|
|
"techniques": sum(map(len, schools.values())), "skills": len(skills), "content_hash": digest,
|
|
}, ensure_ascii=False, indent=2) + "\n"
|
|
if args.check:
|
|
stale = [name for name, content in generated.items() if not (BUILD / name).exists() or (BUILD / name).read_text(encoding="utf-8") != content]
|
|
if stale:
|
|
raise SystemExit("Generated files are stale: " + ", ".join(stale))
|
|
return
|
|
BUILD.mkdir(exist_ok=True)
|
|
for child in BUILD.iterdir():
|
|
if child.is_file():
|
|
child.unlink()
|
|
elif child.is_dir():
|
|
shutil.rmtree(child)
|
|
for name, content in generated.items():
|
|
(BUILD / name).write_text(content, encoding="utf-8")
|
|
print(f"Built {len(generated)} files ({len(skills)} skills, {sum(map(len, schools.values()))} techniques).")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|