Skip to content

Official Codebase of 3DCodeVerse

Python

scene assets may compose the effect library: the asset check budgets and seats what a factory built as the library's (D100)

gaoypeng96b1948e59c5
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js
index 2b45620b..b6c57f7f 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js
@@ -27,6 +27,17 @@ export function snapshotResources(root, {
return resources;
}
+/** Every object in a factory's tree when it claimed ownership (attachDisposal):
+ * how a check tells what the library built from what its caller built around it.
+ * Weak, so it keeps nothing alive; caller additions made afterwards are not in it.
+ */
+const BUILT = new WeakSet();
+
+/** Did a library factory build this object (it was in the tree it claimed)? */
+export function isLibraryBuilt(object) {
+ return BUILT.has(object);
+}
+
/** Install userData.dispose() for an explicit iterable of owned resources.
* Duplicate resources are released once; repeated disposal is harmless. A
* resource may be a Three.js disposable or {dispose(){...}} for external state.
@@ -39,6 +50,7 @@ export function attachDisposal(root, resources) {
throw new TypeError('Every owned resource must implement dispose()');
}
}
+ if (typeof root.traverse === 'function') root.traverse((object) => BUILT.add(object));
let disposed = false;
root.userData.dispose = () => {
if (disposed) return false;
diff --git a/harness/codeverse3d/prompts/scene_threejs/asset.md b/harness/codeverse3d/prompts/scene_threejs/asset.md
index 92090f34..59291686 100644
--- a/harness/codeverse3d/prompts/scene_threejs/asset.md
+++ b/harness/codeverse3d/prompts/scene_threejs/asset.md
@@ -1,7 +1,8 @@
You write ONE self-contained three.js ESM asset module for a larger scene — a factory
function returning a `THREE.Group`, built from raw geometry primitives. Raw three.js only:
-no DOM, no texture or image loading, no fetch, no imports beyond
-`import * as THREE from 'three'`.
+no DOM, no texture or image loading, no fetch. Imports: `import * as THREE from 'three'`, and
+the scene's shipped effect library `../lib/*.js` when the task sheet names one of its factories —
+it is harness code that ships with every scene, not an outside package.
The module is judged as a prop, at scene distance: silhouette first, then the 2-3
recognisable features a person would name, then wear that makes it look used. The task
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index 3d22c78c..91de7100 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -11,8 +11,8 @@ and then build it with `makeShaderMaterial` / `patchStandard` from
`lib/shader.js`.
Import with a relative path from the file you are writing — `src/zones/x.js`
-says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
-`'./lib/grass.js'`.
+and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,
+`src/scene.js` says `'./lib/grass.js'`.
| Want | Call |
| --- | --- |
diff --git a/harness/codeverse3d/prompts/tracks/plan_scene.j2 b/harness/codeverse3d/prompts/tracks/plan_scene.j2
index 3a9c6e07..9d7397e3 100644
--- a/harness/codeverse3d/prompts/tracks/plan_scene.j2
+++ b/harness/codeverse3d/prompts/tracks/plan_scene.j2
@@ -21,9 +21,11 @@ one of them (a Waterfall, OakTree, BoulderCluster, StreamRibbon, Flame or GrassP
an element they do not cover (a pine, a palm, a carved stone) is still an asset, and so is a
grove or forest of many trees: each `makeTree` is a full tree, heavy enough that a whole grove of
them can crash the page.
-The standalone asset stage only imports Three.js; shipped effects must be composed
-by zone/environment code, which may import `../lib/`. Zone `contents` still lists
-only actual asset names; library effects belong in prose, not invented asset ids.
+A `threejs` asset may compose a factory with its own parts (a shrine with a `makeTree` beside it,
+a well ringed by `makeRock`s): name the call and its module (`makeTree`, `tree.js`) in that
+asset's description, and the asset imports `../lib/`. A `blender_glb` hero cannot. Zone
+`contents` still lists only actual asset names; library effects a zone places itself belong in
+prose, not invented asset ids.
Plan the stream's upstream-to-downstream path once, with nonincreasing Y, and
require terrain banks to use that same surface sampler and local coordinate frame.
The zone drives each effect's `userData.update(t, dt)` exactly once per frame.
diff --git a/harness/codeverse3d/prompts/tracks/scene_asset.j2 b/harness/codeverse3d/prompts/tracks/scene_asset.j2
index 1ccb2309..4f4aef66 100644
--- a/harness/codeverse3d/prompts/tracks/scene_asset.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_asset.j2
@@ -57,6 +57,13 @@ Scene: {{ spec_prompt }}
`userData.tick` is never called by anything). Amplitudes must be visible after 1.5 s:
>= 0.10 rad of rotation or >= 0.05 m of travel — not sub-centimetre jitter.
- Segments 12-24.
+{% if library_rows %}
+- The sheet names shipped effect-library factories. `src/lib/` ships with the scene: import them
+ (`import { makeTree } from '../lib/tree.js'`) and compose what they return into your group
+ instead of rebuilding them. Each returned object stands on its own origin; place it by that
+ origin, and pass the lighter options its row names when the asset is repeated.
+{{ library_rows }}
+{% endif %}
{% endif %}
## DO / DON'T
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
index 0f440f0c..be7d86dc 100644
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ b/harness/codeverse3d/tracks/scene_assets.py
@@ -34,7 +34,7 @@ from codeverse3d.contracts.artifacts import Judgment
from codeverse3d.contracts.common import ENTRY_FILE, Language, Track
from codeverse3d.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlan
from codeverse3d.contracts.spec import Constraints, Spec
-from codeverse3d.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
+from codeverse3d.conventions import MAX_TRIS_OBJECT, OBJECT_VIEWS_QUICK, to_pascal, to_snake
from codeverse3d.languages.scene_threejs import asset_file
from codeverse3d.orchestrator import BudgetExceeded
from codeverse3d.proc import fan_out, read_json_or_none, write_json_atomic
@@ -706,10 +706,28 @@ def _scene_context(ctx: RunContext) -> dict[str, Any]:
return {"spec_prompt": brief, "constraints": ctx.extra.get("scene_style") or "(none)"} if brief else {}
+#: what names a library row: a camelCase factory right after a backtick (``makeTree(``,
+#: ``patchMoss``) — a bare lowercase one (``seat``, ``block``) is an ordinary word in a sheet —
+#: and the module it lives in (``lib/tree.js``)
+_CATALOG_CALL_RE = re.compile(r"`([a-z]+[A-Z]\w*)[(`]")
+_CATALOG_MODULE_RE = re.compile(r"`lib/(\w+\.js)`")
+
+
+def library_rows(description: str) -> str:
+ """The effects-catalog rows of the library factories an asset sheet names, by call or by module
+ (D100): a three.js asset may compose ``src/lib/``, and a single-shot writer cannot open the
+ module to learn the call — the rows carry it. The whole catalog is a zone-sized prompt."""
+ words = set(re.findall(r"\w+(?:\.\w+)*", description))
+ return "\n".join(line for line in language_text(Language.SCENE_THREEJS, "effects_catalog.md").splitlines()
+ if line.startswith("| ")
+ and words & (set(_CATALOG_CALL_RE.findall(line)) | set(_CATALOG_MODULE_RE.findall(line))))
+
+
def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str] | None = None) -> str:
files = list(files or [rel])
prompt = render("tracks/scene_asset.j2", **base_prompt_context(
ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description, asset_size=asset.approx_size_m,
+ library_rows=library_rows(asset.description) if language is Language.SCENE_THREEJS else "",
asset_file=rel, asset_files=files, asset_language=language.value, fix_instructions=[], current_code="",
# a single-shot hero has to see the multi-file skeleton it is filling in, like a static object
skeleton_files=skeleton_files(ctx) if (ctx.single_shot and len(files) > 1) else {},
@@ -774,7 +792,8 @@ class AssetCheck(BaseModel):
warnings: list[str] = Field(default_factory=list)
size_m: tuple[float, float, float] | None = None
min_y: float | None = None
- tris: int = 0
+ tris: int = Field(default=0, description="triangles the asset built itself (the per-asset budget)")
+ lib_tris: int = Field(default=0, description="triangles the effect-library factories it composes built (D100)")
meshes: int = 0
materials: int = 0
glb: str = Field(default="", description="the built GLB (blender heroes), '' for a module")
@@ -795,7 +814,10 @@ def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: fl
try:
from codeverse3d.spatial.node import run_node, runtime_js_dir
- res = run_node(runtime_js_dir() / "lib" / "asset_check.mjs", [path.resolve().as_uri(), f"build{pascal}"], cwd=ctx.ws.root,
+ # the workspace's own lib/lifecycle.js: the instance the asset's `../lib/` imports load (D100)
+ lifecycle = ctx.ws.src / "lib" / "lifecycle.js"
+ args = [path.resolve().as_uri(), f"build{pascal}"] + ([lifecycle.resolve().as_uri()] if lifecycle.is_file() else [])
+ res = run_node(runtime_js_dir() / "lib" / "asset_check.mjs", args, cwd=ctx.ws.root,
three_hook=True, timeout_s=timeout_s, check=False)
data = res.last_json
if data is None:
@@ -804,7 +826,7 @@ def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: fl
chk = AssetCheck(ok=bool(data.get("ok")), ran=True, errors=list(data.get("errors") or []),
warnings=list(data.get("warnings") or []),
size_m=tuple(data["size_m"]) if data.get("size_m") else None, # type: ignore[arg-type]
- min_y=data.get("min_y"), tris=int(data.get("tris") or 0),
+ min_y=data.get("min_y"), tris=int(data.get("tris") or 0), lib_tris=int(data.get("lib_tris") or 0),
meshes=int(data.get("meshes") or 0), materials=int(data.get("materials") or 0))
except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
log.warning("asset check could not run for %s: %s", rel, e)
@@ -822,7 +844,10 @@ def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None,
chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")
if chk.tris > max_tris:
chk.errors.append(f"{chk.tris} triangles exceeds the {max_tris} budget per asset — lower the segment counts")
- if chk.meshes == 1 and chk.materials <= 1 and chk.tris < 200:
+ if chk.tris + chk.lib_tris > MAX_TRIS_OBJECT:
+ chk.errors.append(f"the effect-library factories it calls build {chk.lib_tris} triangles, past the {MAX_TRIS_OBJECT} "
+ "ceiling for one object — pass their lighter options (fewer leaves, fewer leaf segments) or call fewer")
+ if chk.meshes == 1 and chk.materials <= 1 and chk.tris + chk.lib_tris < 200:
chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several "
"parts with distinct materials so it reads as the described object")
if expected and chk.size_m:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 0c343b97..237ed64f 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -338,8 +338,12 @@ summary:
Plus the harness-owned, read-only **effect library** `src/lib/*.js` (the starter's other
`.js` files are the example scene), shipped into every workspace by BOTH skeleton paths and
listed in `HARNESS_OWNED_SRC` so agent writes to it are reverted (D51, D97). The want → call
- table the prompts carry is `prompts/scene_threejs/effects_catalog.md`; an asset module
- imports only `three` (`prompts/scene_threejs/asset.md`), so effects are called from zone/env code.
+ table the prompts carry is `prompts/scene_threejs/effects_catalog.md`. A three.js asset module
+ may compose it too (D100): its prompt carries the catalog rows of the factories its sheet names
+ (`scene_assets.library_rows`), and the asset check (`runtime_js/lib/asset_check.mjs`) counts what
+ a factory built — `lib/lifecycle.js` `isLibraryBuilt` — as `lib_tris` against the one-object
+ ceiling, not the per-asset budget, and seats a factory by its origin. `src/lib/` is committed
+ with `src/`, so the deliverable and the dataset sample carry it.
* **glsl_shader**: `src/shader.frag` (+ optional `src/common.glsl`,
`src/buffer_a.frag` for feedback; the harness-owned, read-only `src/recipes.glsl`
is pasted above them when the track seeded recipes) — the agent never writes
diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.md
index af0fc261..3d743b19 100644
--- a/harness/docs/DECISIONS.md
+++ b/harness/docs/DECISIONS.md
@@ -1015,7 +1015,8 @@ Pointers: EVAL, PAPER_WRITING = `eval/docs/*.md`; COST, RUNBOOK, ARCHITECTURE, I
`src/shaders/*.{vert,frag,glsl}` as text (audited by `shader_report`). Named bugs: three r182 compiles
`PCFSoftShadowMap` as BASIC (the renderer uses `PCFShadowMap`); the census missed shader-instanced
geometry; GlHost doubled a relative out dir. Tests follow D96 (a BUILD row + a GPU group each). The
- catalog and planner say the effects are zone code, never assets, with no limits stated (D93).
+ catalog and planner say the effects are zone code, never assets, with no limits stated (D93) — the
+ "never assets" half is superseded by D100.
`examples/graphics_lab/` is a dev lab (sixteen hand-composed studies rendered through the production
scene and GL hosts); its `output/` is ignored and none of its media is committed. 2026-09-23: the lab's
session notes, provenance tooling, audit logs and the unused cinematic judge were deleted (owner); the lab
@@ -1060,6 +1061,24 @@ Pointers: EVAL, PAPER_WRITING = `eval/docs/*.md`; COST, RUNBOOK, ARCHITECTURE, I
and after this commit differs by the fps line and two rubric phrases. A draw WARN is still a gate WARN in
the judge's list, which the judge is told never makes a defect present.
+* **D100 A three.js scene asset may import the effect library (owner, 2026-09-24).** `src/assets/<snake>.js`
+ may `import { makeTree } from '../lib/tree.js'` and compose a factory with its own parts: `src/lib/` is
+ copied into every workspace and committed with `src/`, so the deliverable and the dataset sample (both
+ read the round's commit) carry it and the output stays self-contained — a copied-out deliverable boots
+ alone. Until now `asset.md` said "no imports beyond three" and `plan_scene.j2` routed every effect to
+ zone/env code; the code never rejected the import (lint, node check and GLB export all resolve
+ `../lib/`), but the asset check did: a factory's triangles counted against the per-asset budget (one
+ lean birch is 80 k, the wood alone 75 k) and its below-grade roots read as "sinks", so every such asset
+ failed twice and escalated to an agent session. Now `lib/lifecycle.js` `attachDisposal` records the
+ tree it claims (`isLibraryBuilt`, a WeakSet); `asset_check.mjs` loads the workspace's own lifecycle
+ module (the instance the asset's imports load) and reports what a factory built as `lib_tris` — held to
+ the one-object ceiling `MAX_TRIS_OBJECT`, not `ASSET_MAX_TRIS` — and seats a factory by its origin. The
+ asset's own geometry keeps every rule. A `blender_glb` hero cannot import it. The asset prompt carries
+ only the catalog rows of the factories its sheet names (by camelCase call or module file,
+ `scene_assets.library_rows`), not the whole catalog. Not changed: the scene placement gate still
+ measures an asset's lowest vertex, so a library tree's roots inside a non-exempt asset name can read
+ as sunken there, as they already did for zone-placed trees.
+
## Rejected / deferred
* A versioned `Spec`/`RunRecord`/`RunState` load-normaliser (rejected 2026-08-30: of the seven
diff --git a/harness/runtime_js/lib/asset_check.mjs b/harness/runtime_js/lib/asset_check.mjs
index 005894f7..12df39be 100644
--- a/harness/runtime_js/lib/asset_check.mjs
+++ b/harness/runtime_js/lib/asset_check.mjs
@@ -1,12 +1,18 @@
// The scene-asset checker: import one asset module, call its build<Pascal>(THREE, {}) and
// measure the group it returns (size, triangles, meshes, materials, NaN positions).
-// node --import lib/resolve_three.mjs lib/asset_check.mjs FILE_URL EXPORT_NAME → one JSON line
+// node --import lib/resolve_three.mjs lib/asset_check.mjs FILE_URL EXPORT_NAME [LIFECYCLE_URL]
+// → one JSON line
// (tracks/scene_assets.check_threejs_asset: spatial.node.run_node(three_hook=True)).
+// An asset may compose the workspace's effect library (D100). LIFECYCLE_URL is that library's
+// lib/lifecycle.js, the SAME module instance the asset's own imports load, so `isLibraryBuilt` says
+// which objects a factory built: their triangles are `lib_tris`, not `tris`, and a factory's foot
+// is its origin (a tree's roots go below grade by design), not its lowest vertex.
import * as THREE from 'three';
-const [, , fileUrl, exportName] = process.argv;
-const out = { ok: false, errors: [], warnings: [], size_m: null, tris: 0, meshes: 0, materials: 0 };
+const [, , fileUrl, exportName, lifecycleUrl] = process.argv;
+const out = { ok: false, errors: [], warnings: [], size_m: null, tris: 0, lib_tris: 0, meshes: 0, materials: 0 };
try {
+ const isLibraryBuilt = lifecycleUrl ? (await import(lifecycleUrl)).isLibraryBuilt : () => false;
const mod = await import(fileUrl);
const fn = mod[exportName] ?? mod.default;
if (typeof fn !== 'function') {
@@ -18,8 +24,11 @@ try {
} else {
const box = new THREE.Box3().setFromObject(g);
const mats = new Set();
- let bad = 0;
+ let bad = 0, footY = Infinity;
+ const part = new THREE.Box3(), at = new THREE.Vector3();
g.traverse((o) => {
+ const built = isLibraryBuilt(o);
+ if (built && !isLibraryBuilt(o.parent)) footY = Math.min(footY, o.getWorldPosition(at).y);
if (!o.isMesh) return;
out.meshes += 1;
mats.add(o.material?.uuid ?? o.material);
@@ -28,7 +37,12 @@ try {
const arr = pos.array;
for (let i = 0; i < arr.length; i++) if (!Number.isFinite(arr[i])) { bad += 1; break; }
const idx = o.geometry.index;
- out.tris += ((idx ? idx.count : pos.count) / 3) * (o.isInstancedMesh ? o.count : 1);
+ const tris = ((idx ? idx.count : pos.count) / 3) * (o.isInstancedMesh ? o.count : 1);
+ if (built) { out.lib_tris += tris; return; }
+ out.tris += tris;
+ if (o.isInstancedMesh) { o.computeBoundingBox(); part.copy(o.boundingBox); }
+ else { o.geometry.computeBoundingBox(); part.copy(o.geometry.boundingBox); }
+ if (!part.isEmpty()) footY = Math.min(footY, part.applyMatrix4(o.matrixWorld).min.y);
});
out.materials = mats.size;
if (bad) out.errors.push(`${bad} mesh(es) have NaN/Infinity vertex positions`);
@@ -37,9 +51,13 @@ try {
else {
const s = new THREE.Vector3(); box.getSize(s);
if (!Number.isFinite(s.x + s.y + s.z)) out.errors.push('the bounding box is not finite');
- else { out.size_m = [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)]; out.min_y = +box.min.y.toFixed(3); }
+ else {
+ out.size_m = [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)];
+ out.min_y = +(Number.isFinite(footY) ? footY : box.min.y).toFixed(3);
+ }
}
out.tris = Math.round(out.tris);
+ out.lib_tris = Math.round(out.lib_tris);
}
}
} catch (e) {
diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.py
index 8e9478ca..432886d6 100644
--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py
+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py
@@ -91,6 +91,15 @@ def test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):
sa = render("tracks/scene_asset.j2", **base_prompt_context(ctx, asset_name="Bollard", asset_kind="threejs", asset_description="d", asset_size=(0.3, 0.5, 0.3),
asset_file="src/assets/bollard.js", asset_language="scene_threejs", fix_instructions=["- x"], current_code=""))
assert "buildBollard" in sa and "FIX PASS" in sa
+ # D100: a three.js asset whose sheet names a library factory gets that factory's catalog row
+ from codeverse3d.tracks.scene_assets import _asset_prompt
+
+ shrine = plan.assets[0].model_copy(update={"description": "a wayside shrine with a birch (makeTree) beside it"})
+ lead = "The sheet names shipped effect-library factories"
+ with_lib = _asset_prompt(ctx, shrine, "src/assets/shrine.js", language=Language.SCENE_THREEJS)
+ assert lead in with_lib and "leafSegments" in with_lib and "`lib/rock.js`" not in with_lib
+ assert lead not in _asset_prompt(ctx, plan.assets[0], "src/assets/x.js", language=Language.SCENE_THREEJS)
+ assert lead not in _asset_prompt(ctx, shrine, "src/model.py", language=Language.BLENDER)
# ... but a committed, import-broken module is NOT reused: it goes back through generation
(tmp_ws.root / boat.path).write_text("export function nope() {}\n")
third = run_asset_stage(ctx)
diff --git a/harness/tests/scene_runtime/test_runtime.py b/harness/tests/scene_runtime/test_runtime.py
index bc0d788b..4127925a 100644
--- a/harness/tests/scene_runtime/test_runtime.py
+++ b/harness/tests/scene_runtime/test_runtime.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+from types import SimpleNamespace
import pytest
@@ -27,13 +28,66 @@ def test_runtime_registered_conforms_and_writes_skeleton(ws):
assert (ws.src / "scene.js") in paths
+#: an asset module composing an effect-library factory around its own plinth (D100)
+LIB_ASSET = """import { makeTree } from '../lib/tree.js';
+export function buildBirchStand(THREE, opts = {}) {
+ const g = new THREE.Group(); g.name = 'BirchStand';
+ const tree = makeTree({ species: 'birch', height: 5, leafSegments: 3, maxLeaves: 400, seed: opts.seed ?? 3 });
+ g.add(tree);
+ const plinth = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.6, 0.2, 12),
+ new THREE.MeshStandardMaterial({ color: 0x6b6259 }));
+ plinth.position.y = 0.1; g.add(plinth);
+ return g;
+}
+"""
+
+
+def add_lib_asset(ws, body: str = LIB_ASSET) -> str:
+ rel = "src/assets/birch_stand.js"
+ (ws.root / rel).parent.mkdir(parents=True, exist_ok=True)
+ (ws.root / rel).write_text(body)
+ return rel
+
+
+def test_asset_composing_a_library_factory_passes_the_asset_check(starter_ws):
+ """D100: an asset may import ``../lib/``. The factory's triangles are the library's, not the
+ asset's budget, and its foot is its origin (a tree's roots go below grade by design) — before,
+ every such asset failed the check (80k tris "over budget", roots "sinking") and escalated."""
+ from codeverse3d.languages.scene_threejs import lint
+ from codeverse3d.tracks.scene_assets import ASSET_MAX_TRIS, check_threejs_asset
+
+ ctx = SimpleNamespace(ws=starter_ws)
+ rel = add_lib_asset(starter_ws)
+ assert not [f for f in lint(starter_ws).findings if f.target.startswith(rel)]
+ chk = check_threejs_asset(ctx, rel, "BirchStand", expected_size_m=(3.0, 5.0, 3.0))
+ assert chk.ran and chk.ok, chk.errors
+ assert chk.tris < 200 < ASSET_MAX_TRIS < chk.lib_tris and chk.min_y == 0.0
+ # the asset's OWN geometry is still held to the rules — a sunk plinth — and so is where it
+ # puts a factory: a tree lowered by half a metre sinks by its origin
+ for sunk, text in (("plinth.position.y = -0.3", "sinks 0.40 m"), ("plinth.position.y = 0.1; tree.position.y = -0.5", "sinks 0.50 m")):
+ add_lib_asset(starter_ws, LIB_ASSET.replace("plinth.position.y = 0.1", sunk))
+ assert any(text in e for e in check_threejs_asset(ctx, rel, "BirchStand").errors), sunk
+ # ... and a factory at its heaviest defaults is past the one-object ceiling
+ add_lib_asset(starter_ws, LIB_ASSET.replace("leafSegments: 3, maxLeaves: 400, ", ""))
+ heavy = check_threejs_asset(ctx, rel, "BirchStand")
+ assert not heavy.fatal and any("effect-library factories" in e for e in heavy.errors), heavy.errors
+
+
@pytest.mark.node
@needs_browser
def test_build_ok_on_example(starter_ws):
- """The example scene: one probe boot passes both gates and records its census."""
+ """The example scene: one probe boot passes both gates and records its census — with a zone
+ placing an asset that composes a library factory (D100)."""
+ add_lib_asset(starter_ws)
+ meadow = starter_ws.src / "zones" / "meadow.js"
+ meadow.write_text(meadow.read_text()
+ .replace("import { buildWindmill }", "import { buildBirchStand } from '../assets/birch_stand.js';\nimport { buildWindmill }")
+ .replace(" return zone;\n", " const stand = buildBirchStand(THREE); stand.position.set(6, 0, 6); zone.add(stand);\n return zone;\n"))
rt = SceneThreeJsRuntime()
res = rt.build(starter_ws)
assert res.ok, res.stdout_tail
+ assert "BirchStand" in json.dumps(res.census), "the zone placed the library-composing asset"
assert res.language == "scene_threejs" and res.glb_path is None
census = res.census
assert census["totals"]["meshes"] > 10 and census["totals"]["lights"] == 3
@@ -152,3 +206,28 @@ def test_probe_crash_leaves_no_stale_probe_outputs(ws, monkeypatch):
for name in ("census.json", "scene_probe.json", "shader_preflight.json"):
assert not (ws.artifacts / name).exists(), name
assert json.loads((ws.artifacts / "build.json").read_text())["ok"] is False
+
+
+def test_hand_over_of_a_library_composing_asset_is_self_contained(starter_ws):
+ """D100: the deliverable and the dataset sample read the round's commit, and ``src/lib/`` is
+ committed with ``src/`` — every import of the handed-over code resolves inside it."""
+ from codeverse3d.addons.dataset.sample import code_files_for_round
+ from codeverse3d.contracts.common import Track
+ from codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus
+ from codeverse3d.contracts.spec import Spec
+ from codeverse3d.languages.scene_threejs import lint
+ from codeverse3d.record.deliverable import build_deliverable
+ from codeverse3d.workspace import Workspace
+
+ add_lib_asset(starter_ws)
+ rnd = RoundRecord(index=0, kind="baseline", commit=starter_ws.commit("r0"))
+ rec = RunRecord(spec=Spec(id="s", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a grove"),
+ workspace=str(starter_ws.root), status=RunStatus.MAX_ROUNDS, rounds=[rnd])
+ manifest = build_deliverable(starter_ws, rec, 0)
+ shipped = {f.path for f in manifest.files}
+ assert {"deliverable/src/assets/birch_stand.js", "deliverable/src/lib/tree.js", "deliverable/src/lib/lifecycle.js"} <= shipped
+ bad = [f for f in lint(Workspace(starter_ws.deliverable)).findings if f.data.get("kind") == "bad_import"]
+ assert not bad, bad
+ files, source = code_files_for_round(starter_ws, rnd)
+ assert source == "commit" and {p[len("deliverable/"):] for p in shipped if p.startswith("deliverable/src/")} <= set(files)