Skip to content

Official Codebase of 3DCodeVerse

Python

Add scene director plugin prototype for scene_blender refine rounds

gaoypeng3d5bd5f9c10d
diff --git a/CLAUDE.md b/CLAUDE.md
index fe964661..46010359 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,3 +14,6 @@ Other top-level folders are separate components: `toolkits/` owns the general da
`finetune/` owns training and its data preparation. The canonical LLaMA-Factory data scripts live in
`finetune/llamafactory/`; `finetune/configs/`, `finetune/env/`, and the training launchers in
`finetune/scripts/` retain their existing locations. Read `finetune/CLAUDE.md` before changing them.
+
+`plugins/` holds optional runtime plugins that wrap harness hooks for one process without editing
+`harness/` (`plugins/scene_director/`: art-direction notes as scene refine tasks; a prototype).
diff --git a/plugins/scene_director/README.md b/plugins/scene_director/README.md
new file mode 100644
index 00000000..ba721328
--- /dev/null
+++ b/plugins/scene_director/README.md
@@ -0,0 +1,78 @@
+# Scene director plugin (prototype, 2026-10-19)
+
+A director agent for the scene_blender track, kept as a plugin outside `harness/` so the
+harness package is untouched. Status: **implementation only — not tested and never run on a live
+harness run.** Kept for later development by the owner.
+
+## What it does
+
+Each refine round, after the judge, one structured VLM call reads the round's own renders from the
+cameras the film will use, and writes at most three *target-look* notes (what the frame shows now,
+what it must look like instead), ranked by how much of the frame the target fills. The notes become
+priority-1 refine tasks (`[director/direction:<kind>]`) in the harness's normal refine prompt:
+
+| order | source | rule |
+|---|---|---|
+| 0 | gate ERRORs | always first; the director skips a round that has any |
+| 1 | director | at most 3; protected from the task cap like gate/acceptance tasks |
+| 2+ | judge improvement plan | fills what is left |
+
+The last refine round is left to the judge alone (cleanup), following the world_demo lesson that a
+large change session often leaves one interpenetration that a short follow-up fixes.
+
+## How it hooks in (no harness edits)
+
+`install()` wraps `SceneTrack.extra_refine_tasks`, the shared refine scaffold's existing hook
+(`codeverse3d/tracks/lifecycle.py`; the static-object track uses it for reference-IoU tasks), for
+the current process only. `build_refine_instructions` already protects every non-judge source from
+the cap, so no core logic changes. `DirectorTask` subclasses `RefineTask` only to add the
+`"director"` source label.
+
+```bash
+cd plugins/scene_director
+PYTHONPATH=. python -m scene_director make "..." --track scene --language scene_blender --variant argon_raw
+```
+
+| env | default | meaning |
+|---|---|---|
+| `SCENE_DIRECTOR` | `1` | `0` turns it off (the hook then returns nothing) |
+| `SCENE_DIRECTOR_MODEL` | run's judge backend | VLM for the director call |
+| `SCENE_DIRECTOR_SHOT` | third-person follow, ~2 m, 1080p Cycles | how the scene will be filmed |
+| `SCENE_DIRECTOR_VIEWS` | eye-level / route cameras from the plan | comma-separated camera names to read first |
+| `SCENE_DIRECTOR_MAX_NOTES` | `3` | notes per round |
+| `SCENE_DIRECTOR_SKIP_LAST` | `1` | leave the last refine round to the judge |
+
+Per round it writes `artifacts/director/rNN.json` (views, notes, tasks, cost) and emits
+`director.notes` / `director.skip` / `director.failed` events. The call goes through
+`get_chat_model`, so it is metered into the run's cost ledger like any other call. A director
+failure never fails a round.
+
+## Files
+
+- `scene_director/director.py`: config, view selection, request, notes→tasks, hook body
+- `scene_director/prompts/`: director system and user prompts (tuned for argon from the w2 notes)
+- `scene_director/__init__.py`: `install()` / `uninstall()`
+- `scene_director/__main__.py`: `3dcode` launcher with the director installed
+
+Written against harness commit `fc9584c9`; no tests are included (owner's choice, 2026-10-19).
+
+## Evidence behind the design, and its limits
+
+From the world_demo experiment (2026-10-17, `eval/bench/out/world_demo/work/w2_B` vs `w2_C`):
+notes written from the delivery shot (B) changed the scene far more than handing the judge's plan to
+the same agent (C); judge scores 0.960 vs 0.939. That is **one scene**, and the director there was a
+person (Claude, writing notes by hand), not this automated call. Whether a VLM call reproduces those
+notes is untested. 11 of 12 long `director.py` sessions timed out; this plugin instead rides the
+normal refine session and budget.
+
+## Not done (for a core merge or the next prototype step)
+
+- A live A/B on an `eval/bench` battery: argon_raw vs argon_raw + director, paired, judged by
+ `PairwiseJudge` on the delivery views (absolute scores compress above ~0.9), plus timeout rate
+ and cost.
+- Telling the judge the director's targets (`ScenePipeline.judge_context`): it changes the judge
+ payload, so old scores would stop being comparable.
+- Real delivery-shot renders (a follow camera along the route) instead of the plan's eye-level
+ cameras.
+- Core merge path: `"director"` in `RefineTask.source`, a `director` Settings flag and variant knob,
+ the templates under `prompts/` (variant-overridable), and this hook body in `tracks/`.
diff --git a/plugins/scene_director/scene_director/__init__.py b/plugins/scene_director/scene_director/__init__.py
new file mode 100644
index 00000000..25b2fa61
--- /dev/null
+++ b/plugins/scene_director/scene_director/__init__.py
@@ -0,0 +1,40 @@
+"""Scene director plugin for the 3dcodeverse harness — a prototype kept outside the main repository.
+
+``install()`` binds the director onto ``SceneTrack.extra_refine_tasks`` (the scaffold's existing hook,
+``tracks/lifecycle.py``) for this process only. No harness file is edited; ``uninstall()`` restores
+the original method. Run a harness command with it active via ``python -m scene_director <3dcode args>``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+_ORIGINAL: Any = None
+
+
+def install() -> None:
+ global _ORIGINAL
+ from codeverse3d.tracks.scene import SceneTrack
+
+ from scene_director.director import director_refine_tasks
+
+ if _ORIGINAL is not None:
+ return
+ _ORIGINAL = SceneTrack.extra_refine_tasks
+
+ def extra_refine_tasks(self: Any, ctx: Any, last: Any) -> list[Any]:
+ return [*_ORIGINAL(self, ctx, last), *director_refine_tasks(self, ctx, last)]
+
+ SceneTrack.extra_refine_tasks = extra_refine_tasks # type: ignore[method-assign]
+
+
+def uninstall() -> None:
+ global _ORIGINAL
+ from codeverse3d.tracks.scene import SceneTrack
+
+ if _ORIGINAL is not None:
+ SceneTrack.extra_refine_tasks = _ORIGINAL # type: ignore[method-assign]
+ _ORIGINAL = None
+
+
+__all__ = ["install", "uninstall"]
diff --git a/plugins/scene_director/scene_director/__main__.py b/plugins/scene_director/scene_director/__main__.py
new file mode 100644
index 00000000..1df63910
--- /dev/null
+++ b/plugins/scene_director/scene_director/__main__.py
@@ -0,0 +1,11 @@
+"""``python -m scene_director make "..." --track scene --language scene_blender --variant argon_raw``
+
+Same arguments as ``3dcode``; the director is installed for this process first."""
+
+from scene_director import install
+
+install()
+
+from codeverse3d.cli.main import app # noqa: E402
+
+app(prog_name="3dcode+director")
diff --git a/plugins/scene_director/scene_director/director.py b/plugins/scene_director/scene_director/director.py
new file mode 100644
index 00000000..a25689a5
--- /dev/null
+++ b/plugins/scene_director/scene_director/director.py
@@ -0,0 +1,189 @@
+"""The art director: shot-view notes that become priority-1 refine tasks on the scene track.
+
+One structured VLM call per refine round. It looks at the views the film will actually use (the
+round's own authored renders — nothing is rendered for it), writes at most ``max_notes`` target-look
+notes ranked by screen share, and hands them to the shared refine scaffold through
+``extra_refine_tasks``. Gate ERRORs still come first (priority 0); the judge's plan fills what is left.
+
+Lessons it encodes (world_demo, 2026-10-17, one scene — see ../README.md):
+* notes written from the delivery shot changed far more than the judge's plan did (judge 0.939 vs 0.960
+ on the same scene, the visual gap much larger): the judge saturates above ~0.9;
+* a long "big change" session tended to time out with one interpenetration left: so few notes per
+ round, never on a round with gate ERRORs, and the last refine round is the judge's alone (cleanup).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse3d.contracts.chat import ImagePart
+from codeverse3d.contracts.plan import ScenePlan
+from codeverse3d.models import get_chat_model
+from codeverse3d.models.schema_utils import ask_structured
+from codeverse3d.orchestrator import RefineTask
+
+log = logging.getLogger(__name__)
+
+PROMPTS = Path(__file__).with_name("prompts")
+#: words in a camera's name / purpose that mark a delivery (eye-level, along-the-route) view
+SHOT_WORDS = ("eye", "trail", "walk", "route", "path", "hero", "street", "ground", "follow", "approach")
+DEFAULT_SHOT = ("a third-person camera about 2 m up and 3–4 m behind a character walking the main route, "
+ "rendered in Cycles at 1920x1080")
+
+
+class DirectorTask(RefineTask):
+ """A ``RefineTask`` from the director. Same fields; only the source label is new, so the
+ scaffold's cap keeps it (it protects every non-judge source) and ``line()`` prints
+ ``[director/<kind>]``. A core merge would add ``"director"`` to ``RefineTask.source`` instead."""
+
+ source: Literal["gate", "acceptance", "judge", "director"] = "director" # type: ignore[assignment]
+
+
+class DirectorNote(BaseModel):
+ target: str = Field(description="a zone or asset name from the plan, or 'environment'")
+ view: str = Field(description="the camera the note is read from")
+ screen_share: float = Field(ge=0.0, le=1.0, description="rough fraction of that frame the target fills")
+ kind: Literal["geometry", "material", "lighting", "atmosphere", "dressing", "motion"]
+ now: str = Field(description="what the frame shows today, in visible terms")
+ target_look: str = Field(description="what it must look like instead: concrete, visible features")
+
+
+class DirectorNotes(BaseModel):
+ read: str = Field(description="two sentences: what the shot is and what most weakens it")
+ notes: list[DirectorNote] = Field(default_factory=list)
+
+
+class DirectorConfig(BaseModel):
+ """Read from ``SCENE_DIRECTOR_*`` (not ``C3D_*``: the plugin adds no harness Settings field)."""
+
+ enabled: bool = True
+ model: str = "" # "" → the run's judge backend
+ shot: str = DEFAULT_SHOT # how the scene will be filmed
+ views: list[str] = Field(default_factory=list) # camera names; [] → picked from the plan
+ max_notes: int = 3
+ max_images: int = 4
+ skip_last_round: bool = True
+
+ @classmethod
+ def from_env(cls) -> DirectorConfig:
+ e = os.environ.get
+ return cls(enabled=e("SCENE_DIRECTOR", "1") not in ("0", "false", "off", ""),
+ model=e("SCENE_DIRECTOR_MODEL", ""),
+ shot=e("SCENE_DIRECTOR_SHOT", DEFAULT_SHOT),
+ views=[v.strip() for v in e("SCENE_DIRECTOR_VIEWS", "").split(",") if v.strip()],
+ max_notes=int(e("SCENE_DIRECTOR_MAX_NOTES", "3")),
+ max_images=int(e("SCENE_DIRECTOR_MAX_IMAGES", "4")),
+ skip_last_round=e("SCENE_DIRECTOR_SKIP_LAST", "1") not in ("0", "false", "off"))
+
+
+def skip_reason(ctx: Any, last: Any, cfg: DirectorConfig) -> str:
+ """Why the director sits this round out ("" = it runs)."""
+ if not cfg.enabled:
+ return "disabled"
+ if not isinstance(ctx.plan, ScenePlan) or ctx.language.value != "scene_blender":
+ return "not a scene_blender run"
+ if last.renders is None or not last.renders.views:
+ return "no renders"
+ if any(g.errors for g in last.gates):
+ return "gate errors first"
+ if cfg.skip_last_round and last.index + 1 >= ctx.policy.max_rounds:
+ return "last refine round is the judge's (cleanup)"
+ return ""
+
+
+def delivery_views(ctx: Any, last: Any, cfg: DirectorConfig) -> list[Any]:
+ """The round's renders the film would use: named cameras first, then eye-level / route cameras by
+ their plan purpose, then every other authored camera; the first animation time of each."""
+ plan: ScenePlan = ctx.plan
+ authored = {c.name: c for c in plan.cameras}
+ by_cam: dict[str, Any] = {}
+ for v in sorted(last.renders.views, key=lambda v: v.time_s or 0.0):
+ cam = next((n for n in authored if v.name == n or v.name.startswith(f"{n}_")), None)
+ if cam and cam not in by_cam and v.mode == "shaded":
+ by_cam[cam] = v
+
+ def rank(name: str) -> tuple[int, int]:
+ if name in cfg.views:
+ return (0, cfg.views.index(name))
+ text = f"{name} {authored[name].purpose}".lower()
+ return (1 if any(w in text for w in SHOT_WORDS) else 2, 0)
+
+ return [by_cam[n] for n in sorted(by_cam, key=rank)][:cfg.max_images]
+
+
+def _known_targets(plan: ScenePlan) -> list[str]:
+ return [z.name for z in plan.zones] + [a.name for a in plan.assets] + ["environment"]
+
+
+def build_request(ctx: Any, last: Any, views: list[Any], cfg: DirectorConfig) -> tuple[str, str, list[ImagePart]]:
+ plan: ScenePlan = ctx.plan
+ judged = ""
+ if last.judgment is not None:
+ judged = "\n".join(f"- [{i.severity}] {i.target}: {i.detail}" for i in last.judgment.issues[:8])
+ user = (PROMPTS / "director_user.md").read_text().format(
+ prompt=ctx.spec.prompt.strip(), shot=cfg.shot, title=plan.title, setting=plan.setting, mood=plan.mood,
+ environment=plan.environment[:1500],
+ zones="\n".join(f"- {z.name}: {', '.join(z.contents)}" for z in plan.zones),
+ targets=", ".join(_known_targets(plan)),
+ views="\n".join(f"- {v.name}: {next((c.purpose for c in plan.cameras if v.name.startswith(c.name)), '')}"
+ for v in views),
+ judged=judged or "(none)", max_notes=cfg.max_notes)
+ system = (PROMPTS / "director_system.md").read_text()
+ images = [ImagePart(path=v.path, label=v.name) for v in views]
+ return system, user, images
+
+
+def notes_to_tasks(notes: DirectorNotes, plan: ScenePlan, file_for_target: Any, max_notes: int) -> list[DirectorTask]:
+ """Keep notes on known targets, largest screen share first, at most ``max_notes``."""
+ known = {t.lower(): t for t in _known_targets(plan)}
+ kept = sorted((n for n in notes.notes if n.target.lower() in known), key=lambda n: -n.screen_share)[:max_notes]
+ out = []
+ for n in kept:
+ target = known[n.target.lower()]
+ out.append(DirectorTask(
+ target=target, kind=f"direction:{n.kind}", priority=1,
+ instruction=(f"In {n.view} (≈{n.screen_share:.0%} of the frame) it reads as: {n.now} "
+ f"Make it read as: {n.target_look} One change at a time; build after each."),
+ files=[] if target == "environment" else list(file_for_target(target))))
+ return out
+
+
+def director_refine_tasks(track: Any, ctx: Any, last: Any, cfg: DirectorConfig | None = None,
+ model: Any = None) -> list[DirectorTask]:
+ """The hook body. Never raises: a director failure is logged and the round runs on the judge alone."""
+ cfg = cfg or DirectorConfig.from_env()
+ why = skip_reason(ctx, last, cfg)
+ if why:
+ ctx.events.emit("director.skip", round=last.index + 1, reason=why)
+ return []
+ try:
+ views = delivery_views(ctx, last, cfg)
+ if not views:
+ ctx.events.emit("director.skip", round=last.index + 1, reason="no authored shaded views")
+ return []
+ system, user, images = build_request(ctx, last, views, cfg)
+ model = model or get_chat_model(cfg.model or ctx.spec.backends.judge)
+ notes, usage, error = ask_structured(model, DirectorNotes, system=system, text=user, images=images,
+ temperature=0.4, label="director")
+ if notes is None:
+ ctx.events.emit("director.failed", round=last.index + 1, error=error[:300])
+ return []
+ tasks = notes_to_tasks(notes, ctx.plan, track.refine_file_for_target(ctx), cfg.max_notes)
+ out = Path(ctx.ws.artifacts) / "director" / f"r{last.index + 1:02d}.json"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(json.dumps({"views": [v.name for v in views], "notes": notes.model_dump(mode="json"),
+ "tasks": [t.line() for t in tasks], "cost_usd": usage.cost_usd,
+ "config": cfg.model_dump(mode="json")}, indent=1, ensure_ascii=False))
+ ctx.events.emit("director.notes", round=last.index + 1, n=len(tasks), views=[v.name for v in views],
+ cost_usd=round(usage.cost_usd, 5))
+ return tasks
+ except Exception as e: # noqa: BLE001 — the director is advisory; it must never kill a round
+ log.warning("director failed: %s: %s", type(e).__name__, e)
+ ctx.events.emit("director.failed", round=last.index + 1, error=f"{type(e).__name__}: {e}"[:300])
+ return []
diff --git a/plugins/scene_director/scene_director/prompts/director_system.md b/plugins/scene_director/scene_director/prompts/director_system.md
new file mode 100644
index 00000000..b35646a7
--- /dev/null
+++ b/plugins/scene_director/scene_director/prompts/director_system.md
@@ -0,0 +1,21 @@
+You are the art director of a cinematic trailer. A 3D environment written as raw Blender Python
+(bpy) by a coding agent is about to be filmed. You are shown frames from the cameras the film
+will use. A separate judge already checks defects (floating objects, interpenetration, exposure,
+missing items); do NOT repeat its findings and do NOT act as a checklist.
+
+Your job is to say what would make the SHOT look like a high-end game trailer, and nothing else:
+
+1. Look from the delivery camera. Rank what fills the most of the frame (near verge, ground,
+ path, the nearest props, the skyline) — that is where the eye is, and where notes pay off.
+2. For each note, say what the frame shows now in visible terms, then describe the target look
+ with concrete visible features a modeller can build: silhouette, scale of detail, colour and
+ value variation, how materials break up at several scales, what lies where (by altitude, slope,
+ wear, wetness), aerial perspective. "More realistic" / "add detail" are not notes.
+3. Ask for what code can build in bpy/bmesh, geometry nodes and shader nodes. Do not ask for
+ camera, render-setting or exposure changes, and do not move anything onto the walking route.
+4. Name the target exactly as one of the plan's zone / asset names, or "environment" for sky,
+ sun, atmosphere, terrain and the world beyond the bounds.
+5. Fewer, larger notes beat many small ones; the builder works one note at a time within a fixed
+ session and must keep the build passing.
+
+Answer in the given JSON schema only.
diff --git a/plugins/scene_director/scene_director/prompts/director_user.md b/plugins/scene_director/scene_director/prompts/director_user.md
new file mode 100644
index 00000000..26de13ad
--- /dev/null
+++ b/plugins/scene_director/scene_director/prompts/director_user.md
@@ -0,0 +1,18 @@
+REQUEST (the user's prompt): {prompt}
+
+HOW IT WILL BE FILMED: {shot}
+
+PLAN: "{title}" — {setting}. Mood: {mood}
+Environment: {environment}
+Zones and their contents:
+{zones}
+
+Valid note targets: {targets}
+
+FRAMES ATTACHED (one per delivery camera, in this order):
+{views}
+
+The judge already reported (do not repeat these):
+{judged}
+
+Write at most {max_notes} notes, the biggest visual win first.