#!/usr/bin/env python3 """Build the two D10 Roll20 sheets from explicit models and skill YAML.""" import argparse import hashlib import html import json from pathlib import Path import re import yaml ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / 'data' ASSETS = ROOT / 'assets' IDENT = re.compile(r'^[A-Za-z][A-Za-z0-9_-]*$') COLOR = re.compile(r'^#[0-9a-fA-F]{6}$') TABS = (('skills', 'Compétences'), ('combat', 'Combat'), ('other', 'Autres')) LOCATIONS = { 'head': 'Tête', 'body': 'Torse', 'left_arm': 'Bras gauche', 'right_arm': 'Bras droit', 'left_leg': 'Jambe gauche', 'right_leg': 'Jambe droite', } FIELD_LABELS = { 'skillname': 'Nom', 'skilllevel': 'Niveau', 'skillcost': 'Coût', 'name': 'Nom', 'notes': 'Notes', 'damage': 'Dégâts', 'quantity': 'Quantité', } def read_yaml(path): return yaml.safe_load(path.read_text(encoding='utf-8')) def ident(value): if not isinstance(value, str) or not IDENT.fullmatch(value): raise ValueError(f'invalid Roll20 identifier: {value!r}') return value def esc(value): return html.escape(str(value), quote=True) def validate(model, skills, theme): if model.get('version') != 1: raise ValueError('unsupported model version') for color in theme.values(): if not isinstance(color, str) or not COLOR.fullmatch(color): raise ValueError(f'invalid theme color: {color!r}') for required in ('background', 'panel', 'ink', 'accent', 'border'): if required not in theme: raise ValueError(f'missing theme color: {required}') fields = set() for item in model['attributes'] + model['resources']: key = ident(item['id']) if key in fields: raise ValueError(f'duplicate field: {key}') fields.add(key) for item in model.get('combat', []): key = ident(item['id']) if key in fields: raise ValueError(f'duplicate field: {key}') fields.add(key) for location in model.get('health_locations', []): ident(location) if location not in LOCATIONS: raise ValueError(f'unsupported health location: {location}') if len(set(model.get('health_locations', []))) != len(model.get('health_locations', [])): raise ValueError('duplicate health location') if not isinstance(model.get('weapons', 0), int) or not 0 <= model.get('weapons', 0) <= 10: raise ValueError('weapons must be an integer from 0 to 10') sections = skills['sections'] if not isinstance(sections, list) or not sections: raise ValueError('skills need sections') generated_fields = set() for section in sections: for group in section['groups']: prefix = ''.join(c for c in group['name'].replace(' ', '') if c.isascii() and c.isalpha()).lower() if not prefix: raise ValueError(f'group has no usable identifier: {group["name"]!r}') seen = set() for skill in group.get('skills', []): key = ident(skill['id']) if key in seen: raise ValueError(f'duplicate skill in {group["name"]}: {key}') seen.add(key) stem = f'{prefix}_skilllevel_{key}' if stem in generated_fields: raise ValueError(f'duplicate generated skill field: {stem}') generated_fields.add(stem) if skill.get('parent') and skill['parent'] not in seen: raise ValueError(f'unknown or later parent for {key}') repeating_ids = set() for block in model['repeating']: ident(block['id']) if block['id'] in repeating_ids: raise ValueError(f'duplicate repeating section: {block["id"]}') repeating_ids.add(block['id']) for field in block['fields']: ident(field) if model.get('skill_tabs'): tab_ids = set() content_ids = [] for tab in model['skill_tabs']: key = ident(tab['id']) if key in tab_ids: raise ValueError(f'duplicate skill tab: {key}') tab_ids.add(key) content_ids.extend(tab['content']) expected = repeating_ids | {'fixed_skills'} if set(content_ids) != expected or len(content_ids) != len(expected): raise ValueError('skill tabs must place each skill group and repeating section exactly once') def roll(label, threshold): expression = f'{threshold}-1d@{{dice}}cs1cf@{{dice}}' value = ('&{template:d10skillcheck} ' '{{name=@{character_name}}} ' f'{{{{roll_name={label}}}}} ' '{{dice_name=@{dice}}} ' f'{{{{threshold=[[{threshold}]]}}}} ' f'{{{{result=[[{expression}]]}}}}') return f'' def render_skill(group, skill, variant): # Cyberpunk names follow the original generator's subgroup prefix and ID. prefix = ''.join(c for c in group['name'].replace(' ', '') if c.isascii() and c.isalpha()).lower() if variant == 'base': stem = f'general_skilllevel_{skill["id"]}' name_field = skill['name'] else: stem = f'{prefix}_skilllevel_{skill["id"]}' name_field = skill['name'] threshold = f'@{{{stem}}}+@{{skill_{prefix}_attribute_select_{skill["id"]}}}' if skill.get('parent'): threshold += f'+@{{{prefix}_skilllevel_{skill["parent"]}}}' options = [('Force', 'For'), ('Agilite', 'Agi'), ('Perception', 'Per'), ('Charisme', 'Cha'), ('Intelligence', 'Int'), ('Volonte', 'Vol'), (('Psyche' if variant == 'base' else 'Accred'), ('Psy' if variant == 'base' else 'Acc')), ('Chance', 'Chn')] selector = f'skill_{prefix}_attribute_select_{skill["id"]}' choices = ''.join(f'' for key, short in options) depth = ' sheet-subskill' if skill.get('parent') else '' return (f'
{esc(name_field)}' f'' f'' f'' f'{roll(name_field, threshold)}
') def render_body_map(locations, kind, asset_base_url=''): title = 'Santé' if kind == 'health' else 'Armure' legend = 'PV par localisation' if kind == 'health' else 'P = protection · I = intégrité · Max = intégrité maximale' image_name = f'robotman_{kind}_r.png' image_url = f'{asset_base_url.rstrip("/")}/{image_name}' if asset_base_url else image_name parts = [f'

{title}

', f'
'] for location in locations: label = LOCATIONS[location] parts.append(f'
{label}') if kind == 'health': parts.append(f'') else: for field, short, descriptor in (('Armor_Protection_Points', 'P', 'Protection'), ('Armor_Integrity_Points', 'I', 'Intégrité'), ('Armor_Integrity_Points', 'Max', 'Intégrité maximale')): suffix = '_maximum' if short == 'Max' else '' parts.append(f'') parts.append('
') parts.append(f'

{legend}

') return ''.join(parts) def render_fixed_skills(skills, variant, show_sections=True): parts = [] for section in skills['sections']: if show_sections: parts.append(f'

{esc(section["name"])}

') for group in section['groups']: parts.append(f'

{esc(group["name"])}

' '
CompétenceCarac.NiveauCoûtJet
') parts.extend(render_skill(group, skill, variant) for skill in group.get('skills', [])) parts.append('
') return ''.join(parts) def render_repeating_block(block, attributes, expanded=False): parts = [f'{esc(block["name"])}' f'
'] for field in block['fields']: kind = 'number' if field in ('skilllevel', 'skillcost', 'quantity', 'damage') else 'text' parts.append(f'') if 'skilllevel' in block['fields']: options = ''.join( f'' for item in attributes) parts.append(f'') parts.append(roll('@{skillname}', '@{skilllevel}+@{attribute_select}')) parts.append('
') return ''.join(parts) def render(model, skills, variant, theme_name, theme, asset_base_url=''): tabs = TABS[:-1] if model.get('skill_tabs') else TABS parts = [f'
', '
D10
', f'
Feuille de personnage

{esc(model["title"])}

', '
', '
', '
', '
01

Caractéristiques

', '
'] for item in model['attributes']: key = item['id'] threshold = f'(@{{base-{key}}}+@{{exal-{key}}})*2' parts.append(f'
{esc(item["name"])}' f'' f'' f'{roll(item["name"], threshold)}
') parts.append('
02

Ressources

') for item in model['resources']: key = item['id'] parts.append(f'
{esc(item["name"])}' f'' f'/
') if model.get('health_locations'): parts.append('
') parts.append(render_body_map(model['health_locations'], 'health', asset_base_url)) parts.append(render_body_map(model['health_locations'], 'armor', asset_base_url)) parts.append('
') else: parts.append('
') parts.extend([ '', '', '
03

Combat

', ]) for item in model.get('combat', []): parts.append(f'') parts.append('
Jets de combat') parts.append(roll('Initiative', '@{base-Agilite}+@{exal-Agilite}+@{Initiative}')) parts.append(roll('Attaque', '@{general_attack_threshold}')) parts.append('

Armes équipées

') for number in range(1, model.get('weapons', 0) + 1): parts.append(f'
Arme {number}' f'' f'' f'
') parts.append('
04

Compétences

') if model.get('skill_tabs'): skill_tabs = model['skill_tabs'] parts.append(f'') parts.append('') repeating = {block['id']: block for block in model['repeating']} for tab in skill_tabs: parts.append(f'
') for content in tab['content']: parts.append(render_fixed_skills(skills, variant, show_sections=False) if content == 'fixed_skills' else render_repeating_block(repeating[content], model['attributes'], expanded=True)) parts.append('
') else: parts.append(render_fixed_skills(skills, variant)) parts.append('
') if not model.get('skill_tabs'): parts.append('
05

Autres

') for block in model['repeating']: parts.append(render_repeating_block(block, model['attributes'])) parts.append('
') parts.append('') html_text = '\n'.join(parts) + '\n' css = '.sheet-d10, .sheet-rolltemplate-d10skillcheck {\n' + '\n'.join( f' --d10-{key}: {value};' for key, value in theme.items()) + '\n}\n' css += (ROOT / 'templates' / 'sheet.css').read_text(encoding='utf-8') if model.get('skill_tabs'): css += '\n'.join( f'.sheet-d10 .sheet-skill-tab-state[value="{tab["id"]}"] ~ .sheet-skill-pane-{tab["id"]} {{ display: block; }}\n' f'.sheet-d10 .sheet-skill-tab-state[value="{tab["id"]}"] ~ .sheet-skill-tab-nav .sheet-skill-tab-{tab["id"]} {{ color: var(--d10-panel); background: var(--d10-accent); border-color: var(--d10-accent); }}\n' for tab in model['skill_tabs']) html_text += '''
{{name}} — {{roll_name}}
Seuil: {{threshold}} · Résultat: {{result}}
''' html_text += '\n' return html_text, css def build(variant, theme_name, output, check=False, asset_base_url=''): source = read_yaml(DATA / 'sheet_model.yaml') themes = read_yaml(DATA / 'themes.yaml')['themes'] if variant not in source['variants']: raise ValueError(f'unknown variant: {variant}') if theme_name not in themes: raise ValueError(f'unknown theme: {theme_name}') if asset_base_url and not re.fullmatch(r'https://[^\s<>"\']+', asset_base_url): raise ValueError('asset base URL must be HTTPS') model = source['variants'][variant] skills = read_yaml(DATA / model['skills']) theme = themes[theme_name] validate({**model, 'version': source['version']}, skills, theme) html_text, css = render(model, skills, variant, theme_name, theme, asset_base_url) manifest = {'html': 'sheet.html', 'css': 'sheet.css', 'authors': 'Dandaedre', 'roll20userid': '1067910', 'instructions': f'{model["title"]} generated from D10 YAML'} translation = {} files = {'sheet.html': html_text, 'sheet.css': css, 'sheet.json': json.dumps(manifest, ensure_ascii=False, indent=2) + '\n', 'translation.json': json.dumps(translation, indent=2) + '\n'} if model.get('health_locations'): for kind in ('health', 'armor'): name = f'robotman_{kind}_r.png' files[name] = (ASSETS / name).read_bytes() digest = hashlib.sha256((html_text + css).encode()) for name in sorted(files): if isinstance(files[name], bytes): digest.update(files[name]) files['build-info.json'] = json.dumps({'variant': variant, 'theme': theme_name, 'skills': sum(len(g.get('skills', [])) for s in skills['sections'] for g in s['groups']), 'sha256': digest.hexdigest()}, indent=2) + '\n' if check: stale = [name for name, content in files.items() if not (output / name).exists() or (output / name).read_bytes() != (content if isinstance(content, bytes) else content.encode('utf-8'))] if stale: raise ValueError(f'generated files are missing or stale: {", ".join(stale)}') else: output.mkdir(parents=True, exist_ok=True) for name, content in files.items(): (output / name).write_bytes(content if isinstance(content, bytes) else content.encode('utf-8')) return files def main(): parser = argparse.ArgumentParser() parser.add_argument('--variant', choices=('base', 'cyberpunk'), default='base') parser.add_argument('--theme', choices=('parchment', 'night'), default='parchment') parser.add_argument('--output-dir', type=Path) parser.add_argument('--list-themes', action='store_true') parser.add_argument('--check', action='store_true', help='verify existing output without writing') parser.add_argument('--asset-base-url', default='', help='public HTTPS directory for body images in Roll20') args = parser.parse_args() if args.list_themes: print('\n'.join(read_yaml(DATA / 'themes.yaml')['themes'])) return output = args.output_dir or ROOT / 'build' / args.variant / args.theme try: build(args.variant, args.theme, output, check=args.check, asset_base_url=args.asset_base_url) except ValueError as error: parser.error(str(error)) print(output) if __name__ == '__main__': main()