diff --git a/docs/adaptation-rules.md b/docs/adaptation-rules.md index 7cf3eba..24bae22 100644 --- a/docs/adaptation-rules.md +++ b/docs/adaptation-rules.md @@ -45,6 +45,19 @@ sets the mood and the words carry the scene. So: around between boxes. - Characters with `sprite = false` are never drawn, even if annotated as on stage. +## Human judgment layer + +The annotation is an LLM's first guess; `work.toml` can override it, generically: + +- `[staging.].cast = { = "" }` pins characters (sprite = true) on stage + at fixed positions for the whole scene, overriding the annotation's `on_stage`. +- A cue's `move = { = "" }` slides a visible sprite to another position. +- `[[overrides]] { from, to, emotion }` forces the emotion of an inclusive line range + (same scene) before expression mapping. + +Stage-direction lines never change who is on stage (they keep the previous box's +`on_stage`). Unknown line ids, characters, positions or emotions are errors at generation. + ## Transitions - `dissolve` between expressions and on sprite entry/exit, `fade` between scenes, diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py index 3d1c40b..96b103a 100644 --- a/src/vnpipe/renpy_gen.py +++ b/src/vnpipe/renpy_gen.py @@ -30,6 +30,17 @@ SPLIT_INDENT = 6 # parsed `indent` at or above this marks a split verse line TITLE_PAUSE = 2.0 END_PAUSE = 3.0 +VALID_POSITIONS = ("left", "center", "right") +EMOTIONS = ( + "neutral", + "joyful", + "melancholic", + "solemn", + "ironic", + "angry", + "fearful", + "ecstatic", +) POSITIONS = ("left", "right", "center") # order in which --from-parsed assigns positions TRANSITIONS = { "dissolve": "dissolve", @@ -232,7 +243,9 @@ class SceneWriter: self.tint = "none" self.music_state = music_state # {'playing': mood}, shared across scenes self.shown: dict[str, str] = {} # character -> expression currently shown - self.positions: dict[str, str] = {} # character -> stable position for this scene + self.pinned: dict[str, str] = dict(staging.get("cast", {})) # always on stage in ADV + self.positions: dict[str, str] = dict(self.pinned) # character -> position in this scene + self.last_on_stage: list[dict[str, str]] = [] # on_stage of the last non-direction box self.out: list[str] = [] self.box: Box | None = None @@ -274,6 +287,14 @@ class SceneWriter: self.emit(f"with {TRANSITIONS[transition]}") if cue.get("shake"): self.emit("show layer master at vn_shake") + moved = False + for cid, position in cue.get("move", {}).items(): + self.positions[cid] = position + if cid in self.shown: + self.emit(f"show {cid} {self.shown[cid]} at vn_{position}") + moved = True + if moved: + self.emit("with vn_move") def hide_sprites(self, characters: list[str]) -> bool: for cid in characters: @@ -344,14 +365,22 @@ class SceneWriter: first = box.lines[0] ann = first["ann"] desired: list[str] = [] - for entry in ann["on_stage"]: + # stage directions never change who is on stage + on_stage = self.last_on_stage if box.is_direction else ann["on_stage"] + if not box.is_direction: + self.last_on_stage = on_stage + for cid in self.pinned: + if self.work.cast[cid].get("sprite"): + desired.append(cid) + for entry in on_stage: cid = entry["character"] if cid not in self.work.cast: raise ValueError(f"{first['id']}: on_stage character {cid!r} is not in [cast]") if not self.work.cast[cid].get("sprite"): continue self.positions.setdefault(cid, entry["position"]) - desired.append(cid) + if cid not in desired: + desired.append(cid) changed = self.hide_sprites([c for c in list(self.shown) if c not in desired]) for cid in desired: expressions = self.work.cast[cid].get("expressions", {}) @@ -392,7 +421,49 @@ class SceneWriter: return self.out +def validate_staging(work: Work, annotated: dict[str, Any]) -> None: + """Check the human-judgment layer (staging.cast, cue move, overrides) against the data.""" + cast = work.cast + scene_ids = [sc["id"] for sc in annotated["scenes"]] + for sid, cfg in work.data.get("staging", {}).items(): + if sid not in scene_ids: + raise ValueError(f"[staging.{sid}]: unknown scene") + for cid, pos in cfg.get("cast", {}).items(): + if cid not in cast: + raise ValueError(f"[staging.{sid}].cast: unknown character {cid!r}") + if pos not in VALID_POSITIONS: + raise ValueError(f"[staging.{sid}].cast: unknown position {pos!r}") + for cue in work.data.get("cues", []): + for cid, pos in cue.get("move", {}).items(): + if cid not in cast: + raise ValueError(f"cue at {cue['at']}: move of unknown character {cid!r}") + if pos not in VALID_POSITIONS: + raise ValueError(f"cue at {cue['at']}: unknown position {pos!r}") + + +def apply_overrides(work: Work, annotated: dict[str, Any]) -> dict[str, Any]: + """Return a copy of ``annotated`` with ``[[overrides]]`` emotions applied (inclusive ranges).""" + result = json.loads(json.dumps(annotated)) + where = {ln["id"]: (sc, i) for sc in result["scenes"] for i, ln in enumerate(sc["lines"])} + for ov in work.data.get("overrides", []): + if ov["emotion"] not in EMOTIONS: + raise ValueError( + f"override {ov['from']}..{ov['to']}: unknown emotion {ov['emotion']!r}" + ) + for key in ("from", "to"): + if ov[key] not in where: + raise ValueError(f"override: unknown line id {ov[key]!r}") + (scene, start), (scene_to, end) = where[ov["from"]], where[ov["to"]] + if scene is not scene_to or end < start: + raise ValueError(f"override {ov['from']}..{ov['to']}: not a range within one scene") + for line in scene["lines"][start : end + 1]: + line["ann"]["emotion"] = ov["emotion"] + return result + + def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str: + validate_staging(work, annotated) + annotated = apply_overrides(work, annotated) end_text = work.data["work"].get("end_text", DEFAULT_END_TEXT) out = [ "## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", diff --git a/src/vnpipe/renpy_templates/game/support.rpy b/src/vnpipe/renpy_templates/game/support.rpy index 72ca9f7..c5b21f9 100644 --- a/src/vnpipe/renpy_templates/game/support.rpy +++ b/src/vnpipe/renpy_templates/game/support.rpy @@ -34,3 +34,5 @@ transform vn_shake: init python: config.font_replacement_map["fonts/RobotoSlab-Regular.ttf", True, False] = ( "fonts/RobotoSlab-Bold.ttf", False, False) + +define vn_move = MoveTransition(0.8) diff --git a/tests/test_renpy_gen.py b/tests/test_renpy_gen.py index 84710ed..d5e2bfc 100644 --- a/tests/test_renpy_gen.py +++ b/tests/test_renpy_gen.py @@ -253,3 +253,82 @@ def test_renpy_lint(work, annotated, tmp_path): report = result.stdout + result.stderr assert result.returncode == 0, report assert "Traceback" not in report and "error" not in report.lower(), report + + +def _with_cfg(work, **changes): + data = json.loads(json.dumps(work.data)) + for key, value in changes.items(): + data[key] = value + return type(work)(root=work.root, data=data) + + +def test_pinned_cast(work, annotated): + data = json.loads(json.dumps(work.data)) + data["staging"]["talk"]["cast"] = {"poet": "left", "director": "center"} + pinned = type(work)(root=work.root, data=data) + block = scene_block(renpy_gen.render_script(pinned, annotated, set()), "talk") + first_box = block.index("# talk_0002 .. talk_0005") + assert "show poet neutral at vn_left" in block[first_box:] + assert any(ln.startswith("show director") and ln.endswith("vn_center") for ln in block) + assert not any("vn_right" in ln for ln in block) # annotation position overridden + + +def test_stage_direction_keeps_on_stage(work, annotated): + ann = json.loads(json.dumps(annotated)) + direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010") + direction["ann"]["on_stage"] = [] + block = scene_block(renpy_gen.render_script(work, ann, set()), "talk") + i = block.index('c_narrator "Se aleja."') + assert not any(ln.startswith("hide ") for ln in block[i - 3 : i]) + + +def test_cue_move(work, annotated): + data = json.loads(json.dumps(work.data)) + data["cues"][0]["move"] = {"poet": "left"} + moved = type(work)(root=work.root, data=data) + block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") + # sprites are hidden by that cue's hide_all, so nothing to slide; position is updated + assert "with vn_move" not in block + data["cues"][0].pop("hide_all") + data["cues"][0]["move"] = {"poet": "left"} + moved = type(work)(root=work.root, data=data) + block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") + i = block.index("with vn_move") + assert block[i - 1].startswith("show poet ") and block[i - 1].endswith("vn_left") + + +def test_overrides(work, annotated): + ov = [{"from": "talk_0011", "to": "talk_0013", "emotion": "angry"}] + block = scene_block( + renpy_gen.render_script(_with_cfg(work, overrides=ov), annotated, set()), "talk" + ) + assert "show poet indignant at vn_right" in block[block.index("# talk_0011 .. talk_0013") :] + + +@pytest.mark.parametrize( + "change, match", + [ + ({"overrides": [{"from": "talk_0011", "to": "nope", "emotion": "angry"}]}, "unknown line"), + ({"overrides": [{"from": "talk_0011", "to": "talk_0012", "emotion": "mad"}]}, "emotion"), + ({"overrides": [{"from": "talk_0011", "to": "lyric_0001", "emotion": "angry"}]}, "range"), + ({"overrides": [{"from": "talk_0012", "to": "talk_0011", "emotion": "angry"}]}, "range"), + ], +) +def test_invalid_overrides(work, annotated, change, match): + with pytest.raises(ValueError, match=match): + renpy_gen.render_script(_with_cfg(work, **change), annotated, set()) + + +def test_invalid_staging_cast_and_move(work, annotated): + data = json.loads(json.dumps(work.data)) + data["staging"]["talk"]["cast"] = {"ghost": "left"} + with pytest.raises(ValueError, match="ghost"): + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) + data = json.loads(json.dumps(work.data)) + data["staging"]["talk"]["cast"] = {"poet": "up"} + with pytest.raises(ValueError, match="position"): + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) + data = json.loads(json.dumps(work.data)) + data["cues"][0]["move"] = {"poet": "nowhere"} + with pytest.raises(ValueError, match="position"): + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) diff --git a/works/faust/work.toml b/works/faust/work.toml index 42628e1..df0631d 100644 --- a/works/faust/work.toml +++ b/works/faust/work.toml @@ -146,6 +146,11 @@ sprite = false # mode adv | nvl # hide_all true -> remove all sprites # shake true -> short screen shake +# move { = "" } -> slide a visible sprite to left|center|right +# A scene may also pin characters on stage for the whole scene, overriding the +# annotation's on_stage/positions for them (sprite = true characters only): +# cast { = "left|center|right", ... } +# [[overrides]] (end of file) force the emotion of a line range before expression mapping. [staging.dedicatoria] bg = "bg_dedication" mode = "nvl" @@ -153,14 +158,17 @@ mode = "nvl" [staging.prologo_teatro] bg = "bg_theatre" mode = "adv" +cast = { clown = "left", director = "center", poet = "right" } [staging.prologo_cielo] bg = "bg_heaven" mode = "nvl" +cast = { mephisto = "left" } [staging.noche] bg = "bg_study" mode = "adv" +cast = { faust = "center" } [[cues]] # The archangels' hymn ends; the Lord is addressed by Mephistopheles. @@ -191,3 +199,15 @@ at = "noche_0145" bg = "bg_study_spirit" transition = "flash" shake = true +move = { faust = "left" } # keep the Spirit's flame (centre of the background) visible + +# Mephistopheles is annotated "ironic" throughout; force the register where the text changes. +[[overrides]] +from = "prologo_cielo_0030" +to = "prologo_cielo_0043" +emotion = "solemn" # deferent bow before the Lord + +[[overrides]] +from = "prologo_cielo_0048" +to = "prologo_cielo_0061" +emotion = "angry" # scornful about mankind