Merge branch 'feat/art-styles' into development

This commit is contained in:
dasemu committed 2026-10-19 04:11:07 +02:00
commit 37e176c194
10 files changed
+934 -160

No files matched your search

+3 -3
View File
@@ -27,7 +27,7 @@ redone unless their input changes.
|---|---|---|
| Text | `fetch`, `parse` | `text.py` |
| Annotation | `annotate chunk/status/prompt/merge` ([details](annotation.md)) | `annotate.py` |
| Assets | `assets prompt/import/process/status/placeholders/sheet` | `assets.py` |
| Assets | `assets prompt/import/process/check/status/placeholders/sheet/migrate` | `assets.py` |
| Ren'Py | `renpy [--from-parsed] [--with-test] [--out DIR]` | `renpy_gen.py` |
`--work DIR` (before the subcommand) selects the work root; default is the current directory.
@@ -44,6 +44,6 @@ redone unless their input changes.
## Asset manifest
`assets/assets.json` lists backgrounds and sprites with a status (`processed`, `approved`,
`placeholder`, ...). Anything missing or unusable is replaced by a generated placeholder, so
`assets/assets.json` (v2) declares art styles and lists backgrounds and sprites, each with
one rendition per style and a status (`processed`, `approved`, `placeholder`, ...). Anything missing or unusable is replaced by a generated placeholder, so
the game always runs.
+45 -4
View File
@@ -27,14 +27,55 @@ uv run vnpipe renpy --out some/dir # default output: <work>/vn
```
Generation is deterministic: running it twice gives identical files (no timestamps).
It rewrites `game/{options,gui,screens,support,characters,images,script}.rpy`,
It rewrites `game/{options,gui,screens,support,styles,characters,images,script}.rpy`,
`game/gui/`, `game/fonts/` and `game/images/`; anything else (for example `game/audio/`)
is left alone. Music only appears in the script for moods that have a matching
`game/audio/<mood>.ogg`, so drop files there and regenerate.
Images come from `assets/assets.json` (statuses `processed`, `approved`,
`placeholder`); anything missing or unusable is replaced by a generated placeholder so
the game always runs.
Images come from `assets/assets.json` (see "Art styles" below); anything missing or
unusable is replaced by a generated placeholder so the game always runs. The generator also
writes `game/styles.rpy` (the first-launch style picker and `persistent.art_style`).
### Art styles and the asset manifest (v2)
`assets/assets.json` declares the art styles once and gives each asset one *rendition* per
style:
```json
{
"default_style": "painterly",
"styles": {"painterly": {"label": "Pictórico", "base_prompt": "...",
"templates": {"background": "...", "sprite": "...", "variant": "..."}}},
"assets": [{"id": "sprite_faust_neutral", "kind": "sprite", "character": "faust",
"expression": "neutral", "prompt": "...", "reference": null,
"renditions": {"painterly": {"source": "chatgpt-web", "generation_id": "...",
"raw_file": "raw/painterly/sprite_faust_neutral.png",
"file": "sprites/painterly/faust_neutral.webp", "sha256": "...",
"status": "approved", "notes": ""}}}]
}
```
The prompt sent is `styles[style].base_prompt` + the kind template + the asset prompt.
Files live in `<kind dir>/<style>/<name>.webp` (raw: `raw/<style>/<asset id>.png`).
Asset commands take `--style` (default: `default_style`):
```sh
vnpipe assets prompt|import|process|placeholders|sheet [--style S] ...
vnpipe assets status [--style S] # asset x style matrix + approved/pending/missing counts
vnpipe assets check [--style S] [IDS] # automatic checks, exit 1 on any failure
vnpipe assets migrate STYLE [--label L] # one-off: v1 manifest -> v2 (old data becomes STYLE)
```
`process` runs the checks on what it processed. Checks: a variant's sha256 differs from its
reference's (same style); a sprite's opaque coverage is 15-85% (measured on the keyed raw
image when it exists, else on the trimmed file) and its bbox does not touch the top edge
(raw only); a background is 1920x1080.
In the game, each image is a `ConditionSwitch` on `persistent.art_style` over the styles
with a `processed`/`approved` rendition; the default style is the fallback (placeholder if
it has none). An image with a single usable style is a plain image. First launch shows a
style picker before the first scene (one button per style label); Preferences has a radio
group to change it. A change applies on the next interaction without moving sprites.
### GUI template and licences
+4 -2
View File
@@ -20,5 +20,7 @@ Emotions: `neutral`, `joyful`, `melancholic`, `solemn`, `ironic`, `angry`, `fear
Unknown line ids, characters, positions or emotions are errors at generation. See
[adaptation-rules.md](adaptation-rules.md) for how these choices are meant to be used.
Asset ids (`bg_*`, sprite names) are defined in the work's `assets/assets.json`; a missing
image is replaced by a placeholder.
Asset ids (`bg_*`, sprite names) and the art styles (`styles`, `default_style`, each with a
label and prompts) are defined in the work's `assets/assets.json` (manifest v2, see
[running.md](running.md)); a missing image is replaced by a placeholder. Style names and
labels are work data: nothing about them is hard-coded in the pipeline.
+295 -55
View File
@@ -1,15 +1,18 @@
"""Asset manifest management: import generated images, key out sprite backgrounds,
fall back to placeholders, and build contact sheets for visual review.
The manifest (``<work>/assets/assets.json``) is the single source of truth for every
image: prompt, origin, hash and review status. Image generation itself happens
The manifest (``<work>/assets/assets.json``, v2) is the single source of truth for every
image. Art *styles* (prompt base + templates) are declared once; each asset has one
*rendition* per style (origin, hash, review status). Image generation itself happens
outside this module (an MCP tool driven by an agent); ``import`` ingests its result.
"""
import argparse
import base64
import hashlib
import io
import json
import shutil
from pathlib import Path
from typing import Any
@@ -27,6 +30,11 @@ USABLE = {"processed", "approved"}
KEY_FULL = 60 # at or above: fully transparent
KEY_NONE = 20 # at or below: fully opaque
# Sprite sanity bounds (checked on the keyed, untrimmed image when the raw file exists).
COVERAGE_MIN = 0.15
COVERAGE_MAX = 0.85
ALPHA_VISIBLE = 16
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -35,6 +43,13 @@ def sha256_file(path: Path) -> str:
def load_manifest(work_root: Path) -> dict[str, Any]:
data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8"))
validate(data, "manifest")
styles = data["styles"]
if data["default_style"] not in styles:
raise ValueError(f"default_style {data['default_style']!r} is not in styles")
for asset in data["assets"]:
unknown = set(asset["renditions"]) - set(styles)
if unknown:
raise ValueError(f"{asset['id']}: renditions for unknown styles {sorted(unknown)}")
return data
@@ -51,11 +66,157 @@ def find_asset(manifest: dict[str, Any], asset_id: str) -> dict[str, Any]:
raise KeyError(f"unknown asset id: {asset_id}")
def full_prompt(manifest: dict[str, Any], asset: dict[str, Any]) -> str:
"""Prompt actually sent to the generator: base + kind template + asset prompt."""
def resolve_style(manifest: dict[str, Any], style: str | None) -> str:
"""``style`` or the manifest default; raises ``ValueError`` for an unknown style."""
style = style or manifest["default_style"]
if style not in manifest["styles"]:
raise ValueError(f"unknown style {style!r}; known: {sorted(manifest['styles'])}")
return style
def asset_name(asset: dict[str, Any]) -> str:
"""File stem: the id without its ``bg_`` / ``sprite_`` prefix."""
return asset["id"].split("_", 1)[1]
def style_file(asset: dict[str, Any], style: str) -> str:
"""Final image path (relative to the assets dir): ``<bg|sprites>/<style>/<name>.webp``."""
kind_dir = "bg" if asset["kind"] == "background" else "sprites"
return f"{kind_dir}/{style}/{asset_name(asset)}.webp"
def raw_path_rel(asset: dict[str, Any], style: str) -> str:
return f"raw/{style}/{asset['id']}.png"
def usable_rendition(asset: dict[str, Any], style: str) -> dict[str, Any] | None:
"""The style's rendition if it is processed/approved, else None."""
rendition = asset["renditions"].get(style)
return rendition if rendition and rendition["status"] in USABLE else None
def full_prompt(manifest: dict[str, Any], asset: dict[str, Any], style: str | None = None) -> str:
"""Prompt actually sent to the generator: style base + kind template + asset prompt."""
cfg = manifest["styles"][resolve_style(manifest, style)]
kind = "variant" if asset.get("reference") and asset["kind"] == "sprite" else asset["kind"]
template = manifest["templates"][kind]
return "\n\n".join(p for p in (manifest["base_prompt"], template, asset["prompt"]) if p)
return "\n\n".join(
p for p in (cfg["base_prompt"], cfg["templates"][kind], asset["prompt"]) if p
)
# --- migration ----------------------------------------------------------------
def migrate_v1(work_root: Path, style: str, label: str | None = None) -> dict[str, Any]:
"""Convert a v1 manifest (flat base_prompt/templates/per-asset files) to v2 in place.
The old data becomes the rendition of ``style`` (the default); image files move into the
per-style directories. Returns the new manifest.
"""
path = work_root / MANIFEST
old = json.loads(path.read_text(encoding="utf-8"))
if "styles" in old:
raise ValueError("manifest is already v2")
assets_dir = work_root / "assets"
new_assets = []
for a in old["assets"]:
asset = {k: a[k] for k in ("id", "kind", "character", "expression", "prompt") if k in a}
asset["reference"] = a.get("reference")
rendition = {
k: a[k]
for k in ("source", "generation_id", "raw_file", "file", "sha256", "status", "notes")
if k in a
}
target = style_file(asset, style)
raw_target = raw_path_rel(asset, style)
for key, dest in (("file", target), ("raw_file", raw_target)):
src = rendition.get(key)
if not src:
continue
if (assets_dir / src).is_file() and src != dest:
(assets_dir / dest).parent.mkdir(parents=True, exist_ok=True)
shutil.move(assets_dir / src, assets_dir / dest)
rendition[key] = dest
asset["renditions"] = {style: rendition}
new_assets.append(asset)
new = {
"default_style": style,
"styles": {
style: {
"label": label or style,
"base_prompt": old["base_prompt"],
"templates": old["templates"],
}
},
"assets": new_assets,
}
save_manifest(work_root, new)
return new
# --- automatic checks -----------------------------------------------------------
def sprite_metrics(img: Image.Image) -> tuple[float, tuple[int, int, int, int] | None]:
"""Opaque-pixel fraction and bbox of the visible area of an RGBA image."""
alpha = img.getchannel("A").point(lambda a: 255 if a > ALPHA_VISIBLE else 0)
hist = alpha.histogram()
return hist[255] / (img.width * img.height), alpha.getbbox()
def check_rendition(
work_root: Path, manifest: dict[str, Any], asset: dict[str, Any], style: str
) -> list[str]:
"""Automatic sanity checks for one usable rendition; returns failure messages."""
rendition = usable_rendition(asset, style)
if not rendition:
return []
assets_dir = work_root / "assets"
final = assets_dir / rendition["file"]
tag = f"{asset['id']} [{style}]"
if not final.is_file():
return [f"{tag}: file {rendition['file']} is missing"]
failures = []
if asset["kind"] == "background":
with Image.open(final) as img:
if img.size != BG_SIZE:
failures.append(
f"{tag}: background is {img.width}x{img.height}, "
f"expected {BG_SIZE[0]}x{BG_SIZE[1]}"
)
else:
raw_rel = rendition.get("raw_file")
raw = assets_dir / raw_rel if raw_rel else None
if raw and raw.is_file(): # untrimmed: coverage and top-edge are meaningful
with Image.open(raw) as img:
coverage, bbox = sprite_metrics(chroma_key(img))
if bbox and bbox[1] <= 0:
failures.append(f"{tag}: sprite touches the top edge (head cropped)")
else: # final files are trimmed to the bbox: only coverage applies
with Image.open(final) as img:
coverage, _ = sprite_metrics(img.convert("RGBA"))
if not COVERAGE_MIN <= coverage <= COVERAGE_MAX:
failures.append(
f"{tag}: sprite opaque coverage {coverage:.0%} outside "
f"{COVERAGE_MIN:.0%}-{COVERAGE_MAX:.0%}"
)
ref_id = asset.get("reference")
if ref_id and asset["kind"] == "sprite":
ref_r = find_asset(manifest, ref_id)["renditions"].get(style)
ref_file = assets_dir / ref_r["file"] if ref_r and ref_r.get("file") else None
if ref_file and ref_file.is_file() and sha256_file(final) == sha256_file(ref_file):
failures.append(f"{tag}: identical to its reference {ref_id} (sha256 match)")
return failures
def check_style(
work_root: Path, manifest: dict[str, Any], style: str, ids: list[str] | None = None
) -> list[str]:
failures: list[str] = []
for asset in manifest["assets"]:
if not ids or asset["id"] in ids:
failures += check_rendition(work_root, manifest, asset, style)
return failures
# --- import -----------------------------------------------------------------
@@ -85,26 +246,30 @@ def decode_output(result: dict[str, Any], index: int = 0) -> bytes:
return raw
def import_image(work_root: Path, asset_id: str, raw: bytes, generation_id: str | None) -> Path:
def import_image(
work_root: Path, asset_id: str, raw: bytes, generation_id: str | None, style: str | None = None
) -> Path:
manifest = load_manifest(work_root)
style = resolve_style(manifest, style)
asset = find_asset(manifest, asset_id)
raw_rel = f"raw/{asset_id}.png"
raw_rel = raw_path_rel(asset, style)
raw_path = work_root / "assets" / raw_rel
raw_path.parent.mkdir(parents=True, exist_ok=True)
with Image.open(_bytes_io(raw)) as img:
with Image.open(io.BytesIO(raw)) as img:
img.convert("RGB").save(raw_path, "PNG")
asset.update(raw_file=raw_rel, generation_id=generation_id, status="generated")
asset.setdefault("source", "chatgpt-web")
rendition = asset["renditions"].setdefault(style, {})
rendition.update(
raw_file=raw_rel,
file=style_file(asset, style),
generation_id=generation_id,
sha256=None,
status="generated",
)
rendition.setdefault("source", "chatgpt-web")
save_manifest(work_root, manifest)
return raw_path
def _bytes_io(raw: bytes):
import io
return io.BytesIO(raw)
# --- processing -------------------------------------------------------------
@@ -137,9 +302,10 @@ def trim_and_scale_sprite(img: Image.Image, height: int = SPRITE_HEIGHT) -> Imag
return img.resize((max(1, round(img.width * scale)), height), Image.Resampling.LANCZOS)
def process_asset(work_root: Path, asset: dict[str, Any]) -> None:
raw_path = work_root / "assets" / asset["raw_file"]
final = work_root / "assets" / asset["file"]
def process_asset(work_root: Path, asset: dict[str, Any], style: str) -> None:
rendition = asset["renditions"][style]
raw_path = work_root / "assets" / rendition["raw_file"]
final = work_root / "assets" / rendition["file"]
final.parent.mkdir(parents=True, exist_ok=True)
with Image.open(raw_path) as img:
if asset["kind"] == "sprite":
@@ -147,8 +313,8 @@ def process_asset(work_root: Path, asset: dict[str, Any]) -> None:
else:
out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS)
out.save(final, "WEBP", quality=90, method=6)
asset["sha256"] = sha256_file(final)
asset["status"] = "processed"
rendition["sha256"] = sha256_file(final)
rendition["status"] = "processed"
def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Image:
@@ -170,20 +336,30 @@ def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Im
return img
def ensure_placeholder(work_root: Path, asset: dict[str, Any]) -> None:
final = work_root / "assets" / asset["file"]
def ensure_placeholder(work_root: Path, asset: dict[str, Any], style: str) -> None:
rendition = asset["renditions"].setdefault(style, {})
rendition["file"] = style_file(asset, style)
final = work_root / "assets" / rendition["file"]
final.parent.mkdir(parents=True, exist_ok=True)
placeholder(asset).save(final, "WEBP", quality=90)
asset.update(source="placeholder", status="placeholder", sha256=sha256_file(final))
rendition.update(source="placeholder", status="placeholder", sha256=sha256_file(final))
def contact_sheet(work_root: Path, ids: list[str], out: Path, thumb: int = 360) -> Path:
def contact_sheet(
work_root: Path, ids: list[str], out: Path, style: str | None = None, thumb: int = 360
) -> Path:
"""Tile raw or processed images (sprites over a checkerboard) for visual review."""
manifest = load_manifest(work_root)
style = resolve_style(manifest, style)
tiles = []
for asset_id in ids:
asset = find_asset(manifest, asset_id)
rel = asset["file"] if asset["status"] in USABLE else asset.get("raw_file")
rendition = asset["renditions"].get(style) or {}
rel = (
rendition.get("file")
if rendition.get("status") in USABLE
else rendition.get("raw_file")
)
if not rel:
continue
with Image.open(work_root / "assets" / rel) as img:
@@ -215,49 +391,97 @@ def _checker(size: tuple[int, int], cell: int = 20) -> Image.Image:
# --- CLI --------------------------------------------------------------------
def _style_of(args: argparse.Namespace, manifest: dict[str, Any]) -> str:
try:
return resolve_style(manifest, args.style)
except ValueError as exc:
raise SystemExit(f"assets: {exc}") from exc
def _cmd_import(args: argparse.Namespace) -> int:
work = load_work(args.work)
style = _style_of(args, load_manifest(work.root))
result = load_tool_result(args.tool_result)
raw = decode_output(result, args.index)
path = import_image(work.root, args.asset_id, raw, result.get("generationId"))
print(f"{args.asset_id}: imported {path} ({len(raw)} bytes, sha256 verified)")
path = import_image(work.root, args.asset_id, raw, result.get("generationId"), style)
print(f"{args.asset_id} [{style}]: imported {path} ({len(raw)} bytes, sha256 verified)")
return 0
def _cmd_process(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
style = _style_of(args, manifest)
done = []
for asset in manifest["assets"]:
if args.ids and asset["id"] not in args.ids:
continue
if asset["status"] == "generated" or (args.force and asset.get("raw_file")):
process_asset(work.root, asset)
print(f"{asset['id']}: processed")
rendition = asset["renditions"].get(style)
if rendition and (
rendition["status"] == "generated" or (args.force and rendition.get("raw_file"))
):
process_asset(work.root, asset, style)
done.append(asset["id"])
print(f"{asset['id']} [{style}]: processed")
save_manifest(work.root, manifest)
return 0
failures = check_style(work.root, manifest, style, done)
for line in failures:
print(f"CHECK FAILED {line}")
return 1 if failures else 0
def _cmd_check(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
styles = [_style_of(args, manifest)] if args.style else list(manifest["styles"])
failures = []
for style in styles:
failures += check_style(work.root, manifest, style, args.ids)
for line in failures:
print(f"CHECK FAILED {line}")
print(f"check: {len(failures)} failure(s) in {', '.join(styles)}")
return 1 if failures else 0
def _bucket(rendition: dict[str, Any] | None) -> str:
if rendition is None:
return "missing"
return "approved" if rendition["status"] == "approved" else "pending"
def _cmd_status(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
if args.set:
asset = find_asset(manifest, args.set[0])
asset["status"] = args.set[1]
style = _style_of(args, manifest)
rendition = find_asset(manifest, args.set[0])["renditions"].get(style)
if rendition is None:
raise SystemExit(f"assets: {args.set[0]} has no {style!r} rendition")
rendition["status"] = args.set[1]
if len(args.set) > 2:
asset["notes"] = args.set[2]
rendition["notes"] = args.set[2]
save_manifest(work.root, manifest)
styles = [_style_of(args, manifest)] if args.style else list(manifest["styles"])
print(f"{'asset':<28}" + "".join(f"{s:<14}" for s in styles))
for asset in manifest["assets"]:
print(f"{asset['status']:<11} {asset['id']}")
cells = [(asset["renditions"].get(s) or {}).get("status", "missing") for s in styles]
print(f"{asset['id']:<28}" + "".join(f"{c:<14}" for c in cells))
for s in styles:
counts = {"approved": 0, "pending": 0, "missing": 0}
for asset in manifest["assets"]:
counts[_bucket(asset["renditions"].get(s))] += 1
print(f"{s}: " + ", ".join(f"{n} {k}" for k, n in counts.items()))
return 0
def _cmd_placeholders(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
style = _style_of(args, manifest)
for asset in manifest["assets"]:
if asset["status"] not in USABLE:
ensure_placeholder(work.root, asset)
print(f"{asset['id']}: placeholder")
if not usable_rendition(asset, style):
ensure_placeholder(work.root, asset, style)
print(f"{asset['id']} [{style}]: placeholder")
save_manifest(work.root, manifest)
return 0
@@ -265,13 +489,21 @@ def _cmd_placeholders(args: argparse.Namespace) -> int:
def _cmd_prompt(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
print(full_prompt(manifest, find_asset(manifest, args.asset_id)))
print(full_prompt(manifest, find_asset(manifest, args.asset_id), _style_of(args, manifest)))
return 0
def _cmd_sheet(args: argparse.Namespace) -> int:
work = load_work(args.work)
print(contact_sheet(work.root, args.ids, args.out))
style = _style_of(args, load_manifest(work.root))
print(contact_sheet(work.root, args.ids, args.out, style))
return 0
def _cmd_migrate(args: argparse.Namespace) -> int:
work = load_work(args.work)
new = migrate_v1(work.root, args.style, args.label)
print(f"migrated {len(new['assets'])} assets to manifest v2 (style {args.style!r})")
return 0
@@ -279,29 +511,37 @@ def register(sub: argparse._SubParsersAction) -> None:
parser = sub.add_parser("assets", help="Manage the asset manifest and images")
cmds = parser.add_subparsers(dest="assets_command", required=True)
p = cmds.add_parser("prompt", help="Print the full generation prompt for an asset")
p.add_argument("asset_id")
p.set_defaults(handler=_cmd_prompt)
def add(name: str, help_: str, handler, style: bool = True) -> argparse.ArgumentParser:
p = cmds.add_parser(name, help=help_)
if style:
p.add_argument("--style", help="Art style id (default: the manifest's default_style)")
p.set_defaults(handler=handler)
return p
p = cmds.add_parser("import", help="Decode a stored query_tasks result into an asset")
p = add("prompt", "Print the full generation prompt for an asset", _cmd_prompt)
p.add_argument("asset_id")
p = add("import", "Decode a stored query_tasks result into an asset", _cmd_import)
p.add_argument("asset_id")
p.add_argument("tool_result", type=Path)
p.add_argument("--index", type=int, default=0)
p.set_defaults(handler=_cmd_import)
p = cmds.add_parser("process", help="Cut out sprites / fit backgrounds")
p = add("process", "Cut out sprites / fit backgrounds, then run the checks", _cmd_process)
p.add_argument("ids", nargs="*")
p.add_argument("--force", action="store_true", help="Reprocess already processed assets")
p.set_defaults(handler=_cmd_process)
p = cmds.add_parser("status", help="List statuses, or --set ID STATUS [NOTE]")
p = add("check", "Automatic checks (all styles unless --style)", _cmd_check)
p.add_argument("ids", nargs="*")
p = add("status", "Per-style status matrix, or --set ID STATUS [NOTE]", _cmd_status)
p.add_argument("--set", nargs="+", metavar="ARG")
p.set_defaults(handler=_cmd_status)
p = cmds.add_parser("placeholders", help="Create placeholders for unusable assets")
p.set_defaults(handler=_cmd_placeholders)
add("placeholders", "Create placeholders for unusable assets", _cmd_placeholders)
p = cmds.add_parser("sheet", help="Build a contact sheet PNG for review")
p = add("sheet", "Build a contact sheet PNG for review", _cmd_sheet)
p.add_argument("out", type=Path)
p.add_argument("ids", nargs="+")
p.set_defaults(handler=_cmd_sheet)
p = add("migrate", "Convert a v1 manifest to v2 (old data becomes STYLE)", _cmd_migrate, False)
p.add_argument("style", help="Style id for the existing renditions")
p.add_argument("--label", help="Display label of that style (default: the id)")
+82 -27
View File
@@ -19,12 +19,12 @@ from typing import Any
from PIL import Image, ImageDraw
from vnpipe import PACKAGE_DIR
from vnpipe.assets import USABLE, load_manifest, placeholder
from vnpipe.assets import load_manifest, placeholder, style_file, usable_rendition
from vnpipe.config import Work, load_work
from vnpipe.schema import validate
TEMPLATE_DIR = PACKAGE_DIR / "renpy_templates"
USABLE_STATUS = USABLE | {"placeholder"}
NO_MANIFEST_STYLE = {"default": {"label": "Default"}} # work without an asset manifest
ADV_MAX_LINES = 4
NVL_MAX_LINES = 8
@@ -59,6 +59,11 @@ ABOUT_LABELS = {
"es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."),
"en": ("Text", "Translation", "Visual novel adaptation generated with vnpipe."),
}
# (preferences title and picker heading, picker hint) per work language
ART_STYLE_LABELS = {
"es": ("Estilo visual", "Puedes cambiarlo más tarde en Preferencias."),
"en": ("Visual style", "You can change this later in Preferences."),
}
# --- text helpers -------------------------------------------------------------
@@ -155,9 +160,11 @@ def annotations_from_parsed(work: Work, parsed: dict[str, Any]) -> dict[str, Any
@dataclass
class ImageEntry:
name: str # Ren'Py image name, e.g. "bg heaven" or "hero neutral"
rel: str # path below game/images/
asset: dict[str, Any]
source: Path | None # file to copy, or None to generate a placeholder
default: str # default style id: always present, the ConditionSwitch fallback
# (style, path below game/images/, file to copy or None for a placeholder), default style
# first, then the other styles with an approved rendition in manifest order
variants: list[tuple[str, str, Path | None]]
def _sprite_asset(character: str, expression: str) -> dict[str, Any]:
@@ -166,16 +173,12 @@ def _sprite_asset(character: str, expression: str) -> dict[str, Any]:
"kind": "sprite",
"character": character,
"expression": expression,
"file": f"sprites/{character}_{expression}.webp",
"renditions": {},
}
def _bg_asset(asset_id: str) -> dict[str, Any]:
return {
"id": asset_id,
"kind": "background",
"file": f"bg/{asset_id.removeprefix('bg_')}.webp",
}
return {"id": asset_id, "kind": "background", "renditions": {}}
def _needed_bg_ids(work: Work) -> list[str]:
@@ -184,8 +187,16 @@ def _needed_bg_ids(work: Work) -> list[str]:
return ids
def art_styles(manifest: dict[str, Any] | None) -> tuple[dict[str, Any], str]:
"""(styles by id, default style id); a single pseudo-style when there is no manifest."""
if manifest is None:
return NO_MANIFEST_STYLE, next(iter(NO_MANIFEST_STYLE))
return manifest["styles"], manifest["default_style"]
def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEntry]:
"""Every image the project declares: manifest assets plus anything the staging needs."""
styles, default = art_styles(manifest)
assets: dict[str, dict[str, Any]] = {}
for asset in (manifest or {}).get("assets", []):
assets[asset["id"]] = asset
@@ -204,12 +215,18 @@ def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEnt
name = bg_image_name(asset_id)
else:
name = f"{asset['character']} {asset['expression']}"
source = None
if asset.get("status") in USABLE_STATUS and asset.get("file"):
candidate = work.path("assets") / asset["file"]
if candidate.is_file():
source = candidate
entries.append(ImageEntry(name, asset["file"], asset, source))
variants: list[tuple[str, str, Path | None]] = []
for style in [default, *(s for s in styles if s != default)]:
rendition = asset["renditions"].get(style)
rel = (rendition or {}).get("file") or style_file(asset, style)
candidate = work.path("assets") / rel
if style == default:
# the fallback may also be a placeholder; otherwise one is generated
ok = rendition and rendition["status"] in {"processed", "approved", "placeholder"}
variants.append((style, rel, candidate if ok and candidate.is_file() else None))
elif usable_rendition(asset, style) and candidate.is_file():
variants.append((style, rel, candidate))
entries.append(ImageEntry(name, asset, default, variants))
return entries
@@ -467,6 +484,7 @@ def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str
"## Generated by `vnpipe renpy`. Do not edit: regenerate instead.",
"",
"label start:",
" call vn_pick_art_style",
" window auto",
"",
]
@@ -579,12 +597,27 @@ testcase default:
$ _test.timeout = 30.0
pause 1.0
click "Start"
advance until eval (e2e_state["end"]) timeout 900
@@PICK@@ advance until eval (e2e_state["end"]) timeout 900
advance until screen "main_menu" timeout 60
assert eval (e2e_state["end"])
"""
def render_e2e(styles: dict[str, Any]) -> str:
"""The playthrough testcase; with a style choice it also exercises the first-launch picker
(picking the last style, so the non-default switch branch is the one in use)."""
pick = ""
if len(styles) > 1:
sid, cfg = list(styles.items())[-1]
pick = (
" pause 1.0\n"
' assert screen "vn_art_style_picker"\n'
f" click {_plain_quote(cfg['label'])}\n"
f" assert eval (persistent.art_style == {sid!r})\n"
)
return E2E_TESTCASE.replace("@@PICK@@", pick)
# --- static project files -----------------------------------------------------------------
@@ -619,12 +652,25 @@ def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, str]:
return cards
def render_image_entry(e: ImageEntry) -> str:
"""Plain image, or a ConditionSwitch on ``persistent.art_style`` with the default last."""
default_rel = e.variants[0][1]
if len(e.variants) == 1:
return f"image {e.name} = {_plain_quote('images/' + default_rel)}"
parts = []
for style, rel, _ in e.variants[1:]:
parts.append(
f"{_plain_quote(f'persistent.art_style == {style!r}')}, {_plain_quote('images/' + rel)}"
)
parts.append(f'"True", {_plain_quote("images/" + default_rel)}')
return f"image {e.name} = ConditionSwitch({', '.join(parts)})"
def render_images(entries: list[ImageEntry], cards: dict[str, str]) -> str:
out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""]
for name, text in cards.items(): # title cards: plain images, not `show text`
out.append(f'image {name} = Text("{escape_text(text)}", size=60, text_align=0.5)')
for e in entries:
out.append(f"image {e.name} = {_plain_quote('images/' + e.rel)}")
out.extend(render_image_entry(e) for e in entries)
out.append("")
return "\n".join(out)
@@ -678,7 +724,15 @@ def generate(
first_bg = info.get("menu_bg") or next((c["bg"] for c in staging.values() if c.get("bg")), None)
if first_bg:
menu_bg = bg_image_name(first_bg)
styles, default_style = art_styles(manifest)
picker_title, picker_hint = ART_STYLE_LABELS.get(
info.get("language", "es"), ART_STYLE_LABELS["en"]
)
values = {
"ART_STYLES": repr([(sid, cfg["label"]) for sid, cfg in styles.items()]),
"DEFAULT_STYLE": default_style,
"ART_STYLE_TITLE": picker_title,
"ART_STYLE_HINT": picker_hint,
"TITLE": escape_text(info["title"]),
"VERSION": "0.1",
"ABOUT": _about(work),
@@ -707,7 +761,7 @@ def generate(
test_file = game / E2E_FILE
test_file.unlink(missing_ok=True)
if with_test:
write_text(test_file, E2E_TESTCASE)
write_text(test_file, render_e2e(styles))
written.append(test_file)
for name, text in (
("characters.rpy", render_characters(work)),
@@ -718,13 +772,14 @@ def generate(
written.append(game / name)
for e in entries:
dest = game / "images" / e.rel
dest.parent.mkdir(parents=True, exist_ok=True)
written.append(dest)
if e.source:
shutil.copyfile(e.source, dest)
else:
placeholder(e.asset).save(dest, "WEBP", quality=90)
for _, rel, source in e.variants:
dest = game / "images" / rel
dest.parent.mkdir(parents=True, exist_ok=True)
written.append(dest)
if source:
shutil.copyfile(source, dest)
else:
placeholder(e.asset).save(dest, "WEBP", quality=90)
return sorted(written)
@@ -756,6 +756,14 @@ screen preferences():
textbutton _("After Choices") action Preference("after choices", "toggle")
textbutton _("Transitions") action InvertSelected(Preference("transitions", "toggle"))
if len(vn_art_styles) > 1:
vbox:
style_prefix "radio"
label "@@ART_STYLE_TITLE@@"
for style_id, style_label in vn_art_styles:
textbutton style_label action SetField(persistent, "art_style", style_id)
## Additional vboxes of type "radio_pref" or "check_pref" can be
## added here, to add additional creator-defined preferences.
@@ -0,0 +1,39 @@
## Art styles: the player picks one at first launch and can change it in Preferences.
## Every image is a ConditionSwitch on `persistent.art_style` (see images.rpy), so a
## change takes effect on the next interaction without moving anything on stage.
## Static except for the substituted style list; copied by `vnpipe renpy`.
default persistent.art_style = "@@DEFAULT_STYLE@@"
default persistent.art_style_chosen = False
## (style id, label) pairs, in manifest order.
define vn_art_styles = @@ART_STYLES@@
screen vn_art_style_picker():
modal True
add Solid("#000000")
vbox:
xalign 0.5
yalign 0.5
spacing 30
text "@@ART_STYLE_TITLE@@" xalign 0.5 size 60
text "@@ART_STYLE_HINT@@" xalign 0.5 size 28
null height 20
for style_id, style_label in vn_art_styles:
textbutton style_label:
xalign 0.5
action [SetField(persistent, "art_style", style_id),
SetField(persistent, "art_style_chosen", True), Return()]
## Shown once, before the first scene, when there is a choice to make.
label vn_pick_art_style:
if len(vn_art_styles) > 1 and not persistent.art_style_chosen:
scene black
call screen vn_art_style_picker
return
+98 -64
View File
@@ -4,15 +4,50 @@
"title": "Asset manifest",
"type": "object",
"required": [
"base_prompt",
"templates",
"default_style",
"styles",
"assets"
],
"additionalProperties": false,
"properties": {
"base_prompt": {
"default_style": {
"type": "string"
},
"styles": {
"type": "object",
"minProperties": 1,
"additionalProperties": {
"type": "object",
"required": [
"label",
"base_prompt",
"templates"
],
"additionalProperties": false,
"properties": {
"label": {
"type": "string",
"description": "Player-facing name of the style"
},
"base_prompt": {
"type": "string"
},
"templates": {
"type": "object",
"required": [
"background",
"sprite",
"variant"
],
"additionalProperties": {
"type": "string"
},
"description": "Kind-specific prompt templates appended after base_prompt"
}
}
},
"description": "Art styles keyed by style id"
},
"assets": {
"type": "array",
"items": {
@@ -21,10 +56,7 @@
"id",
"kind",
"prompt",
"source",
"file",
"sha256",
"status"
"renditions"
],
"additionalProperties": false,
"properties": {
@@ -47,21 +79,7 @@
},
"prompt": {
"type": "string",
"description": "Asset-specific prompt; the full prompt sent is base_prompt + kind prompt + this"
},
"source": {
"enum": [
"chatgpt-web",
"zenvairo-media",
"placeholder",
"manual"
]
},
"generation_id": {
"type": [
"string",
"null"
]
"description": "Asset-specific prompt; the full prompt sent is the style's base_prompt + kind template + this"
},
"reference": {
"type": [
@@ -70,51 +88,67 @@
],
"description": "Asset id used as reference image (identity consistency)"
},
"raw_file": {
"type": [
"string",
"null"
],
"description": "Original generated image, relative to the work's assets dir"
},
"file": {
"type": "string",
"description": "Final processed image used by the game, relative to the work's assets dir"
},
"sha256": {
"type": [
"string",
"null"
],
"pattern": "^[0-9a-f]{64}$"
},
"status": {
"enum": [
"planned",
"generated",
"processed",
"approved",
"rejected",
"placeholder"
]
},
"notes": {
"type": "string"
"renditions": {
"type": "object",
"additionalProperties": {
"type": "object",
"required": [
"file",
"status"
],
"additionalProperties": false,
"properties": {
"source": {
"enum": [
"chatgpt-web",
"zenvairo-media",
"placeholder",
"manual"
]
},
"generation_id": {
"type": [
"string",
"null"
]
},
"raw_file": {
"type": [
"string",
"null"
],
"description": "Original generated image, relative to the work's assets dir"
},
"file": {
"type": "string",
"description": "Final processed image used by the game, relative to the work's assets dir"
},
"sha256": {
"type": [
"string",
"null"
],
"pattern": "^[0-9a-f]{64}$"
},
"status": {
"enum": [
"planned",
"generated",
"processed",
"approved",
"rejected",
"placeholder"
]
},
"notes": {
"type": "string"
}
}
},
"description": "One image per art style, keyed by style id"
}
}
}
},
"templates": {
"type": "object",
"required": [
"background",
"sprite",
"variant"
],
"additionalProperties": {
"type": "string"
},
"description": "Kind-specific prompt templates appended after base_prompt"
}
}
}
+355
View File
@@ -0,0 +1,355 @@
import json
import os
import shutil
import subprocess
from pathlib import Path
import pytest
import test_renpy_gen
from PIL import Image
from vnpipe import assets, cli, renpy_gen
from vnpipe.config import load_work
from vnpipe.schema import SchemaError
FIXTURES = Path(__file__).parent / "fixtures"
STYLES = {
"paint": {
"label": "Paint",
"base_prompt": "PAINT base.",
"templates": {
"background": "PAINT bg.",
"sprite": "PAINT sprite.",
"variant": "PAINT var.",
},
},
"ink": {
"label": "Ink",
"base_prompt": "INK base.",
"templates": {"background": "INK bg.", "sprite": "INK sprite.", "variant": "INK var."},
},
}
def v2_manifest() -> dict:
return {
"default_style": "paint",
"styles": json.loads(json.dumps(STYLES)),
"assets": [
{
"id": "bg_theatre",
"kind": "background",
"prompt": "A stage.",
"reference": None,
"renditions": {},
},
{
"id": "sprite_poet_neutral",
"kind": "sprite",
"character": "poet",
"expression": "neutral",
"prompt": "Neutral.",
"reference": None,
"renditions": {},
},
{
"id": "sprite_poet_indignant",
"kind": "sprite",
"character": "poet",
"expression": "indignant",
"prompt": "Angry.",
"reference": "sprite_poet_neutral",
"renditions": {},
},
],
}
@pytest.fixture
def work_root(tmp_path):
root = tmp_path / "w"
shutil.copytree(FIXTURES / "mini_work", root)
(root / "assets").mkdir()
assets.save_manifest(root, v2_manifest())
return root
def green_sprite(path: Path, fill: float = 0.4, top: int = 100) -> None:
"""1000x1500 chroma-green field with an opaque block of roughly ``fill`` of the area."""
img = Image.new("RGB", (1000, 1500), (0, 177, 64))
h = round(1500 * fill)
img.paste((120, 60, 50), (250, top, 750, min(1500, top + h * 2)))
path.parent.mkdir(parents=True, exist_ok=True)
img.save(path)
def set_rendition(root, asset_id, style, **fields):
manifest = assets.load_manifest(root)
asset = assets.find_asset(manifest, asset_id)
rendition = asset["renditions"].setdefault(style, {"file": assets.style_file(asset, style)})
rendition.update(fields)
assets.save_manifest(root, manifest)
def test_schema_rejects_v1_shape():
old = {"base_prompt": "x", "templates": {}, "assets": []}
with pytest.raises(SchemaError):
assets.validate(old, "manifest")
def test_unknown_style_and_default(work_root):
manifest = assets.load_manifest(work_root)
assert assets.resolve_style(manifest, None) == "paint"
with pytest.raises(ValueError, match="unknown style"):
assets.resolve_style(manifest, "nope")
manifest["default_style"] = "nope"
(work_root / assets.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
with pytest.raises(ValueError, match="default_style"):
assets.load_manifest(work_root)
def test_full_prompt_per_style(work_root):
manifest = assets.load_manifest(work_root)
bg, base, var = manifest["assets"]
assert assets.full_prompt(manifest, bg) == "PAINT base.\n\nPAINT bg.\n\nA stage."
assert assets.full_prompt(manifest, bg, "ink").startswith("INK base.\n\nINK bg.")
assert "INK sprite." in assets.full_prompt(manifest, base, "ink")
assert "INK var." in assets.full_prompt(manifest, var, "ink")
def test_style_file_layout():
bg, sprite = v2_manifest()["assets"][:2]
assert assets.style_file(bg, "ink") == "bg/ink/theatre.webp"
assert assets.style_file(sprite, "ink") == "sprites/ink/poet_neutral.webp"
assert assets.raw_path_rel(sprite, "ink") == "raw/ink/sprite_poet_neutral.png"
def test_import_and_process_per_style(work_root):
green_sprite(work_root / "assets/raw/ink/sprite_poet_neutral.png")
raw = (work_root / "assets/raw/ink/sprite_poet_neutral.png").read_bytes()
assets.import_image(work_root, "sprite_poet_neutral", raw, "gid-1", "ink")
manifest = assets.load_manifest(work_root)
rendition = manifest["assets"][1]["renditions"]["ink"]
assert (
rendition["status"] == "generated" and rendition["file"] == "sprites/ink/poet_neutral.webp"
)
assert "paint" not in manifest["assets"][1]["renditions"]
assert cli.main(["--work", str(work_root), "assets", "process", "--style", "ink"]) == 0
manifest = assets.load_manifest(work_root)
rendition = manifest["assets"][1]["renditions"]["ink"]
assert rendition["status"] == "processed" and rendition["sha256"]
assert (work_root / "assets/sprites/ink/poet_neutral.webp").is_file()
def test_status_matrix(work_root, capsys):
set_rendition(work_root, "bg_theatre", "paint", status="approved")
set_rendition(work_root, "bg_theatre", "ink", status="generated")
assert cli.main(["--work", str(work_root), "assets", "status"]) == 0
out = capsys.readouterr().out
theatre = next(ln for ln in out.splitlines() if ln.startswith("bg_theatre"))
assert theatre.split() == ["bg_theatre", "approved", "generated"]
assert "paint: 1 approved, 0 pending, 2 missing" in out
assert "ink: 0 approved, 1 pending, 2 missing" in out
def test_placeholders_only_for_chosen_style(work_root):
cli.main(["--work", str(work_root), "assets", "placeholders", "--style", "ink"])
manifest = assets.load_manifest(work_root)
assert all(set(a["renditions"]) == {"ink"} for a in manifest["assets"])
assert (work_root / "assets/bg/ink/theatre.webp").is_file()
assert not (work_root / "assets/bg/paint").exists()
def test_check_background_size(work_root):
path = work_root / "assets/bg/paint/theatre.webp"
path.parent.mkdir(parents=True)
Image.new("RGB", (1280, 720)).save(path)
set_rendition(work_root, "bg_theatre", "paint", status="approved")
manifest = assets.load_manifest(work_root)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "1280x720" in msg
Image.new("RGB", assets.BG_SIZE).save(path)
assert assets.check_style(work_root, manifest, "paint") == []
def test_check_sprite_coverage_and_top_edge(work_root):
raw = work_root / "assets/raw/paint/sprite_poet_neutral.png"
final = work_root / "assets/sprites/paint/poet_neutral.webp"
final.parent.mkdir(parents=True)
Image.new("RGBA", (10, 10)).save(final)
set_rendition(
work_root,
"sprite_poet_neutral",
"paint",
status="approved",
raw_file="raw/paint/sprite_poet_neutral.png",
)
manifest = assets.load_manifest(work_root)
green_sprite(raw, fill=0.4) # 500x1200 block of 1000x1500 = 40%
assert assets.check_style(work_root, manifest, "paint") == []
green_sprite(raw, fill=0.4, top=0)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "top edge" in msg
green_sprite(raw, fill=0.05) # 500x150 = 10%
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "coverage" in msg
def test_check_variant_identical_to_reference(work_root):
for name in ("poet_neutral", "poet_indignant"):
path = work_root / f"assets/sprites/paint/{name}.webp"
path.parent.mkdir(parents=True, exist_ok=True)
img = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
img.paste((10, 10, 10, 255), (20, 20, 80, 80))
img.save(path) # byte-identical files
for asset_id in ("sprite_poet_neutral", "sprite_poet_indignant"):
set_rendition(work_root, asset_id, "paint", status="approved")
manifest = assets.load_manifest(work_root)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "sprite_poet_indignant" in msg and "identical to its reference" in msg
# same asset under another style is not compared with the paint reference
assert assets.check_style(work_root, manifest, "ink") == []
assert cli.main(["--work", str(work_root), "assets", "check"]) == 1
def test_process_runs_checks_and_fails(work_root):
green_sprite(work_root / "assets/raw/paint/sprite_poet_neutral.png", top=0)
set_rendition(
work_root,
"sprite_poet_neutral",
"paint",
status="generated",
raw_file="raw/paint/sprite_poet_neutral.png",
)
assert cli.main(["--work", str(work_root), "assets", "process"]) == 1
def test_migrate_v1(tmp_path):
root = tmp_path / "w"
shutil.copytree(FIXTURES / "mini_work", root)
(root / "assets/bg").mkdir(parents=True)
(root / "assets/raw").mkdir()
(root / "assets/bg/theatre.webp").write_bytes(b"x")
(root / "assets/raw/bg_theatre.png").write_bytes(b"y")
old = {
"base_prompt": "B",
"templates": {"background": "b", "sprite": "s", "variant": "v"},
"assets": [
{
"id": "bg_theatre",
"kind": "background",
"prompt": "P",
"source": "chatgpt-web",
"generation_id": "g",
"reference": None,
"raw_file": "raw/bg_theatre.png",
"file": "bg/theatre.webp",
"sha256": "a" * 64,
"status": "approved",
"notes": "n",
}
],
}
(root / assets.MANIFEST).write_text(json.dumps(old), encoding="utf-8")
assert cli.main(["--work", str(root), "assets", "migrate", "paint", "--label", "Paint"]) == 0
manifest = assets.load_manifest(root)
assert manifest["default_style"] == "paint"
assert manifest["styles"]["paint"] == {
"label": "Paint",
"base_prompt": "B",
"templates": old["templates"],
}
rendition = manifest["assets"][0]["renditions"]["paint"]
assert (
rendition["file"] == "bg/paint/theatre.webp"
and rendition["raw_file"] == "raw/paint/bg_theatre.png"
)
assert rendition["status"] == "approved" and rendition["notes"] == "n"
assert (root / "assets/bg/paint/theatre.webp").read_bytes() == b"x"
assert (root / "assets/raw/paint/bg_theatre.png").read_bytes() == b"y"
assert not (root / "assets/bg/theatre.webp").exists()
with pytest.raises(ValueError, match="already v2"):
assets.migrate_v1(root, "paint")
# --- Ren'Py generation ------------------------------------------------------------------------
def gen(work_root, tmp_path, with_test=False):
work = load_work(work_root)
annotated = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8"))
out = tmp_path / "proj"
renpy_gen.generate(work, annotated, out, with_test=with_test)
return out
def approve(root, asset_id, style, size=(100, 100)):
manifest = assets.load_manifest(root)
asset = assets.find_asset(manifest, asset_id)
path = root / "assets" / assets.style_file(asset, style)
path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGBA", size, (5, 5, 5, 255)).save(path)
set_rendition(root, asset_id, style, status="approved")
def test_renpy_condition_switch_and_fallback(work_root, tmp_path):
approve(work_root, "bg_theatre", "paint")
approve(work_root, "bg_theatre", "ink")
approve(work_root, "sprite_poet_neutral", "paint") # only the default style
approve(work_root, "sprite_poet_indignant", "ink") # only a non-default style
out = gen(work_root, tmp_path)
images = (out / "game/images.rpy").read_text(encoding="utf-8")
assert (
"image bg theatre = ConditionSwitch(\"persistent.art_style == 'ink'\", "
'"images/bg/ink/theatre.webp", "True", "images/bg/paint/theatre.webp")'
) in images
assert 'image poet neutral = "images/sprites/paint/poet_neutral.webp"' in images
# ink-only rendition: the default style still needs a (placeholder) fallback file
assert "images/sprites/ink/poet_indignant.webp" in images
assert (
'ConditionSwitch("persistent.art_style == \'ink\'", "images/sprites/ink/poet_indignant'
in images
)
assert (out / "game/images/sprites/paint/poet_indignant.webp").is_file()
assert (out / "game/images/bg/ink/theatre.webp").is_file()
styles = (out / "game/styles.rpy").read_text(encoding="utf-8")
assert 'default persistent.art_style = "paint"' in styles
assert "define vn_art_styles = [('paint', 'Paint'), ('ink', 'Ink')]" in styles
assert "@@" not in styles
assert "call vn_pick_art_style" in (out / "game/script.rpy").read_text(encoding="utf-8")
screens = (out / "game/screens.rpy").read_text(encoding="utf-8")
assert "Estilo visual" in screens and 'SetField(persistent, "art_style", style_id)' in screens
def test_renpy_no_anime_renditions_is_plain_default(work_root, tmp_path):
approve(work_root, "bg_theatre", "paint")
set_rendition(work_root, "bg_theatre", "ink", status="generated") # not approved: ignored
out = gen(work_root, tmp_path)
images = (out / "game/images.rpy").read_text(encoding="utf-8")
assert 'image bg theatre = "images/bg/paint/theatre.webp"' in images
assert "ConditionSwitch" not in images
assert not (out / "game/images/bg/ink").exists()
def test_e2e_picks_last_style(work_root, tmp_path):
out = gen(work_root, tmp_path, with_test=True)
text = (out / "game/e2e_test.rpy").read_text(encoding="utf-8")
assert 'click "Ink"' in text and 'assert screen "vn_art_style_picker"' in text
assert "@@" not in text
@pytest.mark.skipif(not test_renpy_gen.SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)")
def test_two_style_project_lints_and_plays(work_root, tmp_path):
"""Picker, preferences and ConditionSwitch images in a real Ren'Py run."""
approve(work_root, "bg_theatre", "paint")
approve(work_root, "bg_theatre", "ink")
out = gen(work_root, tmp_path, with_test=True)
home = tmp_path / "home"
home.mkdir()
env = {**os.environ, "HOME": str(home)}
lint = subprocess.run(
[str(test_renpy_gen.SDK), str(out), "lint"], capture_output=True, text=True, env=env
)
report = lint.stdout + lint.stderr
assert lint.returncode == 0 and "error" not in report.lower(), report
test_renpy_gen.run_e2e(out, home)
+5 -5
View File
@@ -162,11 +162,11 @@ def test_characters_and_images(project):
nameless_nvl = next(ln for ln in chars.split("\n") if ln.startswith("define c_poet_voice_nvl"))
assert "None" in nameless_nvl and "nvl_thought" in nameless_nvl
images = (project / "game/images.rpy").read_text(encoding="utf-8")
assert 'image bg dedication = "images/bg/dedication.webp"' in images
assert 'image director pleased = "images/sprites/director_pleased.webp"' in images
assert (project / "game/images/sprites/poet_indignant.webp").is_file()
assert (project / "game/images/bg/theatre.webp").is_file()
assert not (project / "game/images/sprites/lord_neutral.webp").exists()
assert 'image bg dedication = "images/bg/default/dedication.webp"' in images
assert 'image director pleased = "images/sprites/default/director_pleased.webp"' in images
assert (project / "game/images/sprites/default/poet_indignant.webp").is_file()
assert (project / "game/images/bg/default/theatre.webp").is_file()
assert not (project / "game/images/sprites/default/lord_neutral.webp").exists()
def test_title_card_images(project):