Official Codebase of 3DCodeVerse
Python
runtime_js: the three.js export stops re-measuring the object — census.json keeps what only the export knows
gaoypengfc158d3722f9
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.mdindex 82eaa03f..4f524812 100644--- a/harness/runtime_js/README.md+++ b/harness/runtime_js/README.md@@ -60,7 +60,9 @@ export_glb.mjs node --import lib/resolve_three.mjs export_glb.mjs --ws <wif any (throw → SelfCheckError), bakes InstancedMesh copies into named meshes(lib/instances.mjs — trimesh ignores EXT_mesh_gpu_instancing), keeps the sourceplacement (off-ground/off-centre → warning + census.placement_offset), strips textures (warning),- writes GLB + census.json; on failure export_error.json ++ writes GLB + census.json (only what the export knows: placement offset, baked+ instances, selfcheck, tick, unnamed meshes, warnings — spatial/measure.py measures+ the GLB); on failure export_error.json +{ok:false,error:{type,message,file,line,frames,part?}}render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode shaded|wire|normals|silhouette|clay][--width --height] [--isolate A,B] [--explode 0.3] [--background studio|white|transparent]@@ -73,7 +75,7 @@ lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' resolvmodule.registerHooks on node >= 22.15, module.register + lib/resolve_three_async.mjson the 20.6 floor. Redirect rule stated once in lib/three_redirect.mjslib/node_polyfills.mjs FileReader/self shims so GLTFExporter writes binary GLB without a DOM-lib/census.mjs per-part tri counts, world bboxes, materials, NaN check naming mesh + part (node + browser)+lib/census.mjs NaN/Infinity check naming mesh + part, world boxes, geometry triangles (node + browser)lib/instances.mjs bakeInstancedMeshes(THREE, root): InstancedMesh → Group of named plain mesheslib/stack.mjs Error → {type,message,file,line,frames} with workspace-relative src/ pathslib/syntax_check.mjs THE JS syntax check: every file parsed as an ES module in ONE nodediff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjsindex 06c59dcf..92730b43 100644--- a/harness/runtime_js/export_glb.mjs+++ b/harness/runtime_js/export_glb.mjs@@ -23,7 +23,7 @@ import { pathToFileURL } from 'node:url';import { finish, parseCli } from './lib/cli.mjs';import { installExporterPolyfills } from './lib/node_polyfills.mjs';-import { objectCensus, findNonFinitePositions, worldBox } from './lib/census.mjs';+import { findNonFinitePositions, worldBox } from './lib/census.mjs';import { bakeInstancedMeshes, expandInstancedMesh } from './lib/instances.mjs';import { errorRecord } from './lib/stack.mjs';import { findSyntaxError } from './lib/syntax_check.mjs';@@ -194,11 +194,9 @@ async function main() {if (offset) warnings.push(`object is off ground/centre: it needs a translation of ${JSON.stringify(offset)} m to stand on y=0 centred on the Y axis; exported as authored — fix the source (the contract gate reports this too)`);stripTextures(group, warnings);- const census = objectCensus(THREE, group);- census.placement_offset = offset;- census.instanced_meshes_baked = bakedInstances;- census.selfcheck_ran = selfchecked;- census.tick_present = tickPresent;+ // what only the export knows; the object's measurements are read off the GLB (spatial/measure.py)+ const census = { placement_offset: offset, instanced_meshes_baked: bakedInstances,+ selfcheck_ran: selfchecked, tick_present: tickPresent };let unnamed = 0;group.traverse((o) => {if ((o.isMesh || o.isInstancedMesh) && !o.name) unnamed += 1;@@ -222,8 +220,7 @@ async function main() {fs.mkdirSync(path.dirname(args.census), { recursive: true });fs.writeFileSync(args.census, JSON.stringify(census, null, 2));- finish({ ok: true, glb: args.out, census: args.census, duration_ms: Date.now() - t0,- tri_count: census.tri_count, parts: census.parts.length, warnings });+ finish({ ok: true, glb: args.out, census: args.census, duration_ms: Date.now() - t0, warnings });}main().catch((err) => {diff --git a/harness/runtime_js/lib/census.mjs b/harness/runtime_js/lib/census.mjsindex f13e7d6e..8522f549 100644--- a/harness/runtime_js/lib/census.mjs+++ b/harness/runtime_js/lib/census.mjs@@ -1,7 +1,9 @@-// Census of a THREE.Object3D tree: per-part triangle counts, world bboxes,-// materials, NaN checks (with the offending mesh/part named). Pure three.js math — usable in node and browser.+// Geometry checks on a THREE.Object3D tree: triangle counts, world boxes and the first mesh+// with NaN/Infinity positions (the offending mesh and part named). Pure three.js math — node and+// browser. What the exported object measures (parts, tris, boxes, materials) is spatial/measure.py's+// job, read off the GLB.//-// import { objectCensus, triangleCount, worldBox } from './census.mjs';+// import { findNonFinitePositions, geometryTriangles, worldBox } from './census.mjs';/** Triangles of one mesh geometry (index or non-indexed), honouring draw range. */export function geometryTriangles(geometry) {@@ -15,17 +17,6 @@ function isMeshLike(obj) {return !!(obj.isMesh || obj.isSkinnedMesh || obj.isInstancedMesh);}-/** Triangle count of a subtree (InstancedMesh multiplied by its instance count). */-export function triangleCount(root) {- let n = 0;- root.traverseVisible((o) => {- if (!isMeshLike(o)) return;- const tris = geometryTriangles(o.geometry);- n += o.isInstancedMesh ? tris * o.count : tris;- });- return n;-}-/** World-space AABB of a subtree as [[minx,miny,minz],[maxx,maxy,maxz]] or null if empty. */export function worldBox(THREE, root) {root.updateWorldMatrix(true, true);@@ -70,69 +61,3 @@ export function findNonFinitePositions(root) {};return visit(root, []);}--function materialSummary(m) {- const out = { name: m.name || '', type: m.type };- if (m.color && m.color.isColor) out.color = '#' + m.color.getHexString();- if (typeof m.roughness === 'number') out.roughness = +m.roughness.toFixed(3);- if (typeof m.metalness === 'number') out.metalness = +m.metalness.toFixed(3);- if (m.transparent) out.opacity = +(m.opacity ?? 1).toFixed(3);- if (m.map) out.map = true;- return out;-}--/** Unique materials used under `root` (by object identity). */-export function materialsOf(root) {- const seen = new Set();- const out = [];- root.traverse((o) => {- if (!isMeshLike(o) || !o.material) return;- const mats = Array.isArray(o.material) ? o.material : [o.material];- for (const m of mats) {- if (!m || seen.has(m)) continue;- seen.add(m);- out.push(materialSummary(m));- }- });- return out;-}--function namedDescendants(part) {- const names = [];- part.traverse((o) => {- if (o !== part && o.name) names.push(o.name);- });- return names;-}--/**- * Census of an object group: each direct child is a "part".- * @returns {{object_name, parts, tri_count, bbox, materials, n_meshes}}- */-export function objectCensus(THREE, group) {- group.updateWorldMatrix(true, true);- const parts = group.children.map((child) => {- const box = worldBox(THREE, child);- return {- name: child.name || '',- type: child.type,- tri_count: triangleCount(child),- bbox_min: box ? box[0] : null,- bbox_max: box ? box[1] : null,- children: namedDescendants(child),- };- });- let nMeshes = 0;- group.traverse((o) => {- if (isMeshLike(o)) nMeshes += 1;- });- const box = worldBox(THREE, group);- return {- object_name: group.name || '',- parts,- tri_count: triangleCount(group),- bbox: box ? { min: box[0], max: box[1] } : null,- materials: materialsOf(group),- n_meshes: nMeshes,- };-}diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.pyindex e77cfc93..4b7a9e54 100644--- a/harness/tests/threejs_render/test_build.py+++ b/harness/tests/threejs_render/test_build.py@@ -10,31 +10,36 @@ import pytestimport trimeshfrom codeverse3d.languages.threejs import ThreeJsRuntime+from codeverse3d.spatial.measure import measure_glbfrom codeverse3d.workspace import Workspacepytestmark = pytest.mark.node+def _glb_json(glb: str) -> dict:+ raw = Path(glb).read_bytes()+ return json.loads(raw[20:20 + int.from_bytes(raw[12:16], "little")])++def test_build_stool_glb_and_census(stool_ws: Workspace):rt = ThreeJsRuntime()res = rt.build(stool_ws)assert res.ok, (res.error_type, res.error_message, res.stderr_tail)assert Path(res.glb_path).is_file() and Path(res.glb_path).stat().st_size > 1000assert (stool_ws.artifacts / "build.json").is_file()- c = res.census- assert c["object_name"] == "Stool"- assert [p["name"] for p in c["parts"]] == ["Seat", "Legs", "Stretchers"]- assert c["tri_count"] > 500 and c["n_meshes"] == 9+ c = res.census # what only the export knows; the object itself is measured off the GLBassert c["tick_present"] is Trueassert c["placement_offset"] is Noneassert c["instanced_meshes_baked"] == 0 and c["selfcheck_ran"] is Falseassert c["unnamed_meshes"] == 0- assert "Leg_LB" in c["parts"][1]["children"]- assert len(c["materials"]) == 3 # seat + legs + stretchers (distinct objects)+ m = measure_glb(res.glb_path)+ assert sorted(p.name for p in m.parts) == ["Legs", "Seat", "Stretchers"] and m.tri_count > 500+ assert len(_glb_json(res.glb_path)["materials"]) == 3 # seat + legs + stretchers (distinct objects)# the GLB carries named nodes per part and the bbox matches the authored sizesscene = trimesh.load(res.glb_path, force="scene")names = set(scene.graph.nodes)assert {"Stool", "Seat", "Legs", "Stretchers", "Leg_LB", "Leg_RF"} <= names+ assert len(scene.graph.nodes_geometry) == 9lo, hi = scene.boundsassert np.allclose(lo, [-0.17, 0.0, -0.17], atol=2e-3)assert np.allclose(hi, [0.17, 0.45, 0.17], atol=2e-3)@@ -114,9 +119,8 @@ def test_build_per_plan_placement_passes_contract_even_when_union_is_off_centre(def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace):"""InstancedMesh must not export as EXT_mesh_gpu_instancing (trimesh ignores it):- measure/connectivity must see every instance exactly like the census does."""+ measure/connectivity must see every instance as its own named mesh."""from codeverse3d.spatial.connectivity import check_connectivity- from codeverse3d.spatial.measure import measure_glb(stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name = 'Fence';\n"@@ -129,20 +133,19 @@ def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace):" return g; }\n")res = ThreeJsRuntime().build(stool_ws)assert res.ok, res.error_message- census = res.census- assert census["instanced_meshes_baked"] == 1 and census["tri_count"] == 132 and census["n_meshes"] == 11- assert [p["name"] for p in census["parts"]] == ["Posts", "Rail"]- assert "Posts_0" in census["parts"][0]["children"] and "Posts_9" in census["parts"][0]["children"]- raw = Path(res.glb_path).read_bytes()- header = json.loads(raw[20:20 + int.from_bytes(raw[12:16], "little")])+ assert res.census["instanced_meshes_baked"] == 1+ header = _glb_json(res.glb_path)assert "EXT_mesh_gpu_instancing" not in (header.get("extensionsUsed") or [])+ assert len(header["materials"]) == 3 # base + two instance colours+ scene = trimesh.load(res.glb_path, force="scene")+ assert {"Posts_0", "Posts_9", "Rail"} <= set(scene.graph.nodes) and len(scene.graph.nodes_geometry) == 11m = measure_glb(res.glb_path)- assert m.tri_count == census["tri_count"] and abs(m.ground_gap_m) < 1e-3+ assert sorted(p.name for p in m.parts) == ["Posts", "Rail"]+ assert m.tri_count == 132 and abs(m.ground_gap_m) < 1e-3posts = next(p for p in m.parts if p.name == "Posts")- assert np.allclose(posts.bbox_min, census["parts"][0]["bbox_min"], atol=1e-3)- assert np.allclose(posts.bbox_max, census["parts"][0]["bbox_max"], atol=1e-3)+ assert np.allclose(posts.bbox_min, [-2.275, 0.0, -0.025], atol=1e-3)+ assert np.allclose(posts.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)assert posts.tri_count == 120- assert len(census["materials"]) == 3 # base + two instance coloursassert check_connectivity(res.glb_path).passed@@ -185,4 +188,4 @@ def test_build_async_build_and_texture_strip(stool_ws: Workspace):res = ThreeJsRuntime().build(stool_ws)assert res.ok, res.error_messageassert any("texture" in w for w in res.census["warnings"])- assert res.census["object_name"] == "Async"+ assert "Async" in trimesh.load(res.glb_path, force="scene").graph.nodes # the awaited group was exporteddiff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex e3b81d72..0bdcb6c8 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -18,9 +18,10 @@ def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path:rt = runtime_js_dir()res = run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--out", "artifacts/o.glb", "--census", "artifacts/c.json"], three_hook=True, timeout_s=60)rec = res.last_json- assert rec["ok"] and rec["parts"] == 3 and (stool_ws.root / "artifacts/o.glb").is_file()+ assert rec["ok"] and (stool_ws.root / "artifacts/o.glb").is_file()census = json.loads((stool_ws.root / "artifacts/c.json").read_text())- assert set(census) >= {"object_name", "parts", "tri_count", "bbox", "materials", "placement_offset", "warnings", "tick_present"}+ assert set(census) == {"placement_offset", "instanced_meshes_baked", "selfcheck_ran", "tick_present",+ "unnamed_meshes", "warnings", "glb_bytes", "three_revision"}assert census["three_revision"] == "182"# error path: unknown entrywith pytest.raises(NodeError) as ei: