3D engine that AI agents drive
Merge remote-tracking branch 'origin/main' into HEAD
Nguyen Xuan Andee1c0304bd4
diff --cc CHANGELOG.mdindex 68e55a23,1802ec53..8c82b3f8--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -2,9 -2,8 +2,11 @@@## Unreleased+- Measure and cut the cost of the MCP tools (issue #65). `node scripts/measure-tool-cost.mjs` reports each tool schema and each typical result in bytes and estimated tokens (3.5 characters a token). The 22 schemas came to 373,388 bytes (about 107,000 tokens) and are now 173,216 (about 49,500): recipe geometries and asset recipes point to `mesh_edit`, `mesh_stack` and `scene_create` for the mesh edit, stack and motion detail instead of repeating about 45 KB and 35 KB in each tool, and vectors, colours, quaternions and IDs are shared `$ref` definitions. The backend still validates every field. `tests/tool-cost.test.js` fails when the schema total, one tool's schema or a typical result passes `bench/tool-cost-budgets.json`. A small mesh change is 187 bytes as `mesh_edit` against 1,254 as dispose plus a whole-recipe `scene_create` on a 7-node recipe.+- Return diagnostics that name the next action (issue #66). `mesh_inspect` lint adds `intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part` and `asymmetric` warnings from the BVH, with face budgets and a `skippedChecks` list; they never turn `ok` off and the agent modeling suite does not grade them. `scene_inspect` adds `diagnostics` for material fields the renderer ignores, blended transmission and unused materials or geometries, and asset inspection adds decoder warnings (accepted but not drawn features), skinned meshes with no joints, joints with no skin and assets with no clips. Error messages now list allowed fields, known IDs and the next call: a missing session (the largest group, 21 of 68 recorded errors) names the active session or says to call `scene_create`, and page errors no longer carry the bundle stack. `tests/tool-errors.test.js` walks 27 error paths and rejects a message with no next action.++ - Add authored rigs (#46): a recipe `armatures` list (bones with a name, parent, head and tail, or a `humanoid` or `quadruped` preset fitted to a mesh node's bounds, with `landmarks` to move bones), and a `skin` on a mesh node that binds it with automatic weights, plus a `set-armatures` operation. Each bone becomes a recipe node, so keyframed bone rotation and `motion.ik` run through the same paths as imported rigs, and humanoid bones carry the `HUMANOID_BONES` names so `retargetClip` maps them. Weights are the distance to each bone segment with an inverse-fourth-power falloff, the nearest four kept; they depend only on position, so hard-edge seams never open. `scene_inspect` gains `rig`: unweighted vertices, bones with no vertices, and joint axis problems (zero-length bones, straight limb chains, knees that bend backward). `scene_export_glb` writes the bones and a walk clip baked at 30 frames a second from tracks and IK. Add the `rigged-walker` task to the agent modeling suite, with a reference and three failing variants. Blender 5.2 opens the exported walker as 1 armature, 21 bones, 14 meshes with 21 vertex groups each and 1 action of 24 frames; three.js loads 14 skinned meshes and the clip.+ - Load agent scene code on demand: mesh editing, `lathe`/`extrude`/`tube`, material `pattern` and `motion` now sit behind `loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()`), and `createAgentScene` throws an error naming that call when a needed module is missing. A recipe of primitives drops from 141,241 to 73,581 bytes gzip in `scene:agent-scene` (every lazy chunk still totals 145,049). `npm run size` now bundles with code splitting and reports the initial load, plus a `+lazy` row for the total. `npm test` preloads every module. The archive no longer carries 29 docs that the site serves (physics, lighting, terrain and the other addon docs); agent docs stay- Add joint limits, node constraints and drivers to motion (issue #58). Two-bone IK takes `limits` per joint and axis in degrees and `bendToward`; `scene_inspect` `motionIk` now carries `limited` (each pose a limit changed) and `warnings` (`hyperextended`, and `wrong-bend` for a knee or elbow bent the unnatural way, which a wrong pole used to hide behind `reached`). `motion.constraints` adds `copy_location`, `copy_rotation`, `copy_scale`, `limit_location`, `limit_rotation`, `track_to`, `child_of` (with an inverse and an influence blend) and `floor`, and `motion.drivers` sets a node component or material property from a bounded JSON expression over time and other nodes (never run as code). The order is tracks, IK, drivers, constraints, with no state between samples, so a seek equals playing. `copy_rotation`, `limit_rotation`, `track_to`, `child_of` and `floor` match Blender 5.2 world matrices in 8 recorded cases (`tests/fixtures/blender/constraints.json`). Joint limits are also in `67js/addons/skeleton-pose`. The `leg-plant` task joins the agent modeling suite. The expression language is a new small one in `src/motion-expression.js`: the field expressions of the mesh addon were not on `main` yet- Reach Rapier from recipes: a `physics` section (and a `set-physics` operation) puts rigid bodies on node IDs with box, ball, capsule, convex or trimesh colliders fitted to their geometry, joints, gravity and a duration of up to 10 seconds. It is recorded once at 60 steps a second and seeks like `motion`, so a seek back repeats the same frame (checked as identical PNG bytes on SwiftShader through MCP). `scene_inspect` reports per-body final positions and resting times, contacts and sensor enter and leave events. Rapier stays an optional peer, served to the preview from `node_modules` like Manifold, so the MCP server bundle does not grow.diff --cc bench/size/baseline.jsonindex 2e850a56,d5b95cd4..c91043ef--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@@ -14,9 -14,9 +14,9 @@@},"bundles": {"entry:core": {- "min": 269229,- "gzip": 76877,- "brotli": 65768- "min": 268794,- "gzip": 76776,- "brotli": 65546++ "min": 268850,++ "gzip": 76800,++ "brotli": 65580},"entry:model": {"min": 40093,@@@ -64,9 -64,9 +64,9 @@@"brotli": 12998},"entry:mesh": {-- "min": 144153,-- "gzip": 48359,-- "brotli": 41816++ "min": 194667,++ "gzip": 65618,++ "brotli": 55758},"entry:shrinkwrap": {"min": 56188,@@@ -129,14 -129,24 +129,24 @@@"brotli": 762},"entry:agent-scene": {- "min": 419435,- "gzip": 133124,- "brotli": 113067- "min": 183987,- "gzip": 55346,- "brotli": 47801++ "min": 187390,++ "gzip": 56350,++ "brotli": 48715+ },+ "entry:agent-scene+lazy": {- "min": 439633,- "gzip": 143601,- "brotli": 125617++ "min": 471518,++ "gzip": 154805,++ "brotli": 135128},"entry:agent-asset": {- "min": 445545,- "gzip": 140377,- "brotli": 119117- "min": 262033,- "gzip": 79545,- "brotli": 69297++ "min": 267125,++ "gzip": 81113,++ "brotli": 70586+ },+ "entry:agent-asset+lazy": {- "min": 465052,- "gzip": 150260,- "brotli": 131233++ "min": 498593,++ "gzip": 162013,++ "brotli": 141041},"entry:hdri": {"min": 8075,@@@ -154,9 -164,14 +164,14 @@@"brotli": 63362},"scene:agent-scene": {- "min": 518633,- "gzip": 159129,- "brotli": 135030- "min": 282212,- "gzip": 81177,- "brotli": 69763++ "min": 285615,++ "gzip": 82185,++ "brotli": 70742+ },+ "scene:agent-scene+lazy": {- "min": 537858,- "gzip": 169434,- "brotli": 147600++ "min": 569743,++ "gzip": 180642,++ "brotli": 157169}}}diff --cc bench/size/budgets.jsonindex 2536336a,dd3da36c..4b6bde65--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@@ -15,7 -15,7 +15,7 @@@"entry:sculpt": 2500,"entry:surface": 10100,"entry:mesh-query": 15900,- "entry:mesh": 65700,- "entry:mesh": 49400,++ "entry:mesh": 67000,"entry:shrinkwrap": 18300,"entry:surface-attachment": 11800,"entry:physics": 18000,@@@ -28,11 -28,14 +28,14 @@@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 144500,- "entry:agent-asset": 152300,- "entry:agent-scene": 56500,- "entry:agent-scene+lazy": 146500,- "entry:agent-asset": 81200,- "entry:agent-asset+lazy": 153300,++ "entry:agent-scene": 57500,++ "entry:agent-scene+lazy": 158000,++ "entry:agent-asset": 82800,++ "entry:agent-asset+lazy": 165300,"entry:hdri": 3300,"scene:lit-box": 56000,"scene:gltf-box": 75300,- "scene:agent-scene": 170500- "scene:agent-scene": 82900,- "scene:agent-scene+lazy": 172900++ "scene:agent-scene": 83900,++ "scene:agent-scene+lazy": 184300}}diff --cc bench/tool-cost-budgets.jsonindex 1c861c9d,00000000..4436e9d9mode 100644,000000..100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@@ -1,21 -1,0 +1,21 @@@+{+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; was 373388 schema bytes before shared IDs and recipe references",- "schemaTotalBytes": 176000,++ "schemaTotalBytes": 178800,+ "schemaToolBytes": {- "scene_create": 57000,- "scene_apply": 43000,++ "scene_create": 58600,++ "scene_apply": 43500,+ "mesh_edit": 34000,+ "scene_create_asset": 18000,+ "mesh_stack": 11500+ },+ "schemaOtherToolBytes": 4000,+ "resultBytes": {+ "scene_capabilities": 3000,+ "scene_create": 1400,+ "scene_inspect": 1400,+ "mesh_inspect": 1200,+ "mesh_edit": 2400,+ "scene_apply": 200,+ "scene_export_recipe": 2800+ }+}diff --cc scripts/mcp-server.mjsindex 47437a21,9081882a..0852b721--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@@ -417,9 -419,25 +423,29 @@@ const physics = z.strictObject(bodies: z.array(physicsBody).min(1).max(64),joints: z.array(physicsJoint).max(64).optional().describe('Joint bodies are the node IDs of physics bodies.'),}).describe('Rigid-body physics recorded offline with Rapier at 60 steps a second, then played back by time like motion: scene_look and scene_review motionTime seek into the recording, so a seek back shows the identical frame. Bodies are recipe nodes; scene_inspect reports contacts, sensor events and resting state as numbers. Needs the optional peer dependency @dimforge/rapier3d-compat. A node cannot have a physics body and a motion translation or rotation track.');+// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes+// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.+const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields.');+ const boneRecord = z.strictObject({+ name: z.string().min(1).max(64).describe('Unique within the armature. Humanoid rigs use the canonical names (hips, spine, chest, neck, head, leftUpperArm, leftLowerArm, leftHand, leftUpperLeg, leftLowerLeg, leftFoot, leftToes, and right...) so retarget works.'),+ parent: z.string().min(1).max(64).nullable().optional().describe('Parent bone name, or null for a root bone.'),+ head: vector3.describe('Rest position of the joint in armature space.'),+ tail: vector3.optional().describe('Where the bone ends. Defaults to the mean of its children, so give it on leaf bones.'),+ });+ const armature = z.strictObject({+ id: identifier,+ parent: identifier.nullable().optional().describe('Node the armature hangs from.'),+ translation: vector3.optional(), rotation: quaternion.optional(),+ prefix: z.string().max(64).optional().describe('Prepended to each bone node ID, for a second character or a clash with another node.'),+ preset: z.enum(['humanoid', 'quadruped']).optional().describe('Places bones from fit. A humanoid faces +Z with Y up; its knees sit slightly forward of the leg line and its elbows slightly behind, so poleless two-bone IK bends the right way. A quadruped lies along Z.'),+ fit: z.strictObject({+ node: identifier.optional().describe('A mesh node whose bounds size the preset.'),+ bounds: z.strictObject({ min: vector3, max: vector3 }).optional().describe('Or explicit bounds in armature space.'),+ landmarks: z.record(z.string(), vector3).optional().describe('Move a bone head by bone name, or its tail as <name>Tail, for arms held out or an odd shape.'),+ }).optional(),+ bones: z.array(boneRecord).min(1).max(128).optional().describe('Explicit bones, instead of a preset.'),+ }).describe('A skeleton. Each bone becomes a recipe node named after it (parented like the bones, rotating about its head), so motion tracks, motion.ik and set-node address bones by name. Mesh nodes bind with skin. scene_inspect rig lists unweighted vertices, bones with no vertices and joint axis problems.');++const armaturesReference = z.array(z.record(z.string(), z.unknown())).max(16).describe('The same array as recipe.armatures in scene_create: id, parent, preset, fit, bones. Read that tool for the fields.');const recipe = z.strictObject({format: z.literal('67js.scene'),schemaVersion: z.literal(1),@@@ -454,7 -473,8 +481,8 @@@ const operation = z.discriminatedUnion(z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),- z.strictObject({ type: z.literal('set-motion'), motion: motion.nullable() }),- z.strictObject({ type: z.literal('set-armatures'), armatures: z.array(armature).max(16).nullable() }),+ z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),++ z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),z.strictObject({ type: z.literal('set-physics'), physics: physics.nullable() }),z.strictObject({ type: z.literal('set-environment'), environment }),z.strictObject({ type: z.literal('set-effects'), effects }),diff --cc src/agent-asset.jsindex 99059fda,eeb1f921..fa838f22--- a/src/agent-asset.js+++ b/src/agent-asset.js@@@ -563,20 -565,9 +566,20 @@@ export function createAgentAssetScene(a}/** scene_inspect's motionIk: how each solver fares across the clip, from a sampler that leaves the published pose alone. */+ function diagnosticsReport() {+ const diagnostics = assetDiagnostics({+ assetId: canonicalAssetId,+ warnings: asset.warnings,+ skinnedParts: records.filter(record => record.source.skin).length,+ jointCount: [...sourceNodes.values()].filter(node => node.joint).length,+ clipCount: asset.animations.length,+ });+ return diagnostics.length ? { diagnostics } : {};+ }+function motionIkReport() {if (!recipe.motion?.ik?.length) return {};- const sweeper = compileAgentMotion(recipe.motion, motionRecipe(recipe));+ const sweeper = agentMotion.compileAgentMotion(recipe.motion, motionRecipe(recipe));return {motionIk: sweeper.sweepIk(time => stagedNodePoses(recipe.animation, [...trackOverrides(recipe.nodeOverrides, sweeper.sample(time)).values()])),};diff --cc src/agent-scene.jsindex 564aa116,f27dade9..f0e1274f--- a/src/agent-scene.js+++ b/src/agent-scene.js@@@ -3,22 -3,17 +3,18 @@@ import { box, cylinder, sphere, torusimport { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';import { normalizeAgentLook } from './agent-look.js';- import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';- import { normalizeAgentPhysics, bakeAgentPhysics } from './agent-physics.js';- import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';- import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';- import { expandInstancedNodes } from './mesh-instances.js';- import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';+ import { agentSceneModule } from './agent-scene-modules.js';+ import { MESH_SMOOTH_ANGLE_DEFAULT, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';- import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';+import { recipeDiagnostics } from './agent-diagnostics.js';+ import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';- export { needsMeshBooleans } from './agent-mesh.js';- export { needsPhysics, loadPhysicsEngine, physicsEngineLoaded } from './agent-physics.js';- export { setPhysicsModuleLoader } from './physics.js';- export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';+ export {+ needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,+ needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader,+ loadAgentSceneModules, loadAllAgentSceneModules, allAgentSceneModulesLoaded, agentSceneModulesNeeded,+ } from './agent-scene-modules.js';const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;const MAX_MESH_REPORTS = 16;@@@ -1073,14 -1156,13 +1157,15 @@@ export function createAgentScene(inputreturn result;});const resident = geometryStats(ownedGeometryRecords());+ const diagnostics = recipeDiagnostics(state.recipe);return {revision, topologyRevision,- ...(state.recipe.motion?.ik?.length ? { motionIk: compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),+ ...(state.recipe.motion?.ik?.length ? { motionIk: agentSceneModule('motion').compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,physics: state.physicsSampler ? state.physicsSampler.report() : null,+ ...(state.recipe.armatures ? { rig: rigReport(state.recipe, state.skinBindings) } : {}),boundsSpace: 'authored-base-world',+ ...(diagnostics.length ? { diagnostics } : {}),counts: {nodes: state.recipe.nodes.length, parts: state.parts.length,geometries: state.geometries.size, materials: state.recipe.materials.length,