Official Codebase of 3DCodeVerse
Python
Remove the unreachable derive-cameras path from both scene assemblers; one AssembleResult
gaoypeng1e9dc23e0ed3
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.pyindex f5528c84..bb2351af 100644--- a/harness/codeverse3d/languages/base.py+++ b/harness/codeverse3d/languages/base.py@@ -5,9 +5,9 @@ from __future__ import annotationsfrom collections.abc import Callable, Sequencefrom importlib import import_modulefrom pathlib import Path-from typing import TYPE_CHECKING, Protocol, runtime_checkable+from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom codeverse3d.contracts.artifacts import BuildResult, GateReport, RenderSetfrom codeverse3d.contracts.common import ENTRY_FILE, Language@@ -19,6 +19,15 @@ if TYPE_CHECKING:from codeverse3d.spatial.probes import SceneProbeResult+class AssembleResult(BaseModel):+ scene_path: str+ zones_included: list[str] = Field(default_factory=list)+ zones_failed: dict[str, str] = Field(default_factory=dict)+ env_ok: bool = True+ warnings: list[str] = Field(default_factory=list)+ census: dict[str, Any] = Field(default_factory=dict)++@runtime_checkableclass LanguageRuntime(Protocol):language: Languagediff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.pyindex 4f23da46..73763962 100644--- a/harness/codeverse3d/languages/scene_blender/__init__.py+++ b/harness/codeverse3d/languages/scene_blender/__init__.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport astimport jsonimport logging-import mathimport reimport timefrom collections.abc import Sequence@@ -53,7 +52,7 @@ from codeverse3d.languages._common import (target_line,ws_rel,)-from codeverse3d.languages.base import scene_files_for+from codeverse3d.languages.base import AssembleResult, scene_files_forfrom codeverse3d.languages.blender import (BlenderNotFoundError,BpyCollector,@@ -625,39 +624,6 @@ class WrapperRun(BaseModel):facts: dict[str, Any] = Field(default_factory=dict)-_SUN_RE = re.compile(r"^SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)", re.M)---def _fallback_camera(plan: ScenePlan | None, ws: Workspace | None = None) -> CameraPlan:- """An overview camera (PLAN frame) on the lit side at the bounds' span, for a plan with no camera."""- from codeverse3d.languages.scene_threejs import SUN_AZIMUTH_GUESS_DEG-- azimuth = SUN_AZIMUTH_GUESS_DEG- env = (ws.src / "env.py") if ws is not None else None- if env is not None and env.is_file():- m = _SUN_RE.search(env.read_text(errors="replace"))- if m:- azimuth = float(m.group(1))- if plan is None:- c, r = (0.0, 0.0, 0.0), 30.0- else:- c = tuple(float(v) for v in plan.bounds.center)- r = max(float(plan.bounds.extents[0]), float(plan.bounds.extents[2]), 10.0)- a = math.radians(azimuth)- return CameraPlan(name="overview", position=(c[0] + 0.9 * r * math.cos(a), c[1] + 0.45 * r, c[2] - 0.9 * r * math.sin(a)),- look_at=(c[0], c[1] + 1.0, c[2]), fov=50.0, purpose="fallback: the plan names no camera")---class AssembleResult(BaseModel):- scene_path: str- zones_included: list[str] = Field(default_factory=list)- zones_failed: dict[str, str] = Field(default_factory=dict)- env_ok: bool = True- cameras: list[CameraPlan] = Field(default_factory=list)- warnings: list[str] = Field(default_factory=list)- census: dict[str, Any] = Field(default_factory=dict)--class SceneBlenderRuntime:language = LANGUAGE@@ -871,14 +837,13 @@ def stage_findings(report: dict[str, Any]) -> list[GateFinding]:_ASSEMBLE_OUT = "assemble_probe"-def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan | None, *, probe: bool = True,- timeout_s: float | None = None) -> AssembleResult:+def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan, *, timeout_s: float | None = None) -> AssembleResult:zones = [p.stem for p in module_files(ws, "zones")]if not zones:raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")assets = [p.stem for p in module_files(ws, "assets")]heroes = [p.stem for p in hero_files(ws)]- cams = list(plan.cameras[:6]) if plan is not None and plan.cameras else [_fallback_camera(plan, ws)]+ cams = list(plan.cameras[:6])warnings: list[str] = []env_ok = (ws.src / "env.py").is_file()if not env_ok:@@ -886,28 +851,27 @@ def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan | Nonehealthy, failed = list(zones), {}census: dict[str, Any] = {}out = ws.root / ENTRY_REL- if probe:- # the probe run's entry lists every asset and hero; zones come from --zones- out.parent.mkdir(parents=True, exist_ok=True)- out.write_text(render_scene_py([], assets, heroes, cams))- run = runtime.run_wrapper(ws, ws.artifacts / _ASSEMBLE_OUT, zones={z: to_pascal(z) for z in zones}, blend=False,- timeout_s=timeout_s)- if run.result.ok or run.report.get("zones_ok") is not None:- healthy = [z for z in zones if z in set(run.report.get("zones_ok") or [])]- failed = {z: str(m) for z, m in (run.report.get("zones_failed") or {}).items()}- else:- warnings.append(f"assembler probe did not run: {run.result.error_type}: {run.result.error_message}"[:300])- for e in run.report.get("errors") or []:- if e.get("stage") == "env":- env_ok = False- warnings.append(f"env.py failed in probe: {e.get('error_type')}: {e.get('error_message')}"[:300])- census = {k: run.facts[k] for k in ("lights", "fog", "background", "unique_tris", "instanced_tris") if k in run.facts}+ # the probe run's entry lists every asset and hero; zones come from --zones+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(render_scene_py([], assets, heroes, cams))+ run = runtime.run_wrapper(ws, ws.artifacts / _ASSEMBLE_OUT, zones={z: to_pascal(z) for z in zones}, blend=False,+ timeout_s=timeout_s)+ if run.result.ok or run.report.get("zones_ok") is not None:+ healthy = [z for z in zones if z in set(run.report.get("zones_ok") or [])]+ failed = {z: str(m) for z, m in (run.report.get("zones_failed") or {}).items()}+ else:+ warnings.append(f"assembler probe did not run: {run.result.error_type}: {run.result.error_message}"[:300])+ for e in run.report.get("errors") or []:+ if e.get("stage") == "env":+ env_ok = False+ warnings.append(f"env.py failed in probe: {e.get('error_type')}: {e.get('error_message')}"[:300])+ census = {k: run.facts[k] for k in ("lights", "fog", "background", "unique_tris", "instanced_tris") if k in run.facts}if not healthy:warnings.append("no zone module survived probing; scene.py assembled with zero zones")- out.write_text(render_scene_py(healthy, assets, heroes, cams, title=getattr(plan, "title", ""),- summary=getattr(plan, "summary", "")))+ out.write_text(render_scene_py(healthy, assets, heroes, cams, title=plan.title,+ summary=plan.summary))result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,- cameras=cams, warnings=warnings, census=census)+ warnings=warnings, census=census)ws.write_json(ws.artifacts / "assemble.json", result)return resultdiff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.pyindex 1827f992..852e2a3a 100644--- a/harness/codeverse3d/languages/scene_threejs/__init__.py+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py@@ -2,7 +2,6 @@from __future__ import annotations-import mathimport reimport timefrom collections.abc import Sequence@@ -35,7 +34,7 @@ from codeverse3d.languages._js_lint import (node_check_syntax,strip_js,)-from codeverse3d.languages.base import scene_files_for+from codeverse3d.languages.base import AssembleResult, scene_files_forfrom codeverse3d.workspace import Workspaceif TYPE_CHECKING:@@ -386,7 +385,6 @@ def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:# ===================================================================== assemblePROBE_REL = "src/_c3v_assemble_probe.js"_PREFIX = "[3dcode-assemble]"-_SUN_RE = re.compile(r"export\s+const\s+SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)")class ZoneProbe(BaseModel):@@ -394,9 +392,6 @@ class ZoneProbe(BaseModel):file: strok: boolerror: str = ""- bbox: dict[str, Any] | None = None- meshes: int = 0- triangles: int = 0class ZoneProbeReport(BaseModel):@@ -404,17 +399,6 @@ class ZoneProbeReport(BaseModel):probes: dict[str, ZoneProbe] = Field(default_factory=dict)census: dict[str, Any] = Field(default_factory=dict)other_errors: list[str] = Field(default_factory=list)- camera_specs: dict[str, Any] = Field(default_factory=dict)---class AssembleResult(BaseModel):- scene_path: str- zones_included: list[str] = Field(default_factory=list)- zones_failed: dict[str, str] = Field(default_factory=dict)- env_ok: bool = True- cameras: list[CameraPlan] = Field(default_factory=list)- warnings: list[str] = Field(default_factory=list)- census: dict[str, Any] = Field(default_factory=dict)def zone_files(ws: Workspace) -> list[Path]:@@ -427,15 +411,6 @@ def glb_assets(ws: Workspace) -> list[str]:return sorted(p.stem for p in d.glob("*.glb")) if d.is_dir() else []-def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:- env = ws.src / "env.js"- if env.is_file():- m = _SUN_RE.search(env.read_text(errors="replace"))- if m:- return float(m.group(1))- return default--#: How a Blender-built asset is preloaded in every assembled entry point. The loaded root is#: NAMED after its asset (``to_pascal`` of the file key): a glTF root arrives as "Scene", which#: name-based checks cannot see.@@ -513,20 +488,16 @@ export async function createScene({{ renderer, loaders }}) {{"""-def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_deg: float | None = None) -> ZoneProbeReport:+def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0) -> ZoneProbeReport:from codeverse3d.spatial.render_scene import run_scene_scriptzones = zone_files(ws)probe_path = ws.root / PROBE_RELprobe_path.write_text(_probe_module(zones, glb_assets(ws)))- from codeverse3d.spatial.render_scene import _bounds_json, plan_bounds, probe_env_args+ from codeverse3d.spatial.render_scene import probe_env_argsargs = ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))]args += probe_env_args()- if sun_azimuth_deg is not None:- args += ["--sun-azimuth", str(sun_azimuth_deg)]- if (bounds := plan_bounds(ws)) is not None:- args += ["--bounds", _bounds_json(bounds)]try:res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)finally:@@ -554,9 +525,8 @@ def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_deprobes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=False,error=failed.get(name, "zone not present after probe (build returned nothing visible?)"))else:- probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=True, bbox=g.get("bbox"),- meshes=g.get("meshes", 0), triangles=g.get("triangles", 0))- return ZoneProbeReport(probes=probes, census=census, other_errors=other, camera_specs=s.get("fitted_cameras") or {})+ probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=True)+ return ZoneProbeReport(probes=probes, census=census, other_errors=other)# --------------------------------------------------------------------------- the env module alone@@ -612,42 +582,6 @@ def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:return f"{rel}: {dark.message}" if dark is not None else ""-# --------------------------------------------------------------------------- cameras-def fallback_camera(plan: ScenePlan | None, azimuth_deg: float = SUN_AZIMUTH_GUESS_DEG) -> CameraPlan:- if plan is None:- c, r = (0.0, 0.0, 0.0), 30.0- else:- c = tuple(float(v) for v in plan.bounds.center)- r = max(float(plan.bounds.extents[0]), float(plan.bounds.extents[2]), 10.0)- a = math.radians(azimuth_deg)- return CameraPlan(name="overview", position=(c[0] + 0.9 * r * math.cos(a), c[1] + 0.45 * r, c[2] + 0.9 * r * math.sin(a)),- look_at=(c[0], c[1] + 1.0, c[2]), fov=50.0, purpose="fallback: no measurable zones")---def _plan_from_spec(spec: dict[str, Any], *, name: str, purpose: str) -> CameraPlan:- return CameraPlan(name=name, position=tuple(spec["position"]), look_at=tuple(spec["lookAt"]),- fov=float(spec.get("fov", 50.0)), purpose=purpose)---def cameras_from_specs(specs: dict[str, Any], probes: dict[str, ZoneProbe], *, max_cameras: int = 6,- plan: ScenePlan | None = None, azimuth_deg: float = SUN_AZIMUTH_GUESS_DEG) -> list[CameraPlan]:- """Convert driver-fitted camera specs into CameraPlans (overview first, then zones by footprint);- falls back to a fixed overview when nothing was measurable."""- healthy = [p for p in probes.values() if p.ok and p.bbox]- overview = (specs or {}).get("overview")- if not healthy or not overview:- return [fallback_camera(plan, azimuth_deg)]- cams = [_plan_from_spec(overview, name="overview", purpose="fallback: fitted to the measured content (the plan named no camera)")]- by_zone = {str(z.get("group", "")).removeprefix("__zone__"): z for z in (specs or {}).get("zones", [])}- by_area = sorted(healthy, key=lambda p: -(p.bbox["size"][0] * p.bbox["size"][2]))- for p in by_area[: max_cameras - 1]:- spec = by_zone.get(p.name)- if spec:- cams.append(_plan_from_spec(spec, name=f"{to_snake(p.name)}_view",- purpose=f"fallback: zone {to_pascal(p.name)} fitted to its measured bbox (the plan named no camera)"))- return cams--# --------------------------------------------------------------------------- scene.jsdef _cam_literal(c: CameraPlan) -> str:p, la = c.position, c.look_at@@ -714,8 +648,7 @@ export async function createScene({{ renderer, loaders }}) {{"""-def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "derive", probe: bool = True,- timeout_s: float = 90.0) -> AssembleResult:+def assemble(ws: Workspace, plan: ScenePlan, *, timeout_s: float = 90.0) -> AssembleResult:warnings: list[str] = []zones = zone_files(ws)if not zones:@@ -723,34 +656,23 @@ def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "deenv_ok = (ws.src / "env.js").is_file()if not env_ok:warnings.append("src/env.js missing: scene assembled without env (flat ground at y=0, no lights unless zones add them)")- probes: dict[str, ZoneProbe] = {}- census: dict[str, Any] = {}- camera_specs: dict[str, Any] = {}- if probe:- report = probe_zone_modules(ws, timeout_s=timeout_s, sun_azimuth_deg=sun_azimuth(ws))- probes, census, camera_specs = report.probes, report.census, report.camera_specs- for o in report.other_errors:- if _PREFIX in o and "env failed" in o:- env_ok = False- warnings.append(f"env.js failed in probe; assembled without it: {o[:300]}")- else:- warnings.append(o[:300])- else:- probes = {to_snake(p.stem): ZoneProbe(name=to_snake(p.stem), file=f"src/zones/{p.name}", ok=True) for p in zones}- healthy = [n for n, p in probes.items() if p.ok]- failed = {n: p.error for n, p in probes.items() if not p.ok}+ report = probe_zone_modules(ws, timeout_s=timeout_s)+ for o in report.other_errors:+ if _PREFIX in o and "env failed" in o:+ env_ok = False+ warnings.append(f"env.js failed in probe; assembled without it: {o[:300]}")+ else:+ warnings.append(o[:300])+ healthy = [n for n, p in report.probes.items() if p.ok]+ failed = {n: p.error for n, p in report.probes.items() if not p.ok}if not healthy:warnings.append("no zone module survived probing; scene.js assembled with zero zones")- if cameras == "plan" and plan is not None and plan.cameras:- cams = list(plan.cameras[:6])- else:- cams = cameras_from_specs(camera_specs, probes, plan=plan, azimuth_deg=sun_azimuth(ws))- text = render_scene_js(healthy, cams, glb_assets(ws), env_ok=env_ok)+ text = render_scene_js(healthy, list(plan.cameras[:6]), glb_assets(ws), env_ok=env_ok)out = ws.src / "scene.js"out.parent.mkdir(parents=True, exist_ok=True)out.write_text(text)result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,- cameras=cams, warnings=warnings, census=census)+ warnings=warnings, census=report.census)ws.write_json(ws.artifacts / "assemble.json", result)return result@@ -770,7 +692,7 @@ class SceneThreeJsRuntime:return list(SCENE_FILES)def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:- return assemble(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")+ return assemble(ws, plan)def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:from codeverse3d.spatial.probes import probe_scenediff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.pyindex 1381e734..a300b38e 100644--- a/harness/tests/scene_runtime/test_assemble.py+++ b/harness/tests/scene_runtime/test_assemble.py@@ -2,15 +2,16 @@from __future__ import annotations-import math-import pytest+from codeverse3d.contracts.common import Track+from codeverse3d.contracts.plan import ScenePlan+from codeverse3d.conventions import to_snakefrom codeverse3d.languages.scene_threejs import (assemble,lint,- sun_azimuth,)+from codeverse3d.tracks.planner import plan_examplefrom tests.scene_runtime.conftest import needs_browser@@ -31,16 +32,15 @@ def test_assemble_probes_each_zone_excludes_the_broken_and_boots(starter_ws):" return g;\n""}\n")- res = assemble(starter_ws)+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))+ res = assemble(starter_ws, plan)assert set(res.zones_included) == {"meadow", "pondside", "orchard"}assert "kaboom" in res.zones_failed["broken"]assert "no export build" in res.zones_failed["nobuild"]assert res.census.get("ground_y") is not Noneassert not (starter_ws.root / "src" / "_c3v_assemble_probe.js").exists()- # driver-fitted cameras: an overview plus one eye-level camera per measured zone- assert res.cameras[0].name == "overview" and res.cameras[0].position[1] > 0.5- assert {"meadow_view", "pondside_view", "orchard_view"} <= {c.name for c in res.cameras}src = (starter_ws.src / "scene.js").read_text()+ assert all(f"name: '{to_snake(c.name)}'" in src for c in plan.cameras), "the plan's cameras reach scene.js"assert "broken" not in src and "nobuild" not in src(zones / "broken.js").unlink()(zones / "nobuild.js").unlink()@@ -50,38 +50,3 @@ def test_assemble_probes_each_zone_excludes_the_broken_and_boots(starter_ws):probe = probe_scene(starter_ws)assert probe.gate.passed, [(f.target, f.message) for f in probe.gate.findings]assert "Orchard" in {g["name"] for g in probe.census.get("groups", [])}---@needs_browser-def test_fitted_overview_faces_the_lit_side_inside_the_plan_bounds(tmp_ws):- """Regressions (audit 2026-09-24 N8, N9)."""- import json-- from codeverse3d.languages.scene_threejs import probe_zone_modules-- (tmp_ws.src / "env.js").write_text("export const SUN_AZIMUTH_DEG = 135;\nexport function buildEnv() { return {}; }\n")- zones = tmp_ws.src / "zones"- zones.mkdir()- (zones / "cottage.js").write_text(- "import * as THREE from 'three';\n"- "export function build() {\n"- " const m = new THREE.Mesh(new THREE.BoxGeometry(16, 7, 12), new THREE.MeshStandardMaterial());\n"- " m.position.y = 3.5; m.name = 'Cottage'; const g = new THREE.Group(); g.add(m); return g;\n"- "}\n")- (zones / "meadow.js").write_text( # an instanced scatter 400 m wide- "import * as THREE from 'three';\n"- "export function build() {\n"- " const im = new THREE.InstancedMesh(new THREE.BoxGeometry(0.3, 1.2, 0.3), new THREE.MeshStandardMaterial(), 64);\n"- " const m = new THREE.Matrix4();\n"- " for (let i = 0; i < 64; i++) im.setMatrixAt(i, m.makeTranslation(-200 + (i % 8) * 400 / 7, 0.6, -200 + Math.floor(i / 8) * 400 / 7));\n"- " im.name = 'Grass'; const g = new THREE.Group(); g.add(im); return g;\n"- "}\n")- tmp_ws.plan_path.write_text(json.dumps({"bounds": {"center": [0, 7.5, 0], "extents": [60, 15, 60]}}))- report = probe_zone_modules(tmp_ws, sun_azimuth_deg=sun_azimuth(tmp_ws))- ov = report.camera_specs["overview"]- view = [p - q for p, q in zip(ov["position"], ov["lookAt"], strict=True)]- sun = (math.cos(math.radians(135)), math.sin(math.radians(135))) # sunRig's (x, z)- cos = (view[0] * sun[0] + view[2] * sun[1]) / math.hypot(view[0], view[2])- assert cos > 0.99, (ov, cos)- assert math.dist(ov["position"], ov["lookAt"]) < 100, ov