Official Codebase of 3DCodeVerse
Python
scene: settle — deterministically seat floating/sunken assets at boot
gaoypengd161877dda7e
diff --git a/harness/codeverse/spatial/probes.py b/harness/codeverse/spatial/probes.pyindex 239c4459..b2a8e188 100644--- a/harness/codeverse/spatial/probes.py+++ b/harness/codeverse/spatial/probes.py@@ -9,6 +9,7 @@ Both drive the node host (``runtime_js/*.mjs``) via ``run_scene_script``.from __future__ import annotationsimport json+import osimport timefrom typing import Any@@ -68,10 +69,10 @@ def probe_scene(ws: Workspace, *, timeout_s: float = 60.0, write_census: bool =census: dict[str, Any] = {}out_json = ws.artifacts / "scene_probe.json"try:- res = run_scene_script(- "probe_scene.mjs", ["--ws", str(ws.root), "--out", str(out_json), "--timeout-ms", str(int(timeout_s * 1000))],- timeout_s=timeout_s + 20,- )+ args = ["--ws", str(ws.root), "--out", str(out_json), "--timeout-ms", str(int(timeout_s * 1000))]+ if os.environ.get("CV3D_SETTLE") == "0": # A/B switch for the boot-time auto-seat+ args.append("--no-settle")+ res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)except SceneRenderError as e:findings.append(_f(gate, Severity.ERROR, f"scene probe could not run: {e}", target="src/scene.js",hint="this is a harness/driver failure, not your code; retry or report", harness_failure=True))diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.pyindex 2321f407..d28eb8c0 100644--- a/harness/codeverse/spatial/render_scene.py+++ b/harness/codeverse/spatial/render_scene.py@@ -140,6 +140,8 @@ def render_scene(args += ["--bounds", _bounds_json(bounds)]tmo = timeout_s or settings.limits.render_timeout_sargs += ["--timeout-ms", str(int(tmo * 1000))]+ if os.environ.get("CV3D_SETTLE") == "0": # A/B switch for the boot-time auto-seat+ args.append("--no-settle")driver_error = ""try:res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjsindex 985785d3..8cf5e4ea 100644--- a/harness/runtime_js/lib/host_page.mjs+++ b/harness/runtime_js/lib/host_page.mjs@@ -55,7 +55,7 @@ export function requestFailureLine(url, base, hasResponse, errorText) {* Open the host for workspace `wsRoot`.* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}*/-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0 } = {}) {+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true } = {}) {wsRoot = path.resolve(wsRoot);if (!fs.existsSync(path.join(wsRoot, sceneRel))) {throw new Error(`missing ${sceneRel} in workspace ${wsRoot}`);@@ -101,7 +101,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'autoawait page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });const boot = await page.evaluate((o) => window.__c3v.boot(o),- { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs },+ { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs, settle },);const close = async () => {// page first, then release: a SHARED browser (connect-first reuse) must getdiff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjsindex 7f4145f0..e498504f 100644--- a/harness/runtime_js/lib/host_placement.mjs+++ b/harness/runtime_js/lib/host_placement.mjs@@ -420,3 +420,90 @@ export function placementTable(scene, THREE, opts = {}) {ground_y: groundY, notes, duration_ms: Date.now() - t0,};}++// ============================================================================ settle+// Deterministic auto-seat, added 2026-08-30. Measured on the 48-run scene batteries:+// 38 sunken + 22 floating gate ERRORS were still present in FINAL rounds — the refine+// agent is handed the exact "lower X by 0.23 m" hint and demonstrably does not apply+// it reliably. The measurement is deterministic, so the FIX can be too: after boot+// (before any census or render) every clearly mis-seated asset is translated onto its+// support. The zone code keeps its wrong constant; every frame anyone sees or judges+// is seated. The moves are returned and carried in the census, so nothing is silent.+//+// Deliberately conservative, mirroring the python gate's exemptions+// (codeverse/spatial/scene_placement.py — keep the two in sync):+// · exempt assets (free / backdrop / enclosure / instanced) are never touched+// · a foot in the water is a boat / jetty: never touched+// · BURIED-ok names (basin, trench, pool…) are below ground by definition+// · PARTIAL-ok names (rocks, posts, trees…) may bury half their height; only a+// burial past 3/4 height is pulled up, and only to the 40 % embed that reads+// as "grown in", never to the surface+// · a floating asset that TOUCHES another asset may be mounted on it: skipped+// · normal sunken assets keep a 4 cm embed (the zone recipes ask for 3-5 cm)+const SETTLE_EMBED_M = 0.04;+const SETTLE_PARTIAL_FRAC = 0.40;+const SETTLE_MAX_MOVE_M = 6;+const SETTLE_SEAT_EPS_M = 0.005;+const BURIED_OK_RE = /\b(basin|bed|canal|cave|cellar|crater|ditch|drain|foundations?|graves?|gutter|holes?|lakebed|moat|pits?|pools?|riverbed|trench(es)?|tunnels?|wells?)\b/i;+const PARTIAL_OK_RE = /\b(boulders?|bridges?|bush(es)?|cliffs?|docks?|dunes?|fences?|flowers?|grass|hills?|jett(y|ies)|logs?|mounds?|outcrops?|pebbles?|piers?|piles?|plants?|poles?|posts?|reeds?|rocks?|roots?|shrubs?|stakes?|stones?|stumps?|trees?|trunks?|tufts?)\b/i;++/** Measure every placed asset once, then translate the clearly mis-seated ones onto+ * their support. Returns `{count, moves}`; mutates object positions (world-space dy+ * applied through each parent's frame) and leaves matrices updated. */+export function settleScene(scene, THREE, opts = {}) {+ const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;+ const notes = [];+ scene.updateMatrixWorld(true);+ const indices = indexMeshes(scene, notes);+ const { assets } = collectAssets(scene, indices, opts.contentBox || null);+ const checked = assets.filter((a) => !a.exempt);+ for (const a of checked) { a.meshSet = new Set(a.meshes); }+ const meshOwner = new Map();+ for (const a of assets) for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name);+ const owner = (mesh) => meshOwner.get(mesh) || nearestName(mesh);+ const moves = [];+ const t0 = Date.now();+ for (const a of checked) {+ if (Date.now() - t0 > TIME_BUDGET_MS) break;+ const cols = footColumns(a);+ if (!cols.length) continue;+ let best = null, sunk = null, water = false;+ for (const col of cols) {+ const r = probeColumn(a, col, indices, owner, groundY);+ if (r.gap !== null && (!best || r.gap < best.gap)) best = r;+ if (r.sunk > 0 && (!sunk || r.sunk > sunk.sunk)) sunk = r;+ if (r.water) water = true;+ }+ if (water) continue;+ const name = spaced(a.name);+ const height = Math.max(a.max[1] - a.min[1], 1e-6);+ let dy = 0, why = '';+ if (sunk && sunk.sunk > 0) {+ if (BURIED_OK_RE.test(name)) continue;+ const frac = sunk.sunk / height;+ if (PARTIAL_OK_RE.test(name)) {+ if (frac <= 0.75) continue; // grown / driven in: fine+ dy = sunk.sunk - SETTLE_PARTIAL_FRAC * height; // pull up to a 40 % embed+ why = 'sunken_partial';+ } else if (sunk.sunk > SUNK_M) {+ dy = sunk.sunk - SETTLE_EMBED_M; // reseat with a 4 cm embed+ why = 'sunken';+ } else { continue; }+ } else if (best && best.gap !== null && best.gap > FLOATING_M) {+ // mounted on a neighbour? touching anything → leave it alone+ if (checked.some((b) => b !== a && touches(a, b, CONTACT_TOL_M))) continue;+ dy = -(best.gap - SETTLE_SEAT_EPS_M); // drop onto the support+ why = 'floating';+ } else { continue; }+ if (!Number.isFinite(dy) || Math.abs(dy) < 1e-4 || Math.abs(dy) > Math.max(SETTLE_MAX_MOVE_M, height)) continue;+ const obj = a.obj, parent = obj.parent || scene;+ const w = new THREE.Vector3();+ obj.getWorldPosition(w);+ const delta = parent.worldToLocal(new THREE.Vector3(w.x, w.y + dy, w.z))+ .sub(parent.worldToLocal(w.clone()));+ obj.position.add(delta);+ moves.push({ name: a.name, zone: a.zone, dy_m: Math.round(dy * 1000) / 1000, why });+ }+ if (moves.length) scene.updateMatrixWorld(true);+ return { count: moves.length, moves };+}diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex ce0b53ce..3190034e 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -15,7 +15,7 @@import * as THREE from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { sceneCensus } from './host_census.mjs';-import { placementTable } from './host_placement.mjs';+import { placementTable, settleScene } from './host_placement.mjs';import { frameStats, nearGeometry } from './host_metrics.mjs';import { frameCoverage } from './host_coverage.mjs';import { installShaderErrorHook } from './host_shader_errors.mjs';@@ -46,6 +46,7 @@ const state = {bootInfo: null,contentBox: null,fullBox: null,+ settleInfo: null,};/**@@ -224,6 +225,21 @@ async function boot(opts) {runUpdate(0, 0);state.simTime = 0;state.scene.updateMatrixWorld(true);++ // settle (2026-08-30): deterministically seat floating / sunken assets before any+ // census or render — the placement gate measured the errors for two batteries and+ // the refine agent left 38 sunken + 22 floating standing in final rounds. Runs on+ // every boot (probe and render see the same seated scene); --no-settle disables.+ if (opts.settle !== false) {+ info.stage = 'settle';+ try {+ const c0 = sceneCensus(state.scene, THREE);+ state.settleInfo = settleScene(state.scene, THREE, { groundY: c0.ground_y, contentBox: c0.content_bbox });+ } catch (e) {+ state.settleInfo = { count: 0, moves: [], error: String((e && e.message) || e).slice(0, 300) };+ }+ info.settled = state.settleInfo.count;+ }state.booted = true;info.ok = cameras.length > 0;info.stage = 'ready';@@ -405,6 +421,7 @@ function placement() {function census() {const c = sceneCensus(state.scene, THREE);c.glb_assets = glbUsage(state.scene);+ if (state.settleInfo) c.settle = state.settleInfo;state.contentBox = c.content_bbox;state.fullBox = c.bbox;c.cameras = state.cameras.length;diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjsindex 5393a0d3..c335a385 100644--- a/harness/runtime_js/probe_scene.mjs+++ b/harness/runtime_js/probe_scene.mjs@@ -56,6 +56,7 @@ async function main() {host = await openHost(args.ws, {width: 320, height: 180, gpu: args.gpu, sceneRel: args.scene.replace(/^\.?\//, ''),createSceneTimeoutMs: createTimeoutMs(args['create-timeout-ms'], timeoutMs),+ settle: !args['no-settle'],});} catch (e) {return fail(`host failed: ${e.message}`);diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjsindex c37b5947..00c752e0 100644--- a/harness/runtime_js/render_scene.mjs+++ b/harness/runtime_js/render_scene.mjs@@ -53,6 +53,7 @@ async function main() {host = await openHost(args.ws, {width, height, gpu: args.gpu, logDepth: args['log-depth'],createSceneTimeoutMs: createTimeoutMs(args['create-timeout-ms'], timeoutMs),+ settle: !args['no-settle'],});} catch (e) {return fail(`host failed: ${e.message}`);diff --git a/harness/tests/scene_runtime/test_placement_census.py b/harness/tests/scene_runtime/test_placement_census.pyindex 006f8a50..a6d2aad4 100644--- a/harness/tests/scene_runtime/test_placement_census.py+++ b/harness/tests/scene_runtime/test_placement_census.py@@ -102,3 +102,52 @@ def test_no_false_positives_on_legitimate_placements(table):rock = _row(table, "Rock")assert rock["sunk_into"] == "Ground" and 0.3 < rock["sunk_m"] < 0.5 and not rock["floating"]+++SETTLE_JS = """+import * as THREE from 'three';+import { settleScene, placementTable } from './lib/host_placement.mjs';+const mat = new THREE.MeshStandardMaterial();+const box = (name, sx, sy, sz, x, y, z) => { const m = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat); m.name = name; m.position.set(x, y + sy / 2, z); return m; };+const scene = new THREE.Scene();+const env = new THREE.Group(); env.name = 'Environment'; scene.add(env);+const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 64, 64), mat); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2; env.add(ground);+const pond = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), mat); pond.rotation.x = -Math.PI / 2; pond.position.set(-20, 0.2, -20);+const pondGroup = new THREE.Group(); pondGroup.name = 'PondWater'; pondGroup.add(pond); env.add(pondGroup);+const zone = new THREE.Group(); zone.name = 'Yard'; scene.add(zone);+zone.add(box('Lantern', 0.4, 0.6, 0.4, 5, 0.3, 0)); // floating 0.3, touches nothing+zone.add(box('Anvil', 1, 1, 1, -5, -0.5, 0)); // sunken 0.5 into Ground+const bird = box('Bird', 0.3, 0.2, 0.3, 0, 4, 5); bird.userData.placement = 'free'; zone.add(bird);+zone.add(box('Boat', 2, 0.6, 0.8, -20, 0.0, -20)); // foot at pond level: on water+const rock = box('Rock', 1, 1.2, 1, 8, -0.6, -8); zone.add(rock); // half-buried rock: partial-ok, frac 0.5 <= 0.75+const shelf = box('Shelf', 1, 0.1, 0.4, 12, 1.2, 0); // floating but TOUCHING the wall+const wall = box('Wall', 0.2, 2.5, 3, 12.5, 0, 0); zone.add(wall); zone.add(shelf);+shelf.position.x = 12.35; // AABBs meet the wall's+scene.updateMatrixWorld(true);+const settle = settleScene(scene, THREE, { groundY: 0 });+const after = placementTable(scene, THREE, { groundY: 0 });+console.log(JSON.stringify({ settle, after: { assets: after.assets.map((a) => ({ name: a.name, gap: a.ground_gap_m, sunk: a.sunk_m, supported: a.supported, exempt: a.exempt })) } }));+"""++[email protected](scope="module")+def settled() -> dict:+ return run_node_json(SETTLE_JS.replace("'./lib/", f"'{RUNTIME_JS}/lib/"))+++def test_settle_seats_floating_and_sunken_and_reports_the_moves(settled):+ moves = {m["name"]: m for m in settled["settle"]["moves"]}+ assert moves["Lantern"]["why"] == "floating" and moves["Lantern"]["dy_m"] == pytest.approx(-0.295, abs=5e-3)+ assert moves["Anvil"]["why"] == "sunken" and moves["Anvil"]["dy_m"] == pytest.approx(0.46, abs=5e-3)+ after = {a["name"]: a for a in settled["after"]["assets"]}+ assert after["Lantern"]["supported"] and after["Lantern"]["gap"] == pytest.approx(0.005, abs=3e-3)+ assert after["Anvil"]["sunk"] == pytest.approx(0.04, abs=5e-3) # reseated with the 4 cm embed+++def test_settle_leaves_exempt_water_partial_and_mounted_alone(settled):+ touched = {m["name"] for m in settled["settle"]["moves"]}+ assert touched == {"Lantern", "Anvil"}, touched+ after = {a["name"]: a for a in settled["after"]["assets"]}+ assert after["Bird"]["exempt"] == "free" # tagged free: untouched+ assert after["Boat"]["supported"] # on water: untouched+ assert after["Rock"]["sunk"] == pytest.approx(0.6, abs=5e-3) # half-buried rock stays half-buried