mirror of
https://github.com/Dasemu/vnpipe.git
synced 2026-11-26 15:26:27 +00:00
Merge branch 'feat/art-styles' into development
This commit is contained in:
commit
37e176c194
10 files changed
+934
-160
No files matched your search
+3
-3
@@ -27,7 +27,7 @@ redone unless their input changes.
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Text | `fetch`, `parse` | `text.py` |
|
| Text | `fetch`, `parse` | `text.py` |
|
||||||
| Annotation | `annotate chunk/status/prompt/merge` ([details](annotation.md)) | `annotate.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` |
|
| 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.
|
`--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
|
## Asset manifest
|
||||||
|
|
||||||
`assets/assets.json` lists backgrounds and sprites with a status (`processed`, `approved`,
|
`assets/assets.json` (v2) declares art styles and lists backgrounds and sprites, each with
|
||||||
`placeholder`, ...). Anything missing or unusable is replaced by a generated placeholder, so
|
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.
|
the game always runs.
|
||||||
+45
-4
@@ -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).
|
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/`)
|
`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
|
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.
|
`game/audio/<mood>.ogg`, so drop files there and regenerate.
|
||||||
|
|
||||||
Images come from `assets/assets.json` (statuses `processed`, `approved`,
|
Images come from `assets/assets.json` (see "Art styles" below); anything missing or
|
||||||
`placeholder`); anything missing or unusable is replaced by a generated placeholder so
|
unusable is replaced by a generated placeholder so the game always runs. The generator also
|
||||||
the game always runs.
|
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
|
### GUI template and licences
|
||||||
|
|
||||||
|
|||||||
+4
-2
@@ -20,5 +20,7 @@ Emotions: `neutral`, `joyful`, `melancholic`, `solemn`, `ironic`, `angry`, `fear
|
|||||||
Unknown line ids, characters, positions or emotions are errors at generation. See
|
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.
|
[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
|
Asset ids (`bg_*`, sprite names) and the art styles (`styles`, `default_style`, each with a
|
||||||
image is replaced by a placeholder.
|
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
@@ -1,15 +1,18 @@
|
|||||||
"""Asset manifest management: import generated images, key out sprite backgrounds,
|
"""Asset manifest management: import generated images, key out sprite backgrounds,
|
||||||
fall back to placeholders, and build contact sheets for visual review.
|
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
|
The manifest (``<work>/assets/assets.json``, v2) is the single source of truth for every
|
||||||
image: prompt, origin, hash and review status. Image generation itself happens
|
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.
|
outside this module (an MCP tool driven by an agent); ``import`` ingests its result.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import base64
|
import base64
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
|
import shutil
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -27,6 +30,11 @@ USABLE = {"processed", "approved"}
|
|||||||
KEY_FULL = 60 # at or above: fully transparent
|
KEY_FULL = 60 # at or above: fully transparent
|
||||||
KEY_NONE = 20 # at or below: fully opaque
|
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:
|
def sha256_file(path: Path) -> str:
|
||||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
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]:
|
def load_manifest(work_root: Path) -> dict[str, Any]:
|
||||||
data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8"))
|
data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8"))
|
||||||
validate(data, "manifest")
|
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
|
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}")
|
raise KeyError(f"unknown asset id: {asset_id}")
|
||||||
|
|
||||||
|
|
||||||
def full_prompt(manifest: dict[str, Any], asset: dict[str, Any]) -> str:
|
def resolve_style(manifest: dict[str, Any], style: str | None) -> str:
|
||||||
"""Prompt actually sent to the generator: base + kind template + asset prompt."""
|
"""``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"]
|
kind = "variant" if asset.get("reference") and asset["kind"] == "sprite" else asset["kind"]
|
||||||
template = manifest["templates"][kind]
|
return "\n\n".join(
|
||||||
return "\n\n".join(p for p in (manifest["base_prompt"], template, asset["prompt"]) if p)
|
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 -----------------------------------------------------------------
|
# --- import -----------------------------------------------------------------
|
||||||
@@ -85,26 +246,30 @@ def decode_output(result: dict[str, Any], index: int = 0) -> bytes:
|
|||||||
return raw
|
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)
|
manifest = load_manifest(work_root)
|
||||||
|
style = resolve_style(manifest, style)
|
||||||
asset = find_asset(manifest, asset_id)
|
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 = work_root / "assets" / raw_rel
|
||||||
raw_path.parent.mkdir(parents=True, exist_ok=True)
|
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")
|
img.convert("RGB").save(raw_path, "PNG")
|
||||||
asset.update(raw_file=raw_rel, generation_id=generation_id, status="generated")
|
rendition = asset["renditions"].setdefault(style, {})
|
||||||
asset.setdefault("source", "chatgpt-web")
|
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)
|
save_manifest(work_root, manifest)
|
||||||
return raw_path
|
return raw_path
|
||||||
|
|
||||||
|
|
||||||
def _bytes_io(raw: bytes):
|
|
||||||
import io
|
|
||||||
|
|
||||||
return io.BytesIO(raw)
|
|
||||||
|
|
||||||
|
|
||||||
# --- processing -------------------------------------------------------------
|
# --- 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)
|
return img.resize((max(1, round(img.width * scale)), height), Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
|
|
||||||
def process_asset(work_root: Path, asset: dict[str, Any]) -> None:
|
def process_asset(work_root: Path, asset: dict[str, Any], style: str) -> None:
|
||||||
raw_path = work_root / "assets" / asset["raw_file"]
|
rendition = asset["renditions"][style]
|
||||||
final = work_root / "assets" / asset["file"]
|
raw_path = work_root / "assets" / rendition["raw_file"]
|
||||||
|
final = work_root / "assets" / rendition["file"]
|
||||||
final.parent.mkdir(parents=True, exist_ok=True)
|
final.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with Image.open(raw_path) as img:
|
with Image.open(raw_path) as img:
|
||||||
if asset["kind"] == "sprite":
|
if asset["kind"] == "sprite":
|
||||||
@@ -147,8 +313,8 @@ def process_asset(work_root: Path, asset: dict[str, Any]) -> None:
|
|||||||
else:
|
else:
|
||||||
out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS)
|
out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS)
|
||||||
out.save(final, "WEBP", quality=90, method=6)
|
out.save(final, "WEBP", quality=90, method=6)
|
||||||
asset["sha256"] = sha256_file(final)
|
rendition["sha256"] = sha256_file(final)
|
||||||
asset["status"] = "processed"
|
rendition["status"] = "processed"
|
||||||
|
|
||||||
|
|
||||||
def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Image:
|
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
|
return img
|
||||||
|
|
||||||
|
|
||||||
def ensure_placeholder(work_root: Path, asset: dict[str, Any]) -> None:
|
def ensure_placeholder(work_root: Path, asset: dict[str, Any], style: str) -> None:
|
||||||
final = work_root / "assets" / asset["file"]
|
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)
|
final.parent.mkdir(parents=True, exist_ok=True)
|
||||||
placeholder(asset).save(final, "WEBP", quality=90)
|
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."""
|
"""Tile raw or processed images (sprites over a checkerboard) for visual review."""
|
||||||
manifest = load_manifest(work_root)
|
manifest = load_manifest(work_root)
|
||||||
|
style = resolve_style(manifest, style)
|
||||||
tiles = []
|
tiles = []
|
||||||
for asset_id in ids:
|
for asset_id in ids:
|
||||||
asset = find_asset(manifest, asset_id)
|
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:
|
if not rel:
|
||||||
continue
|
continue
|
||||||
with Image.open(work_root / "assets" / rel) as img:
|
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 --------------------------------------------------------------------
|
# --- 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:
|
def _cmd_import(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
work = load_work(args.work)
|
||||||
|
style = _style_of(args, load_manifest(work.root))
|
||||||
result = load_tool_result(args.tool_result)
|
result = load_tool_result(args.tool_result)
|
||||||
raw = decode_output(result, args.index)
|
raw = decode_output(result, args.index)
|
||||||
path = import_image(work.root, args.asset_id, raw, result.get("generationId"))
|
path = import_image(work.root, args.asset_id, raw, result.get("generationId"), style)
|
||||||
print(f"{args.asset_id}: imported {path} ({len(raw)} bytes, sha256 verified)")
|
print(f"{args.asset_id} [{style}]: imported {path} ({len(raw)} bytes, sha256 verified)")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def _cmd_process(args: argparse.Namespace) -> int:
|
def _cmd_process(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
work = load_work(args.work)
|
||||||
manifest = load_manifest(work.root)
|
manifest = load_manifest(work.root)
|
||||||
|
style = _style_of(args, manifest)
|
||||||
|
done = []
|
||||||
for asset in manifest["assets"]:
|
for asset in manifest["assets"]:
|
||||||
if args.ids and asset["id"] not in args.ids:
|
if args.ids and asset["id"] not in args.ids:
|
||||||
continue
|
continue
|
||||||
if asset["status"] == "generated" or (args.force and asset.get("raw_file")):
|
rendition = asset["renditions"].get(style)
|
||||||
process_asset(work.root, asset)
|
if rendition and (
|
||||||
print(f"{asset['id']}: processed")
|
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)
|
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:
|
def _cmd_status(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
work = load_work(args.work)
|
||||||
manifest = load_manifest(work.root)
|
manifest = load_manifest(work.root)
|
||||||
if args.set:
|
if args.set:
|
||||||
asset = find_asset(manifest, args.set[0])
|
style = _style_of(args, manifest)
|
||||||
asset["status"] = args.set[1]
|
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:
|
if len(args.set) > 2:
|
||||||
asset["notes"] = args.set[2]
|
rendition["notes"] = args.set[2]
|
||||||
save_manifest(work.root, manifest)
|
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"]:
|
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
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def _cmd_placeholders(args: argparse.Namespace) -> int:
|
def _cmd_placeholders(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
work = load_work(args.work)
|
||||||
manifest = load_manifest(work.root)
|
manifest = load_manifest(work.root)
|
||||||
|
style = _style_of(args, manifest)
|
||||||
for asset in manifest["assets"]:
|
for asset in manifest["assets"]:
|
||||||
if asset["status"] not in USABLE:
|
if not usable_rendition(asset, style):
|
||||||
ensure_placeholder(work.root, asset)
|
ensure_placeholder(work.root, asset, style)
|
||||||
print(f"{asset['id']}: placeholder")
|
print(f"{asset['id']} [{style}]: placeholder")
|
||||||
save_manifest(work.root, manifest)
|
save_manifest(work.root, manifest)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@@ -265,13 +489,21 @@ def _cmd_placeholders(args: argparse.Namespace) -> int:
|
|||||||
def _cmd_prompt(args: argparse.Namespace) -> int:
|
def _cmd_prompt(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
work = load_work(args.work)
|
||||||
manifest = load_manifest(work.root)
|
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
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def _cmd_sheet(args: argparse.Namespace) -> int:
|
def _cmd_sheet(args: argparse.Namespace) -> int:
|
||||||
work = load_work(args.work)
|
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
|
return 0
|
||||||
|
|
||||||
|
|
||||||
@@ -279,29 +511,37 @@ def register(sub: argparse._SubParsersAction) -> None:
|
|||||||
parser = sub.add_parser("assets", help="Manage the asset manifest and images")
|
parser = sub.add_parser("assets", help="Manage the asset manifest and images")
|
||||||
cmds = parser.add_subparsers(dest="assets_command", required=True)
|
cmds = parser.add_subparsers(dest="assets_command", required=True)
|
||||||
|
|
||||||
p = cmds.add_parser("prompt", help="Print the full generation prompt for an asset")
|
def add(name: str, help_: str, handler, style: bool = True) -> argparse.ArgumentParser:
|
||||||
p.add_argument("asset_id")
|
p = cmds.add_parser(name, help=help_)
|
||||||
p.set_defaults(handler=_cmd_prompt)
|
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("asset_id")
|
||||||
p.add_argument("tool_result", type=Path)
|
p.add_argument("tool_result", type=Path)
|
||||||
p.add_argument("--index", type=int, default=0)
|
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("ids", nargs="*")
|
||||||
p.add_argument("--force", action="store_true", help="Reprocess already processed assets")
|
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.add_argument("--set", nargs="+", metavar="ARG")
|
||||||
p.set_defaults(handler=_cmd_status)
|
|
||||||
|
|
||||||
p = cmds.add_parser("placeholders", help="Create placeholders for unusable assets")
|
add("placeholders", "Create placeholders for unusable assets", _cmd_placeholders)
|
||||||
p.set_defaults(handler=_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("out", type=Path)
|
||||||
p.add_argument("ids", nargs="+")
|
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
@@ -19,12 +19,12 @@ from typing import Any
|
|||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
from vnpipe import PACKAGE_DIR
|
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.config import Work, load_work
|
||||||
from vnpipe.schema import validate
|
from vnpipe.schema import validate
|
||||||
|
|
||||||
TEMPLATE_DIR = PACKAGE_DIR / "renpy_templates"
|
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
|
ADV_MAX_LINES = 4
|
||||||
NVL_MAX_LINES = 8
|
NVL_MAX_LINES = 8
|
||||||
@@ -59,6 +59,11 @@ ABOUT_LABELS = {
|
|||||||
"es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."),
|
"es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."),
|
||||||
"en": ("Text", "Translation", "Visual novel adaptation generated with 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 -------------------------------------------------------------
|
# --- text helpers -------------------------------------------------------------
|
||||||
@@ -155,9 +160,11 @@ def annotations_from_parsed(work: Work, parsed: dict[str, Any]) -> dict[str, Any
|
|||||||
@dataclass
|
@dataclass
|
||||||
class ImageEntry:
|
class ImageEntry:
|
||||||
name: str # Ren'Py image name, e.g. "bg heaven" or "hero neutral"
|
name: str # Ren'Py image name, e.g. "bg heaven" or "hero neutral"
|
||||||
rel: str # path below game/images/
|
|
||||||
asset: dict[str, Any]
|
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]:
|
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",
|
"kind": "sprite",
|
||||||
"character": character,
|
"character": character,
|
||||||
"expression": expression,
|
"expression": expression,
|
||||||
"file": f"sprites/{character}_{expression}.webp",
|
"renditions": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _bg_asset(asset_id: str) -> dict[str, Any]:
|
def _bg_asset(asset_id: str) -> dict[str, Any]:
|
||||||
return {
|
return {"id": asset_id, "kind": "background", "renditions": {}}
|
||||||
"id": asset_id,
|
|
||||||
"kind": "background",
|
|
||||||
"file": f"bg/{asset_id.removeprefix('bg_')}.webp",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _needed_bg_ids(work: Work) -> list[str]:
|
def _needed_bg_ids(work: Work) -> list[str]:
|
||||||
@@ -184,8 +187,16 @@ def _needed_bg_ids(work: Work) -> list[str]:
|
|||||||
return ids
|
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]:
|
def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEntry]:
|
||||||
"""Every image the project declares: manifest assets plus anything the staging needs."""
|
"""Every image the project declares: manifest assets plus anything the staging needs."""
|
||||||
|
styles, default = art_styles(manifest)
|
||||||
assets: dict[str, dict[str, Any]] = {}
|
assets: dict[str, dict[str, Any]] = {}
|
||||||
for asset in (manifest or {}).get("assets", []):
|
for asset in (manifest or {}).get("assets", []):
|
||||||
assets[asset["id"]] = asset
|
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)
|
name = bg_image_name(asset_id)
|
||||||
else:
|
else:
|
||||||
name = f"{asset['character']} {asset['expression']}"
|
name = f"{asset['character']} {asset['expression']}"
|
||||||
source = None
|
variants: list[tuple[str, str, Path | None]] = []
|
||||||
if asset.get("status") in USABLE_STATUS and asset.get("file"):
|
for style in [default, *(s for s in styles if s != default)]:
|
||||||
candidate = work.path("assets") / asset["file"]
|
rendition = asset["renditions"].get(style)
|
||||||
if candidate.is_file():
|
rel = (rendition or {}).get("file") or style_file(asset, style)
|
||||||
source = candidate
|
candidate = work.path("assets") / rel
|
||||||
entries.append(ImageEntry(name, asset["file"], asset, source))
|
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
|
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.",
|
"## Generated by `vnpipe renpy`. Do not edit: regenerate instead.",
|
||||||
"",
|
"",
|
||||||
"label start:",
|
"label start:",
|
||||||
|
" call vn_pick_art_style",
|
||||||
" window auto",
|
" window auto",
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
@@ -579,12 +597,27 @@ testcase default:
|
|||||||
$ _test.timeout = 30.0
|
$ _test.timeout = 30.0
|
||||||
pause 1.0
|
pause 1.0
|
||||||
click "Start"
|
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
|
advance until screen "main_menu" timeout 60
|
||||||
assert eval (e2e_state["end"])
|
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 -----------------------------------------------------------------
|
# --- static project files -----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -619,12 +652,25 @@ def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, str]:
|
|||||||
return cards
|
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:
|
def render_images(entries: list[ImageEntry], cards: dict[str, str]) -> str:
|
||||||
out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""]
|
out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""]
|
||||||
for name, text in cards.items(): # title cards: plain images, not `show text`
|
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)')
|
out.append(f'image {name} = Text("{escape_text(text)}", size=60, text_align=0.5)')
|
||||||
for e in entries:
|
out.extend(render_image_entry(e) for e in entries)
|
||||||
out.append(f"image {e.name} = {_plain_quote('images/' + e.rel)}")
|
|
||||||
out.append("")
|
out.append("")
|
||||||
return "\n".join(out)
|
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)
|
first_bg = info.get("menu_bg") or next((c["bg"] for c in staging.values() if c.get("bg")), None)
|
||||||
if first_bg:
|
if first_bg:
|
||||||
menu_bg = bg_image_name(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 = {
|
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"]),
|
"TITLE": escape_text(info["title"]),
|
||||||
"VERSION": "0.1",
|
"VERSION": "0.1",
|
||||||
"ABOUT": _about(work),
|
"ABOUT": _about(work),
|
||||||
@@ -707,7 +761,7 @@ def generate(
|
|||||||
test_file = game / E2E_FILE
|
test_file = game / E2E_FILE
|
||||||
test_file.unlink(missing_ok=True)
|
test_file.unlink(missing_ok=True)
|
||||||
if with_test:
|
if with_test:
|
||||||
write_text(test_file, E2E_TESTCASE)
|
write_text(test_file, render_e2e(styles))
|
||||||
written.append(test_file)
|
written.append(test_file)
|
||||||
for name, text in (
|
for name, text in (
|
||||||
("characters.rpy", render_characters(work)),
|
("characters.rpy", render_characters(work)),
|
||||||
@@ -718,13 +772,14 @@ def generate(
|
|||||||
written.append(game / name)
|
written.append(game / name)
|
||||||
|
|
||||||
for e in entries:
|
for e in entries:
|
||||||
dest = game / "images" / e.rel
|
for _, rel, source in e.variants:
|
||||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
dest = game / "images" / rel
|
||||||
written.append(dest)
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
if e.source:
|
written.append(dest)
|
||||||
shutil.copyfile(e.source, dest)
|
if source:
|
||||||
else:
|
shutil.copyfile(source, dest)
|
||||||
placeholder(e.asset).save(dest, "WEBP", quality=90)
|
else:
|
||||||
|
placeholder(e.asset).save(dest, "WEBP", quality=90)
|
||||||
|
|
||||||
return sorted(written)
|
return sorted(written)
|
||||||
|
|
||||||
|
|||||||
@@ -756,6 +756,14 @@ screen preferences():
|
|||||||
textbutton _("After Choices") action Preference("after choices", "toggle")
|
textbutton _("After Choices") action Preference("after choices", "toggle")
|
||||||
textbutton _("Transitions") action InvertSelected(Preference("transitions", "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
|
## Additional vboxes of type "radio_pref" or "check_pref" can be
|
||||||
## added here, to add additional creator-defined preferences.
|
## 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
|
||||||
@@ -4,15 +4,50 @@
|
|||||||
"title": "Asset manifest",
|
"title": "Asset manifest",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
"base_prompt",
|
"default_style",
|
||||||
"templates",
|
"styles",
|
||||||
"assets"
|
"assets"
|
||||||
],
|
],
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"properties": {
|
"properties": {
|
||||||
"base_prompt": {
|
"default_style": {
|
||||||
"type": "string"
|
"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": {
|
"assets": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
@@ -21,10 +56,7 @@
|
|||||||
"id",
|
"id",
|
||||||
"kind",
|
"kind",
|
||||||
"prompt",
|
"prompt",
|
||||||
"source",
|
"renditions"
|
||||||
"file",
|
|
||||||
"sha256",
|
|
||||||
"status"
|
|
||||||
],
|
],
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -47,21 +79,7 @@
|
|||||||
},
|
},
|
||||||
"prompt": {
|
"prompt": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Asset-specific prompt; the full prompt sent is base_prompt + kind prompt + this"
|
"description": "Asset-specific prompt; the full prompt sent is the style's base_prompt + kind template + this"
|
||||||
},
|
|
||||||
"source": {
|
|
||||||
"enum": [
|
|
||||||
"chatgpt-web",
|
|
||||||
"zenvairo-media",
|
|
||||||
"placeholder",
|
|
||||||
"manual"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"generation_id": {
|
|
||||||
"type": [
|
|
||||||
"string",
|
|
||||||
"null"
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"reference": {
|
"reference": {
|
||||||
"type": [
|
"type": [
|
||||||
@@ -70,51 +88,67 @@
|
|||||||
],
|
],
|
||||||
"description": "Asset id used as reference image (identity consistency)"
|
"description": "Asset id used as reference image (identity consistency)"
|
||||||
},
|
},
|
||||||
"raw_file": {
|
"renditions": {
|
||||||
"type": [
|
"type": "object",
|
||||||
"string",
|
"additionalProperties": {
|
||||||
"null"
|
"type": "object",
|
||||||
],
|
"required": [
|
||||||
"description": "Original generated image, relative to the work's assets dir"
|
"file",
|
||||||
},
|
"status"
|
||||||
"file": {
|
],
|
||||||
"type": "string",
|
"additionalProperties": false,
|
||||||
"description": "Final processed image used by the game, relative to the work's assets dir"
|
"properties": {
|
||||||
},
|
"source": {
|
||||||
"sha256": {
|
"enum": [
|
||||||
"type": [
|
"chatgpt-web",
|
||||||
"string",
|
"zenvairo-media",
|
||||||
"null"
|
"placeholder",
|
||||||
],
|
"manual"
|
||||||
"pattern": "^[0-9a-f]{64}$"
|
]
|
||||||
},
|
},
|
||||||
"status": {
|
"generation_id": {
|
||||||
"enum": [
|
"type": [
|
||||||
"planned",
|
"string",
|
||||||
"generated",
|
"null"
|
||||||
"processed",
|
]
|
||||||
"approved",
|
},
|
||||||
"rejected",
|
"raw_file": {
|
||||||
"placeholder"
|
"type": [
|
||||||
]
|
"string",
|
||||||
},
|
"null"
|
||||||
"notes": {
|
],
|
||||||
"type": "string"
|
"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"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
@@ -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"))
|
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
|
assert "None" in nameless_nvl and "nvl_thought" in nameless_nvl
|
||||||
images = (project / "game/images.rpy").read_text(encoding="utf-8")
|
images = (project / "game/images.rpy").read_text(encoding="utf-8")
|
||||||
assert 'image bg dedication = "images/bg/dedication.webp"' in images
|
assert 'image bg dedication = "images/bg/default/dedication.webp"' in images
|
||||||
assert 'image director pleased = "images/sprites/director_pleased.webp"' in images
|
assert 'image director pleased = "images/sprites/default/director_pleased.webp"' in images
|
||||||
assert (project / "game/images/sprites/poet_indignant.webp").is_file()
|
assert (project / "game/images/sprites/default/poet_indignant.webp").is_file()
|
||||||
assert (project / "game/images/bg/theatre.webp").is_file()
|
assert (project / "game/images/bg/default/theatre.webp").is_file()
|
||||||
assert not (project / "game/images/sprites/lord_neutral.webp").exists()
|
assert not (project / "game/images/sprites/default/lord_neutral.webp").exists()
|
||||||
|
|
||||||
|
|
||||||
def test_title_card_images(project):
|
def test_title_card_images(project):
|
||||||
|
|||||||
Reference in new issue
Block a user