d10_cs_generator/tools/build.py

563 lines
34 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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'
DEFAULT_ASSET_BASE_URL = 'https://books.dandaedre.com/RPG/d10_character_sheet/assets/'
BASE_THEMES = ('parchment', 'night')
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é',
}
WEAPON_FIELDS = {
'distance': {'name', 'damage', 'notes', 'weapon_type', 'accuracy', 'base_threshold',
'skill_id', 'single_cost', 'burst_cost', 'auto_cost',
'ammo_current', 'magazine_size', 'ammo_reserve', 'damage_per_success', 'rmax',
'weapon_status'},
'melee': {'name', 'damage', 'notes', 'weapon_type', 'accuracy', 'base_threshold',
'skill_id', 'damage_per_success', 'rmax', 'weapon_status'},
}
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 figure_filter(background):
channels = [int(background[index:index + 2], 16) for index in (1, 3, 5)]
return 'invert(1)' if sum(channels) / 3 < 130 else 'none'
def validate(model, skills, theme):
if model.get('version') != 1:
raise ValueError('unsupported model version')
for color in (theme[key] for key in ('background', 'panel', 'ink', 'accent', 'border') if key in theme):
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')
if model.get('skill_category_tabs'):
if model.get('skill_tabs'):
raise ValueError('choose one skill tab layout')
category_ids = [ident(section.get('id')) for section in sections
if any(group.get('skills') for group in section['groups'])]
if len(category_ids) < 2 or len(category_ids) != len(set(category_ids)):
raise ValueError('skill categories need at least two unique tab identifiers')
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_category_tabs') and block['id'] in WEAPON_FIELDS and set(block['fields']) != WEAPON_FIELDS[block['id']]:
raise ValueError(f'invalid weapon fields: {block["id"]}')
if model.get('skill_category_tabs'):
equipment_ids = [ident(group['equipment']) for section in sections for group in section['groups']
if group.get('equipment')]
if len(equipment_ids) != len(set(equipment_ids)) or not set(equipment_ids) <= repeating_ids:
raise ValueError('equipment categories must reference unique repeating sections')
if not combat_skills(skills):
raise ValueError('cyberpunk weapons need combat skills')
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, combat=False):
die = '10' if combat else '@{dice}'
expression = f'{threshold}-1d{die}cs1cf{die}'
value = ('&{template:d10skillcheck} '
'{{name=@{character_name}}} '
f'{{{{roll_name={label}}}}} '
f'{{{{dice_name={die}}}}} '
f'{{{{threshold=[[{threshold}]]}}}} '
f'{{{{result=[[{expression}]]}}}}')
return f'<button type="roll" class="sheet-roll" value="{esc(value)}" title="Lancer {esc(label)}">Jet</button>'
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'<option value="@{{base-{key}}}+@{{exal-{key}}}">{esc(short)}</option>' for key, short in options)
depth = ' sheet-subskill' if skill.get('parent') else ''
return (f'<div class="sheet-skill-row{depth}"><span class="sheet-skill-name">{esc(name_field)}</span>'
f'<select name="attr_{selector}" title="Caractéristique">{choices}</select>'
f'<input type="number" name="attr_{stem}" value="0" min="0" title="Niveau">'
f'<input type="number" name="attr_{prefix}_skillcost_{skill["id"]}" value="0" min="0" title="Coût">'
f'{roll(name_field, threshold)}</div>')
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'<div class="sheet-map-card sheet-map-{kind}"><h3>{title}</h3>',
f'<div class="sheet-body-figure"><img class="sheet-body-image" src="{esc(image_url)}" alt="" aria-hidden="true" width="146" height="300">']
for location in locations:
label = LOCATIONS[location]
parts.append(f'<div class="sheet-zone sheet-zone-{location}"><span class="sheet-zone-label">{label}</span>')
if kind == 'health':
parts.append(f'<input type="number" name="attr_Life_Points_{location}" value="0" aria-label="PV {label}" title="PV {label}">')
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'<label>{short}<input type="number" name="attr_{field}_{location}{suffix}" value="0" aria-label="{descriptor} {label}" title="{descriptor} {label}"></label>')
parts.append('</div>')
parts.append(f'</div><p class="sheet-map-legend">{legend}</p></div>')
return ''.join(parts)
def render_fixed_skills(skills, variant, show_sections=True, sections=None):
parts = []
for section in (skills['sections'] if sections is None else sections):
if show_sections:
parts.append(f'<h3 class="sheet-subheading">{esc(section["name"])}</h3>')
for group in section['groups']:
parts.append(f'<div class="sheet-skill-group"><h4>{esc(group["name"])}</h4>'
'<div class="sheet-skill-head"><span>Compétence</span><span>Carac.</span><span>Niveau</span><span>Coût</span><span>Jet</span></div>')
parts.extend(render_skill(group, skill, variant) for skill in group.get('skills', []))
parts.append('</div>')
return ''.join(parts)
def combat_skills(skills):
return next((group['skills'] for section in skills['sections'] for group in section['groups']
if group['name'] == 'Combat'), [])
def render_repeating_block(block, attributes, expanded=False):
parts = [f'<details{" open" if expanded else ""}><summary>{esc(block["name"])}</summary>'
f'<fieldset class="repeating_{esc(block["id"])}"><div class="sheet-repeater">']
for field in block['fields']:
kind = 'number' if field in ('skilllevel', 'skillcost', 'quantity', 'damage') else 'text'
parts.append(f'<label class="sheet-repeater-{field}">{esc(FIELD_LABELS.get(field, field))}<input type="{kind}" name="attr_{esc(field)}"></label>')
if block['id'] == 'contacts-skills':
command = '&{template:d10contact} {{name=@{skillname}}} {{level=@{skilllevel}}}'
parts.append(f'<button type="roll" class="sheet-roll sheet-show" value="{esc(command)}" title="Afficher le contact">Show</button>')
elif block['id'] == 'consommable':
command = '&{template:d10consumable} {{name=@{name}}} {{quantity=@{quantity}}} {{notes=@{notes}}}'
parts.append(f'<button type="roll" class="sheet-roll sheet-show" value="{esc(command)}" title="Afficher le consommable">Show</button>')
elif 'skilllevel' in block['fields']:
options = ''.join(
f'<option value="@{{base-{item["id"]}}}+@{{exal-{item["id"]}}}">{esc(item["name"])}</option>'
for item in attributes)
parts.append(f'<label class="sheet-repeater-attribute">Caractéristique<select name="attr_attribute_select">{options}</select></label>')
parts.append(roll('@{skillname}', '@{skilllevel}+@{attribute_select}'))
parts.append('</div></fieldset></details>')
return ''.join(parts)
def render_weapon_block(block, combat_skills):
ranged = block['id'] == 'distance'
options = '<option value="">Aucune spécialité</option>' + ''.join(
f'<option value="{esc(skill["id"])}">{esc(skill["name"])}</option>' for skill in combat_skills)
def field(name, label, kind='number', value='0', extra=''):
return (f'<label class="sheet-weapon-field sheet-weapon-{name}">{label}'
f'<input type="{kind}" name="attr_{name}" value="{esc(value)}" {extra}></label>')
parts = [f'<fieldset class="repeating_{esc(block["id"])}"><div class="sheet-weapon-repeater">',
field('name', 'Nom', 'text', ''), field('weapon_type', 'Type', 'text', ''),
field('accuracy', 'Précision', value='0'),
field('base_threshold', 'Seuil de base', value='4'),
'<label class="sheet-weapon-field sheet-weapon-skill_id">Compétence'
f'<select name="attr_skill_id">{options}</select></label>',
field('damage', 'Dégâts de base', value='0'),
field('damage_per_success', 'Dégâts / réussite', value='0'),
field('rmax', 'Rmax (0 = sans limite)', value='0', extra='min="0"'),
field('notes', 'Spécial / notes', 'text', '')]
if ranged:
parts.extend([field('single_cost', 'Coup par coup', value='1', extra='min="1"'),
field('burst_cost', 'Rafale', value='3', extra='min="1"'),
field('auto_cost', 'Automatique', value='5', extra='min="1"'),
field('ammo_current', 'Chargeur actuel', value='0', extra='min="0"'),
field('magazine_size', 'Taille du chargeur', value='0', extra='min="0"'),
field('ammo_reserve', 'Chargeurs de réserve', value='0', extra='min="0"')])
actions = ([('firesingle', 'Tir simple'), ('fireburst', 'Rafale'),
('fireauto', 'Automatique'), ('reload', 'Recharger')]
if ranged else [('attack', 'Attaque')])
actions.append(('damage', 'Dégâts'))
parts.append('<div class="sheet-weapon-actions">' + ''.join(
f'<button type="action" name="act_{key}">{label}</button>' for key, label in actions) + '</div>')
parts.append('<span class="sheet-weapon-status" name="attr_weapon_status"></span></div></fieldset>')
return ''.join(parts)
def render(model, skills, variant, theme_name, theme, themes, asset_base_url=''):
tabs = TABS[:-1] if model.get('skill_tabs') else TABS
switchable = variant == 'cyberpunk'
parts = []
parts.extend(['<div class="sheet-theme-shell">',
f'<input type="hidden" class="sheet-theme-state" name="attr_d10_theme" value="{esc(theme_name)}">'])
parts.extend([f'<div class="sheet-d10 sheet-variant-{variant} sheet-theme-{esc(theme_name)}">',
'<header class="sheet-hero"><div class="sheet-hero-mark">D10</div>',
f'<div class="sheet-hero-main"><span class="sheet-eyebrow">Feuille de personnage</span><h1>{esc(model["title"])}</h1>',
'<div class="sheet-identity"><label>Nom <input type="text" name="attr_character_name"></label>',
'<label>Origine <input type="text" name="attr_character_race"></label></div></div>',
'<label class="sheet-die-choice">Dé de jeu <select name="attr_dice">' + ''.join(
f'<option value="{n}"{" selected" if n == 10 else ""}>d{n}</option>'
for n in (4, 6, 8, 10, 12, 20)) + '</select></label>',
])
parts.append('<div class="sheet-hero-tools"><label class="sheet-theme-choice">Thème <select name="attr_d10_theme_choice">' + ''.join(
f'<option value="{esc(key)}"{" selected" if key == theme_name else ""}>{esc(palette.get("name", key))}</option>'
for key, palette in themes.items()) + '</select></label>')
parts.append('<details class="sheet-character-io-menu"><summary>Échanges JSON</summary>'
'<div class="sheet-character-io-actions">'
'<button type="roll" name="roll_export_character" '
'value="!d10-export --id @{character_id}">Exporter</button>'
'<button type="roll" name="roll_replace_character" '
'value="!d10-import --replace --id @{character_id} --handout ?{ID du handout personnage}">Restaurer</button>'
'</div></details></div>')
parts.extend(['</header>',
'<section class="sheet-panel"><div class="sheet-section-title"><span>01</span><h2>Caractéristiques</h2></div>',
'<div class="sheet-stat-grid">'])
for item in model['attributes']:
key = item['id']
threshold = f'(@{{base-{key}}}+@{{exal-{key}}})*2'
parts.append(f'<div class="sheet-stat"><strong>{esc(item["name"])}</strong>'
f'<label>Base<input type="number" name="attr_base-{key}" value="0" title="Base"></label>'
f'<label>Bonus<input type="number" name="attr_exal-{key}" value="0" title="Bonus"></label>'
f'{roll(item["name"], threshold)}</div>')
parts.append('</div></section><section class="sheet-panel"><div class="sheet-section-title"><span>02</span><h2>Ressources</h2></div><div class="sheet-resource-grid">')
for item in model['resources']:
key = item['id']
parts.append(f'<div class="sheet-resource"><strong>{esc(item["name"])}</strong>'
f'<label>Actuel<input type="number" name="attr_{key}" value="0" title="Actuel"></label>'
f'<span>/</span><label>Maximum<input type="number" name="attr_{key}_maximum" value="0" title="Maximum"></label></div>')
if model.get('health_locations'):
parts.append('</div><div class="sheet-body-maps">')
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('</div>')
else:
parts.append('</div>')
parts.extend([
'</section>',
'<input type="hidden" class="sheet-tab-state" name="attr_d10_tab" value="skills">',
'<nav class="sheet-tab-nav" aria-label="Sections de la feuille">',
*(f'<button type="action" class="sheet-tab-button sheet-tab-{key}" name="act_tab_{key}">{label}</button>'
for key, label in tabs),
'</nav><div class="sheet-page sheet-page-combat"><section class="sheet-panel"><div class="sheet-section-title"><span>03</span><h2>Combat</h2></div><div class="sheet-combat-grid">',
])
for item in model.get('combat', []):
if switchable:
field = (f'<label>{esc(item["name"])}'
f'<input type="number" name="attr_{esc(item["id"])}" value="0"></label>')
parts.append('<div class="sheet-combat-field sheet-combat-field-initiative">' + field +
roll('Initiative', '@{base-Agilite}+@{exal-Agilite}+@{Initiative}', combat=True) + '</div>')
else:
parts.append(f'<label class="sheet-combat-field">{esc(item["name"])}'
f'<input type="number" name="attr_{esc(item["id"])}" value="0"></label>')
if not switchable:
parts.append('</div><div class="sheet-combat-actions"><span>Jets de combat</span>')
parts.append(roll('Initiative', '@{base-Agilite}+@{exal-Agilite}+@{Initiative}', combat=True))
parts.append(roll('Attaque', '@{general_attack_threshold}', combat=True))
parts.append('</div><h3 class="sheet-subheading">Armes équipées</h3><div class="sheet-weapon-grid">')
for number in range(1, model.get('weapons', 0) + 1):
parts.append(f'<div class="sheet-weapon"><span>Arme {number}</span>'
f'<input type="text" name="attr_general_item_weapon{number}_name" title="Nom">'
f'<input type="number" name="attr_general_item_weapon{number}" value="0" title="Dégâts">'
f'<input type="checkbox" name="attr_item_weapon{number}_activation" value="1" title="Équipée"></div>')
else:
equipment = [group for section in skills['sections'] for group in section['groups']
if group.get('equipment')]
repeating = {block['id']: block for block in model['repeating']}
weapon_skills = combat_skills(skills)
parts.append('</div><h3 class="sheet-subheading">Arsenal</h3><div class="sheet-arsenal">')
parts.append('<input type="hidden" class="sheet-arsenal-tab-state" name="attr_d10_arsenal_tab" value="distance">')
parts.append('<nav class="sheet-skill-tab-nav sheet-arsenal-tab-nav" aria-label="Catégories d’arsenal">')
for group in equipment:
key = group['equipment']
parts.append(f'<button type="action" class="sheet-arsenal-tab-{key}" name="act_arsenal_tab_{key}">{esc(group["name"])}</button>')
parts.append('</nav>')
for group in equipment:
key = group['equipment']
parts.append(f'<div class="sheet-skill-pane sheet-arsenal-pane-{key}">')
parts.append(render_weapon_block(repeating[key], weapon_skills) if key in ('distance', 'melee')
else render_repeating_block(repeating[key], model['attributes'], expanded=True))
parts.append('</div>')
parts.append('</div></section></div><div class="sheet-page sheet-page-skills"><section class="sheet-panel"><div class="sheet-section-title"><span>04</span><h2>Compétences</h2></div>')
if model.get('skill_tabs'):
skill_tabs = model['skill_tabs']
parts.append(f'<input type="hidden" class="sheet-skill-tab-state" name="attr_d10_skill_tab" value="{skill_tabs[0]["id"]}">')
parts.append('<nav class="sheet-skill-tab-nav" aria-label="Catégories de compétences">')
for tab in skill_tabs:
parts.append(f'<button type="action" class="sheet-skill-tab-button sheet-skill-tab-{tab["id"]}" name="act_skill_tab_{tab["id"]}">{esc(tab["name"])}</button>')
parts.append('</nav>')
repeating = {block['id']: block for block in model['repeating']}
for tab in skill_tabs:
parts.append(f'<div class="sheet-skill-pane sheet-skill-pane-{tab["id"]}">')
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('</div>')
elif model.get('skill_category_tabs'):
categories = [section for section in skills['sections']
if any(group.get('skills') for group in section['groups'])]
parts.append(f'<input type="hidden" class="sheet-category-tab-state" name="attr_d10_category_tab" value="{esc(categories[0]["id"])}">')
parts.append('<nav class="sheet-skill-tab-nav sheet-category-tab-nav" aria-label="Catégories de compétences">')
for section in categories:
key = section['id']
parts.append(f'<button type="action" class="sheet-skill-tab-button sheet-category-tab-{key}" name="act_category_tab_{key}">{esc(section["name"])}</button>')
parts.append('</nav>')
for section in categories:
parts.append(f'<div class="sheet-skill-pane sheet-category-pane-{section["id"]}">')
parts.append(render_fixed_skills(skills, variant, show_sections=False, sections=[section]))
parts.append('</div>')
else:
parts.append(render_fixed_skills(skills, variant))
parts.append('</section></div>')
if not model.get('skill_tabs'):
parts.append('<div class="sheet-page sheet-page-other"><section class="sheet-panel"><div class="sheet-section-title"><span>05</span><h2>Autres</h2></div>')
equipment_ids = {group['equipment'] for section in skills['sections'] for group in section['groups']
if group.get('equipment')} if model.get('skill_category_tabs') else set()
for block in model['repeating']:
if block['id'] in equipment_ids:
continue
parts.append(render_repeating_block(block, model['attributes']))
parts.append('</section></div>')
parts.append('</div>')
parts.append('</div>')
html_text = '\n'.join(parts) + '\n'
css = ('.sheet-d10, .sheet-rolltemplate-d10skillcheck, .sheet-rolltemplate-d10weapon, .sheet-rolltemplate-d10contact, .sheet-rolltemplate-d10consumable {\n' + '\n'.join(
f' --d10-{key}: {theme[key]};' for key in ('background', 'panel', 'ink', 'accent', 'border')) +
f'\n --d10-figure-filter: {figure_filter(theme["background"])};\n}}\n')
css += (ROOT / 'templates' / 'sheet.css').read_text(encoding='utf-8')
for key, palette in themes.items():
css += f'\n.sheet-theme-state[value="{key}"] ~ .sheet-d10 {{\n'
css += '\n'.join(f' --d10-{color}: {palette[color]};' for color in
('background', 'panel', 'ink', 'accent', 'border'))
css += f'\n --d10-figure-filter: {figure_filter(palette["background"])};\n}}\n'
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'])
if model.get('skill_category_tabs'):
css += '\n'.join(
f'.sheet-d10 .sheet-category-tab-state[value="{section["id"]}"] ~ .sheet-category-pane-{section["id"]} {{ display: block; }}\n'
f'.sheet-d10 .sheet-category-tab-state[value="{section["id"]}"] ~ .sheet-category-tab-nav .sheet-category-tab-{section["id"]} {{ color: var(--d10-panel); background: var(--d10-accent); border-color: var(--d10-accent); }}\n'
for section in skills['sections'] if any(group.get('skills') for group in section['groups']))
css += ('.sheet-d10 .sheet-category-tab-state[value="arsenal"] ~ .sheet-category-pane-physique { display: block; }\n'
'.sheet-d10 .sheet-category-tab-state[value="arsenal"] ~ .sheet-category-tab-nav .sheet-category-tab-physique { color: var(--d10-panel); background: var(--d10-accent); border-color: var(--d10-accent); }\n')
arsenal = [group['equipment'] for section in skills['sections'] for group in section['groups']
if group.get('equipment')]
css += '\n'.join(
f'.sheet-d10 .sheet-arsenal-tab-state[value="{key}"] ~ .sheet-arsenal-pane-{key} {{ display: block; }}\n'
f'.sheet-d10 .sheet-arsenal-tab-state[value="{key}"] ~ .sheet-arsenal-tab-nav .sheet-arsenal-tab-{key} {{ color: var(--d10-panel); background: var(--d10-accent); border-color: var(--d10-accent); }}\n'
for key in arsenal)
html_text += '''<rolltemplate class="sheet-rolltemplate-d10skillcheck">
<div class="sheet-roll-title"><strong>{{name}}</strong><span>{{roll_name}}</span></div>
<div class="sheet-roll-values"><span>Seuil</span><span class="sheet-roll-value">{{threshold}}</span><span>Résultat</span><span class="sheet-roll-value">{{result}}</span></div>
</rolltemplate>
'''
if variant == 'cyberpunk':
html_text += '''<rolltemplate class="sheet-rolltemplate-d10contact">
<div class="sheet-roll-title"><strong>Contact</strong><span>{{name}}</span></div>
<div class="sheet-roll-detail">Niveau : {{level}}</div>
</rolltemplate>
'''
html_text += '''<rolltemplate class="sheet-rolltemplate-d10consumable">
<div class="sheet-roll-title"><strong>Consommable</strong><span>{{name}}</span></div>
<div class="sheet-roll-detail">Quantité : {{quantity}}</div>
{{#notes}}<div class="sheet-roll-detail">{{notes}}</div>{{/notes}}
</rolltemplate>
'''
html_text += '''<rolltemplate class="sheet-rolltemplate-d10weapon">
<div class="sheet-roll-title"><strong>{{name}}</strong><span>{{mode}}</span></div>
{{#type}}<div class="sheet-roll-detail">{{type}}</div>{{/type}}
<div class="sheet-roll-values"><span>Réussites</span><span class="sheet-roll-value">{{#attack_roll}}{{attack_roll}}{{/attack_roll}}{{#damage_roll}}{{damage_roll}}{{/damage_roll}}</span>{{#damage}}<span>Dégâts</span><span class="sheet-roll-value">{{computed::damage}}</span>{{/damage}}{{#damage_list}}<span>Dégâts par tir</span><span class="sheet-roll-value sheet-roll-damage-list">{{computed::damage_list}}</span>{{/damage_list}}</div>
{{#threshold}}<div class="sheet-roll-detail">Seuil : {{threshold}}</div>{{/threshold}}
{{#rmax}}<div class="sheet-roll-detail">Rmax : {{rmax}}</div>{{/rmax}}
{{#ammo_info}}<div class="sheet-roll-detail">Chargeur : {{ammo}} / {{magazine}} · chargeurs de réserve : {{reserve}}</div>{{/ammo_info}}
{{#special}}<div class="sheet-roll-detail">{{special}}</div>{{/special}}
</rolltemplate>
'''
html_text += '<script type="text/worker">\n'
html_text += ''.join(
f'on("clicked:tab_{key}", function () {{ setAttrs({{d10_tab: "{key}"}}); }});\n'
for key, _ in tabs)
html_text += ''.join(
f'on("clicked:skill_tab_{tab["id"]}", function () {{ setAttrs({{d10_skill_tab: "{tab["id"]}"}}); }});\n'
for tab in model.get('skill_tabs', []))
if model.get('skill_category_tabs'):
html_text += ''.join(
f'on("clicked:category_tab_{section["id"]}", function () {{ setAttrs({{d10_category_tab: "{section["id"]}"}}); }});\n'
for section in skills['sections'] if any(group.get('skills') for group in section['groups']))
html_text += ''.join(
f'on("clicked:arsenal_tab_{key}", function () {{ setAttrs({{d10_arsenal_tab: "{key}"}}); }});\n'
for key in arsenal)
html_text += 'on("change:d10_theme_choice", function (event) { setAttrs({d10_theme: event.newValue}); });\n'
if switchable:
weapon_skills = combat_skills(skills)
worker = (ROOT / 'templates' / 'cyberpunk-weapons.js').read_text(encoding='utf-8')
html_text += worker.replace('__COMBAT_SKILLS__', json.dumps([skill['id'] for skill in weapon_skills]))
html_text += '</script>\n'
return html_text, css
def build(variant, theme_name, output, check=False, asset_base_url=None):
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}')
allowed_themes = ({key: themes[key] for key in BASE_THEMES} if variant == 'base' else themes)
if theme_name not in allowed_themes:
raise ValueError(f'unknown theme for {variant}: {theme_name}')
if asset_base_url is None:
asset_base_url = DEFAULT_ASSET_BASE_URL
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 = allowed_themes[theme_name]
validate({**model, 'version': source['version']}, skills, theme)
html_text, css = render(model, skills, variant, theme_name, theme, allowed_themes, 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', 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=None,
help='override the default public HTTPS image directory; pass an empty value for local preview')
args = parser.parse_args()
if args.list_themes:
themes = read_yaml(DATA / 'themes.yaml')['themes']
print('\n'.join(BASE_THEMES if args.variant == 'base' else 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()