3D engine that AI agents drive
Merge origin/main into feat/imported-topology
Nguyen Xuan Ancbcb08e3f647
diff --cc CHANGELOG.mdindex f421c3ac,d1a18688..9a353fe8--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -2,7 -2,12 +2,13 @@@## Unreleased+- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.+ - Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.+ - Add six whole-mesh modifiers as edits and stack nodes (part of issue #42): `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform` (twist, bend, taper, stretch) and `cast` (sphere). Each has Blender cases in `tests/fixtures/blender/` that match with no listed difference, `triangulate` and `edge_split` check their output size before building it, and their fields are described in `scene_capabilities` `meshModifiers` so the tool schemas grow by one compact entry. Left for later slices: screw, skin, wireframe, lattice, curve, hook, wave, shrinkwrap, weighted normal, smooth by angle and the other cast shapes. `npm run parity` now prints the modifier coverage.++ - Add `curve` and `text` geometry (part of issue #45). `curve` sweeps a round or custom profile along a cubic Bezier chain with explicit or automatic handles, a taper along the length and flat caps; `text` extrudes the outlines of the bundled DejaVu Sans (printable ASCII, 20 KB, loaded on demand with its own `text` module and never in an entry) or of a font table added with `registerAgentSceneFont`, with size, depth, alignment, lines and curve resolution. Volume, area and bounds match Blender 5.2 to 2e-5 for two Bezier curves and for a letter and a word set in the same font. Recipes stay plain JSON with bounded, validated fields and vertex estimates checked before generation. The MCP schemas gain two strict entries in the geometry list (1.4 KB of the 190 KB across all tools; not offered as mesh bases or cutters); field types and limits live in `scene_capabilities` under `curveText`, and the MCP takes no font file or URL. The DejaVu licence is in `THIRD-PARTY-NOTICES.md`. Metaballs and NURBS surfaces are recorded as out of scope in `docs/parity.md`. Not done: a suite task in `bench/agent-modeling`, kerning, bevelled text, non-ASCII glyphs in the bundled font.++ - Add frustum culling, levels of detail and live adaptive resolution (part of issue #37). `Renderer67` tests each instance of a batch against the view frustum with the geometry's bounding sphere and draws only the visible ones (on by default, `culling: false` turns it off; skinned, morphed, swaying, fire, smoke, water, assembly and blended batches and the shadow passes are not culled). A part's `lods`, the array from `generateGeometryLods`, makes each instance pick a level by pixel error (`lodPixelError`, default 1). Selection is a pure function of the camera and the matrices, so a seek draws the same frame. `createGpuTimer` and `AdaptiveResolution` in `src/adaptive-quality.js` give live viewers GPU timing and a resolution scale with a minimum; an export can not build one, and `src/main.js` uses it only outside `export=1`. New `large-outdoor` scene in `bench/runtime` with ablations: 1.55 ms against 8.41 ms without culling and 6.0 ms for three.js on an RTX 3060, 517 ms against 4,428 ms and 944 ms on SwiftShader. Core grows 1,845 bytes gzip (budget 81,500). Recipes cannot declare `lods` yet. See `docs/culling-lod.md`.- Add relations between parts (part of issue #44, no new tool): a mesh node takes `relations` (`attach`, `gap`, `flush`, `align`, `centered`, up to 8) against other mesh nodes, or against the faces of one carrying a mesh tag (`region`). They work on world bounds, are solved after geometry exists and again on every `scene_apply`, so one edit to a body keeps the parts that sit against it. Unknown IDs and tags, two relations on one axis and cycles (a part waiting on its own child included) are rejected with the next action; solving is deterministic and independent of node order. The code loads on demand (`relations`). The schema carries only a generic `relations` list (597 bytes over `scene_create` and `scene_apply` together); the kinds and fields are in `scene_capabilities` `relations`, and the engine validates them. Measured on Sonnet (3 runs each), relations did not cut tool calls or errors: the kettle resize took 3.3 calls against 3.0, and a 12-part desk with three inspected resizes took 8 against 8, with 13% fewer output tokens (3,833 against 4,403) and the same cost and pass rate. The suite gains `kettle-resize`, `desk-resize` and their plain twins, and `touches` and `centreAt` checks.- Add render passes, depth of field and camera motion blur (issue #54, first slice). Render jobs of kind `image` or `stills` take `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) and write each as a raw, unantialiased PNG beside the lit image (`render-depth.png`, `frame-3-objectId.png`); depth is 16 bits over 100 m in red and green, object IDs are 24 bits with the part names in the job metrics. In code, `renderer.render({ pass })` draws a pass into its own non-multisampled target. `effects.depthOfField` (`blur`, `focusDistance`) and `effects.motionBlur` (`shutter`) are new recipe effects: fixed sample patterns and a per-pixel rotation from the pixel position, so a seek to a frame repeats the same pixels. They live in the new `67js/addons/camera-effects` entry; the preview installs it, and the core renderer only gains a stage hook and the pass branch (a compiled-out shader feature). Motion blur follows camera tracks only, sampled from time at `motion.start + elapsed - shutter`. Measured on SwiftShader through MCP (`npm run smoke:render-passes`): 8 stills with 5 passes each, then four seeks, all byte-identical to the same frame in the sequence. Temporal anti-aliasing, accumulation and the compositing graph of #54 are not part of this slice.diff --cc scripts/mcp-server.mjsindex a23937be,429cb9a2..824ee9bd--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@@ -576,9 -593,9 +593,9 @@@ export function createAgentMcpServer(ruregister('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));- register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));- register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));+ register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Also imported asset parts (mesh-0). Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));+ register('mesh_edit', 'Append edits to a recipe mesh geometry or an imported asset part such as mesh-0 (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh, or an imported part such as mesh-0.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));- register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide, set_position, displace, decimate, remesh), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));+ register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (ops and fields: scene_capabilities meshModifiers), evaluated after its edits, each prefix cached. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.'), branch: branchName.optional().describe('Fork: store the result as this branch (up to 8), leaving the scene unchanged.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG, optionally with part labels. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.'), labels: labelsFlag }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);diff --cc src/agent-scene-capabilities.jsindex c52ef207,0e609e02..6db86852--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@@ -75,14 -95,13 +96,20 @@@ export const AGENT_SCENE_CAPABILITIESmaterialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,materialMappings: MATERIAL_MAPPINGS,renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png or frame-N-<pass>.png, raw and unantialiased; opaque and cutout geometry only', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; the job result lists the part names' }),+ curveText: Object.freeze({+ maxCurvePoints: CURVE_TEXT_LIMITS.maxCurvePoints, maxProfilePoints: CURVE_TEXT_LIMITS.maxProfilePoints,+ maxTextCharacters: CURVE_TEXT_LIMITS.maxTextCharacters, maxTextLines: CURVE_TEXT_LIMITS.maxTextLines,+ verticesPerCharacterSegment: CURVE_TEXT_LIMITS.verticesPerCharacterSegment,+ details: CURVE_TEXT_DETAILS,+ }),materialGraph: Object.freeze({ outputs: MATERIAL_GRAPH_OUTPUTS, operators: MATERIAL_GRAPH_OPERATORS, ...MATERIAL_GRAPH_LIMITS, nodes: MATERIAL_GRAPH_NODES }),+ // mesh_edit on an imported GLB part (geometry mesh-<n>, listed by scene_inspect). Edits run in the part's local space+ // (mesh_inspect gives localToWorldScale and localAxesInWorld) on a welded mesh with axis tags and a material tag.+ importedMeshEdits: Object.freeze({+ ...IMPORTED_MESH_EDIT_LIMITS,+ transfer: 'New vertices take skin weights, morph deltas and colours from the nearest original surface point; faces left without UVs read the nearest original UV island. Not supported: mesh_stack, relations, instancing.',+ rejects: 'On a skinned or morphed part an edit farther than maxTransferFraction of the part bounds diagonal from the original surface; booleans on open parts (fill_holes first).',+ }),fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,authoredLook: true, maxPointLights: 8,lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,