3D engine that AI agents drive
Add mesh edits, the recipe mesh type and the mesh_edit tool
Nguyen Xuan And0817698dd9a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a1a669aa..74fb4dff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,8 @@## Unreleased- Add `67js/addons/mesh`, a polygon mesh core for agent modeling: compact `MeshData` with attributes on point, edge, face and corner domains, a half-edge `EditMesh` with typed-array disk and radial cycles, `validateTopology`, conversion from renderer geometry with welding, quads and axis face tags, hard-edge corner normals, n-gon triangulation, render extraction and `lintMesh`+- Add semantic face selection and mesh edits (extrude region and individual, inset region and individual, delete, flip normals, translate with proportional falloff, merge by distance, tag) that tag the faces they create+- Add the recipe geometry type `mesh` (a base shape plus a replayable edit log) and the `mesh_edit` MCP tool, which appends or replaces edits atomically and reports each edit's result- Add the `mesh_inspect` MCP tool: polygon counts, face sizes, parts, face tags, bounds and lint problems with suggested fixes for every recipe geometry## 0.10.0diff --git a/ROADMAP.md b/ROADMAP.mdindex 8cbd5240..b310e3bd 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -27,7 +27,7 @@ Version `0.8.0` adds source-node authoring on imported GLBs with retained rigs,Version `0.9.0` adds isolated multi-angle and pose review with unchanged source revision and preview state.-The stdio MCP server supplies nineteen schema-backed tools and persistent CPU/GPU image previews.+The stdio MCP server supplies twenty schema-backed tools and persistent CPU/GPU image previews.Recipes retain lighting, volumetric fog, grading and directional shadow coverage with atomic edits and undo.Imported asset sessions retain supported textures, rigs, morphs and clips from a configured local GLB catalog.diff --git a/docs/guide.md b/docs/guide.mdindex e2c979ef..26928cae 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -464,7 +464,7 @@ Disconnect observers, cancel animation frames, release pointer state and call `d## Models and AI agentsVersion `0.5.0` includes [agent scene sessions](/agent-scene.md) and the `67js-mcp` command.-Its [MCP server](/mcp.md) provides nineteen tools for authoring, previewing and exporting scenes through a persistent browser runtime.+Its [MCP server](/mcp.md) provides twenty tools for authoring, previewing and exporting scenes through a persistent browser runtime.Release `0.7.0` adds [agent motion](/agent-motion.md) for deterministic joint, material and camera keyframes.Read the MCP guide for npm installation, client configuration and CPU/GPU selection.The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.diff --git a/docs/mcp.md b/docs/mcp.mdindex 94f2ff37..3cea7827 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -103,6 +103,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision || `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status || `mesh_inspect` | `sessionId`, optional `geometries` (up to 16 IDs) | Per geometry: polygon counts, face sizes, parts, face tags, bounds and lint problems with fixes |+| `mesh_edit` | `sessionId`, `expectedRevision`, `geometry`, `edits`, optional `replace` | Updated revision, render status and the mesh report with per-edit results || `scene_look` | `sessionId`, optional `width`, `height`, `motionTime` | PNG image and metadata || `scene_review` | `sessionId`, `expectedRevision`, `shots`, optional `width`, `height` | Labeled PNG grid and metadata from an isolated snapshot || `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |@@ -117,7 +118,8 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_render_release` | `jobId` | Confirmation that owned job files were removed |The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.-Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, and `tube`.+Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, and `mesh`.+A `mesh` geometry starts from one of the others as `base` and replays an edit log; see [mesh.md](mesh.md).Geometry fields remain flat inside each geometry record.Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.diff --git a/docs/mesh.md b/docs/mesh.mdindex 491ba89d..f945b9ee 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -102,8 +102,69 @@ rebuilding the topology.`ok` is false when any error is present. Self-intersections and wall thickness are not checked yet.+## Selection and edits++`selectFaces(mesh, rule)` turns a JSON rule into a face mask. `applyMeshEdits(mesh, edits)` runs an edit log and+returns `{ mesh, results }`. Both are what recipe `mesh` geometries and the `mesh_edit` tool use.++Selection rules:++| Rule | Selects |+| --- | --- |+| `{ "all": true }` | every face |+| `{ "tag": "top" }` | faces carrying a tag |+| `{ "normal": [0, 1, 0], "maxAngle": 10 }` | faces facing within `maxAngle` degrees (default 10) of a direction |+| `{ "inside": { "min": [x, y, z], "max": [x, y, z] } }` | faces whose centroid lies in a box |+| `{ "faces": [0, 4] }` | explicit face indices |+| `{ "and": [...] }`, `{ "or": [...] }`, `{ "not": rule }` | combinations |+| `{ "grow": rule, "steps": 1 }` | the selection plus faces sharing an edge, repeated |+| `{ "boundary": rule }` | selected faces that touch an unselected face or an open edge |++Edits (names follow Blender's `bmesh.ops` where they match):++| Op | Fields | Creates tags |+| --- | --- | --- |+| `extrude_face_region` | `select`, `offset`, optional `direction`, `name` | `<name>.cap`, `<name>.side` |+| `extrude_individual` | same | same, per face |+| `inset_region` | `select`, `thickness`, optional `depth`, `name` | `<name>.cap`, `<name>.rim` |+| `inset_individual` | same | same, per face |+| `delete` | `select` (required) | |+| `flip_normals` | `select` | |+| `translate` | `select`, `offset` [x, y, z], optional `falloff` `{ radius, curve, connected }` | |+| `merge_by_distance` | `distance` (default 1e-4) | |+| `tag` | `select`, `name` (required) | `<name>` |++- `select` defaults to every face, except for `delete` and `tag`.+- `name` defaults to `<op>-<index>`, for example `extrude-1`.+- Extrusions move each group of edge-connected faces along that group's own average normal. Faces in one group+ that face opposite ways (the four sides of a box) cancel out; use the `_individual` op or pass `direction`.+- Caps keep their earlier tags; side and rim faces start without tags.+- Falloff curves follow Blender's proportional editing: `smooth`, `sphere`, `root`, `sharp`, `linear`,+ `constant`, `inverseSquare`. With `connected`, distance is measured along edges.+- An edit that selects no faces, names an unknown tag, or grows the mesh past its limits throws an error naming+ the edit index and op. A log holds at most 64 edits.++Each result records `selected`, the `tags` created with their face counts, op-specific counts (`deletedFaces`,+`movedVertices`, `removedVertices`) and the mesh size `after` the edit.++Bevel, loop cut, booleans, mirror, array and solidify are planned next.+## MCP+A recipe geometry of type `mesh` starts from a primitive or profile and replays an edit log:++```json+{ "id": "crate", "type": "mesh", "base": { "type": "box", "bevel": 0 }, "smoothAngle": 30,+ "edits": [+ { "op": "inset_individual", "select": { "tag": "side" }, "thickness": 0.07, "name": "panel" },+ { "op": "extrude_individual", "select": { "tag": "panel.cap" }, "offset": -0.04 }+ ] }+```++Edges bending more than `smoothAngle` degrees (default 30) render hard. `mesh_edit` appends edits to such a+geometry (or replaces its log with `replace: true`) as one atomic revision, so checkpoints and `expectedRevision`+work as for `scene_apply`. It returns the render status and the mesh report below, including one result per edit.+`mesh_inspect` runs the same conversion and lint on the geometries of a procedural recipe scene and returns onecompact record per geometry:@@ -117,8 +178,9 @@ compact record per geometry:"problems": [] }```-Reports are cached per generated geometry, so asking again without edits is free. Imported asset scenes are not-supported yet.+Reports are cached per generated geometry, so asking again without edits is free. For `mesh` geometries the report+describes the edited polygon mesh and adds `edits`, the per-edit results. Imported asset scenes are not supported+yet.## Measured speeddiff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 2bd11386..00387588 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -300,6 +300,16 @@ window.__agentPreview = {record.scene.apply(operations, { expectedRevision });return mutationStatus(record);},+ editMesh({ sessionId, expectedRevision, geometry, edits, replace }) {+ const record = requireSession(sessionId);+ if (typeof record.scene.inspectMeshes !== 'function') {+ throw new TypeError('mesh_edit supports procedural recipe scenes. Imported asset scenes have no editable mesh geometry yet.');+ }+ const operation = { type: 'edit-mesh', geometry, edits, ...(replace === undefined ? {} : { replace }) };+ const status = this.apply({ sessionId, operations: [operation], expectedRevision });+ const [mesh] = record.scene.inspectMeshes({ geometries: [geometry] }).meshes;+ return { ...status, mesh };+ },look({ sessionId, motionTime }) {const record = requireSession(sessionId);if (motionTime !== undefined) {diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex d37a7d4b..f6d5b8b9 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -365,6 +365,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoinspectMeshes(input) {return enqueue(() => invoke('inspectMeshes', input));},+ editMesh(input) {+ return enqueue(async () => {+ await requirePreviewRenderer();+ return invoke('editMesh', input);+ });+ },apply(input) {return enqueue(async () => {await requirePreviewRenderer();diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5296c96d..c3544f4c 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -110,14 +110,35 @@ const shadow = z.strictObject({near: bounded(0.001, 1e6).optional(),far: bounded(0.001, 1e6).optional(),}).describe('Directional shadow coverage. Backend checks Float32 view/projection consistency.');+function primitiveGeometries(identified) {+ const id = identified ? { id: identifier } : {};+ return [+ z.strictObject({ ...id, type: z.literal('box'), bevel: finite.optional(), subdivisions: detail(1, 128) }),+ z.strictObject({ ...id, type: z.literal('cylinder'), segments, bevel: finite.optional(), bevelSegments: detail(1, 128) }),+ z.strictObject({ ...id, type: z.literal('sphere'), segments, rings: detail(2, 2048) }),+ z.strictObject({ ...id, type: z.literal('torus'), tubeRadius: finite.optional(), segments, sides: detail(3, 128), arc: finite.optional(), start: finite.optional() }),+ z.strictObject({ ...id, type: z.literal('lathe'), profile: z.array(point2).min(2).max(4096), segments, startAngle: finite.optional(), sweep: finite.optional() }),+ z.strictObject({ ...id, type: z.literal('extrude'), contour: ring, holes: z.array(ring).max(128).optional(), depth: finite.optional(), steps: detail(1, 256), bevel: finite.optional(), bevelThickness: finite.optional(), bevelSegments: detail(1, 32) }),+ z.strictObject({ ...id, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),+ ];+}+const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}. Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');+const editName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).optional().describe('Prefix for the tags this edit creates. Defaults to <op>-<index>.');+const meshEdit = z.discriminatedUnion('op', [+ z.strictObject({ op: z.literal('extrude_face_region'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each connected region\'s average normal (negative pushes in).'), direction: vector3.optional().describe('Move along this direction instead of the normal.') }),+ z.strictObject({ op: z.literal('extrude_individual'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each face\'s own normal.'), direction: vector3.optional() }),+ z.strictObject({ op: z.literal('inset_region'), select: selectRule.optional(), name: editName, thickness: finite.describe('Rim width, positive.'), depth: finite.optional().describe('Move the inner faces along the normal afterwards.') }),+ z.strictObject({ op: z.literal('inset_individual'), select: selectRule.optional(), name: editName, thickness: finite, depth: finite.optional() }),+ z.strictObject({ op: z.literal('delete'), select: selectRule }),+ z.strictObject({ op: z.literal('flip_normals'), select: selectRule.optional() }),+ z.strictObject({ op: z.literal('translate'), select: selectRule.optional(), offset: vector3, falloff: z.strictObject({ radius: finite, curve: z.enum(['smooth', 'sphere', 'root', 'sharp', 'linear', 'constant', 'inverseSquare']).optional(), connected: z.boolean().optional().describe('Measure distance along edges instead of straight lines.') }).optional() }),+ z.strictObject({ op: z.literal('merge_by_distance'), distance: finite.optional() }),+ z.strictObject({ op: z.literal('tag'), select: selectRule, name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).describe('Tag to add to the selected faces.') }),+]);+const meshEdits = z.array(meshEdit).max(64);const geometry = z.discriminatedUnion('type', [- z.strictObject({ id: identifier, type: z.literal('box'), bevel: finite.optional(), subdivisions: detail(1, 128) }),- z.strictObject({ id: identifier, type: z.literal('cylinder'), segments, bevel: finite.optional(), bevelSegments: detail(1, 128) }),- z.strictObject({ id: identifier, type: z.literal('sphere'), segments, rings: detail(2, 2048) }),- z.strictObject({ id: identifier, type: z.literal('torus'), tubeRadius: finite.optional(), segments, sides: detail(3, 128), arc: finite.optional(), start: finite.optional() }),- z.strictObject({ id: identifier, type: z.literal('lathe'), profile: z.array(point2).min(2).max(4096), segments, startAngle: finite.optional(), sweep: finite.optional() }),- z.strictObject({ id: identifier, type: z.literal('extrude'), contour: ring, holes: z.array(ring).max(128).optional(), depth: finite.optional(), steps: detail(1, 256), bevel: finite.optional(), bevelThickness: finite.optional(), bevelSegments: detail(1, 32) }),- z.strictObject({ id: identifier, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),+ ...primitiveGeometries(true),+ z.strictObject({ id: identifier, type: z.literal('mesh'), base: z.discriminatedUnion('type', primitiveGeometries(false)).describe('Starting shape, converted to welded quads with axis face tags.'), edits: meshEdits.optional().describe('Replayable edit log, applied in order.'), smoothAngle: bounded(0, 180).optional().describe('Edges bending more than this many degrees render hard. Defaults to 30.') }),]);function motionTrack(kind, property, value, tangent) {return z.strictObject({@@ -245,6 +266,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('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. 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, geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit to check the first 16 geometries.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspectMeshes(argumentsValue)));+ 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, and tag. 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('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.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG. 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.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);diff --git a/scripts/smoke-agent-assets.mjs b/scripts/smoke-agent-assets.mjsindex 1aed3c6c..9511bac7 100644--- a/scripts/smoke-agent-assets.mjs+++ b/scripts/smoke-agent-assets.mjs@@ -35,7 +35,7 @@ async function look(sessionId, label) {}try {await client.connect(transport, { timeout: 180000 });- assert.equal((await client.listTools()).tools.length, 19);+ assert.equal((await client.listTools()).tools.length, 20);const catalog = (await call('scene_asset_catalog')).structuredContent;assert.equal(catalog.configured, true);assert.equal(catalog.assets.length, 2);diff --git a/scripts/smoke-agent-render-jobs.mjs b/scripts/smoke-agent-render-jobs.mjsindex 72946bb6..461e3be7 100644--- a/scripts/smoke-agent-render-jobs.mjs+++ b/scripts/smoke-agent-render-jobs.mjs@@ -57,7 +57,7 @@ async function close() {}try {await connect();- assert.equal((await client.listTools()).tools.length, 19);+ assert.equal((await client.listTools()).tools.length, 20);const catalog = (await call('scene_asset_catalog')).structuredContent;const created = (await call('scene_create_asset', { recipe: {format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId,diff --git a/scripts/smoke-agent-review.mjs b/scripts/smoke-agent-review.mjsindex 3b58de85..006bdbcb 100644--- a/scripts/smoke-agent-review.mjs+++ b/scripts/smoke-agent-review.mjs@@ -48,7 +48,7 @@ function pixels(bytes, crop) {}try {await client.connect(transport);- assert.equal((await client.listTools()).tools.length, 19);+ assert.equal((await client.listTools()).tools.length, 20);const created = (await call('scene_create_asset', { recipe: fixture.recipe })).structuredContent;const sessionId = created.sessionId;const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex e82e4afe..012585f0 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -108,7 +108,7 @@ for (const era of ['modern', 'legacy']) {const connectMs = performance.now() - start;processId = transport.pid;assert.equal(client.getServerVersion().version, metadata.version);- assert.equal((await client.listTools()).tools.length, 19);+ assert.equal((await client.listTools()).tools.length, 20);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');assert.equal(capabilities.preview.maximumActiveScenes, 1);diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjsindex 4f79b4c9..7eaf1dca 100644--- a/scripts/smoke-mcp.mjs+++ b/scripts/smoke-mcp.mjs@@ -53,7 +53,7 @@ try {await client.connect(transport);processId = transport.pid;const listing = await client.listTools();- assert.equal(listing.tools.length, 19);+ assert.equal(listing.tools.length, 20);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');const fixture = createAgentPreviewFixture();diff --git a/src/agent-mesh.js b/src/agent-mesh.jsindex 866119dd..af098125 100644--- a/src/agent-mesh.js+++ b/src/agent-mesh.js@@ -1,10 +1,30 @@import { meshFromGeometry } from './mesh-convert.js';import { lintMesh } from './mesh-lint.js';+import { applyMeshEdits } from './mesh-recipe.js';+import { extractRender } from './mesh-render.js';// Compact, agent-facing mesh reports for scene geometry. Reports are cached per immutable geometry object, so// repeated inspection of an unchanged scene costs nothing.+export const MESH_SMOOTH_ANGLE_DEFAULT = 30;const reports = new WeakMap();+// Render geometry generated from a mesh recipe keeps its polygon mesh and edit results here.+const polygonMeshes = new WeakMap();++/**+ * Build render geometry for a recipe `mesh` geometry: convert the base, run the edit log, and extract triangles with+ * edges sharper than smoothAngle (degrees) kept hard, as Blender's auto smooth does.+ */+export function generateMeshGeometry(baseGeometry, edits, { maxVertices, smoothAngle = MESH_SMOOTH_ANGLE_DEFAULT }) {+ const base = meshFromGeometry(baseGeometry);+ const { mesh, results } = applyMeshEdits(base, edits, { maxVertices, maxFaces: maxVertices });+ const { geometry } = extractRender(mesh, { sharpAngle: smoothAngle * Math.PI / 180 });+ if (geometry.positions.length / 3 > maxVertices) {+ throw new RangeError(`The edited mesh needs ${geometry.positions.length / 3} render vertices, over maxVertices ${maxVertices}.`);+ }+ polygonMeshes.set(geometry, { mesh, results });+ return geometry;+}function faceSizeHistogram(mesh) {const histogram = { triangles: 0, quads: 0, ngons: 0 };@@ -29,7 +49,8 @@ function roundedBounds(bounds) {export function meshReport(geometry) {let report = reports.get(geometry);if (report) return report;- const mesh = meshFromGeometry(geometry);+ const polygon = polygonMeshes.get(geometry);+ const mesh = polygon?.mesh ?? meshFromGeometry(geometry);const lint = lintMesh(mesh);report = Object.freeze({ok: lint.ok,@@ -39,6 +60,7 @@ export function meshReport(geometry) {tags: lint.tags,bounds: roundedBounds(lint.bounds),problems: lint.problems,+ ...(polygon ? { edits: polygon.results } : {}),});reports.set(geometry, report);return report;diff --git a/src/agent-scene.js b/src/agent-scene.jsindex a0f19607..eff09e4d 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -5,7 +5,8 @@ import { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';import { normalizeAgentLook } from './agent-look.js';import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';-import { meshReport } from './agent-mesh.js';+import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';+import { normalizeMeshEdits, MESH_EDIT_OPERATIONS, MAX_MESH_EDITS } from './mesh-recipe.js';export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';const DEFAULT_LIMITS = Object.freeze({@@ -37,11 +38,12 @@ const REMOVAL_FIELDS = Object.freeze({export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']),+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),+ meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',- 'set-environment', 'set-effects', 'set-shadow', 'set-motion',+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'edit-mesh',]),materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),alphaModes: Object.freeze(RECIPE_ALPHA_MODES),@@ -321,6 +323,7 @@ const GEOMETRY_FIELDS = {lathe: ['profile', 'segments', 'startAngle', 'sweep'],extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],+ mesh: ['base', 'edits', 'smoothAngle'],};function geometryEstimate(value) {@@ -341,7 +344,7 @@ function geometryEstimate(value) {return input.length;}for (const field of GEOMETRY_FIELDS[value.type]) {- if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed'].includes(field)) {+ if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits'].includes(field)) {finite(value[field], field);}}@@ -374,6 +377,19 @@ function geometryEstimate(value) {const beveled = (value.bevel ?? 0) > 0 || (value.bevelThickness ?? value.bevel ?? 0) > 0;return 6 * (count + holes.length * 2 - 2) + 6 * count * (detail('steps', 1, 1, 256) + (beveled ? detail('bevelSegments', 3, 1, 32) * 2 : 0));}+ case 'mesh': {+ const base = value.base;+ if (!base || typeof base !== 'object' || Array.isArray(base) || base.type === 'mesh' || Object.hasOwn(base, 'id')) {+ throw new TypeError('mesh base must be a primitive or profile geometry record without an id (box, cylinder, sphere, torus, lathe, extrude or tube).');+ }+ const baseEstimate = geometryEstimate({ id: 'base', ...base });+ normalizeMeshEdits(value.edits ?? []);+ if (value.smoothAngle !== undefined && (value.smoothAngle < 0 || value.smoothAngle > 180)) {+ throw new RangeError('smoothAngle is degrees from 0 to 180.');+ }+ // Edits can grow the mesh; the real size is checked against maxVertices after generation.+ return baseEstimate * 2;+ }}}@@ -393,6 +409,10 @@ function generateGeometry(value, maxVertices) {return extrude(value.contour, { ...value, maxVertices });case 'tube':return tube(value.path, { ...value, maxVertices });+ case 'mesh':+ return generateMeshGeometry(generateGeometry(value.base, maxVertices), value.edits ?? [], {+ maxVertices, smoothAngle: value.smoothAngle ?? MESH_SMOOTH_ANGLE_DEFAULT,+ });}}@@ -689,7 +709,11 @@ export function createAgentScene(input, inputLimits = {}) {const geometry = Object.freeze(generateGeometry(plan.definition, Math.min(limits.maxVertices, 1_000_000)));const geometryBytes = Object.values(geometry).reduce((total, array) => total + array.byteLength, 0);const vertices = geometry.positions.length / 3;- if (vertices > plan.estimatedVertices || geometryBytes > plan.estimatedVertices * 56) {+ if (plan.definition.type === 'mesh') {+ if (residentStats.vertices + pendingVertices - plan.estimatedVertices + vertices > limits.maxVertices) {+ throw new RangeError(`Mesh ${plan.definition.id} has ${vertices} render vertices after its edits, which exceeds maxVertices across the scene. Reduce detail or edits.`);+ }+ } else if (vertices > plan.estimatedVertices || geometryBytes > plan.estimatedVertices * 56) {throw new RangeError('Generated geometry exceeds its conservative preflight bound.');}record = Object.freeze({@@ -853,6 +877,26 @@ export function createAgentScene(input, inputLimits = {}) {candidate[collection].push(record);continue;}+ if (operation.type === 'edit-mesh') {+ knownKeys(operation, ['type', 'geometry', 'edits', 'replace'], 'operation');+ identifier(operation.geometry);+ const target = candidate.geometries.find(geometry => geometry.id === operation.geometry);+ if (!target) {+ throw new RangeError(`Geometry ID was not found: ${operation.geometry}.`);+ }+ if (target.type !== 'mesh') {+ throw new TypeError(`Geometry ${operation.geometry} is a ${target.type}. Add a mesh geometry with base: { type: '${target.type}', ... } to edit it.`);+ }+ if (operation.replace !== undefined && typeof operation.replace !== 'boolean') {+ throw new TypeError('replace must be boolean.');+ }+ if (!Array.isArray(operation.edits)) {+ throw new TypeError('edit-mesh needs an edits array.');+ }+ target.edits = operation.replace ? operation.edits : [...(target.edits ?? []), ...operation.edits];+ normalizeMeshEdits(target.edits);+ continue;+ }if (operation.type === 'remove-node') {for (const id of removeNode(candidate, operation)) {removedNodes.add(id);diff --git a/src/mesh-ops.js b/src/mesh-ops.jsnew file mode 100644index 00000000..1c044631--- /dev/null+++ b/src/mesh-ops.js@@ -0,0 +1,553 @@+import { createMeshData, deriveEdges, TAG_PREFIX, DOMAINS } from './mesh-data.js';+import { weldVertices } from './mesh-convert.js';++// Local topology operators on an EditMesh. Each takes a face mask indexed by EditMesh face index (equal to MeshData+// face index right after editMesh()) and returns the faces it created, so callers can tag and report them.++function copyElementAttributes(store, source, target) {+ for (const attribute of store.attributes.values()) {+ const size = attribute.size;+ attribute.data.copyWithin(target * size, source * size, (source + 1) * size);+ }+}++function saveElementAttributes(store, index) {+ const saved = [];+ for (const attribute of store.attributes.values()) {+ saved.push(attribute.data.slice(index * attribute.size, (index + 1) * attribute.size));+ }+ return saved;+}++function restoreElementAttributes(store, index, saved) {+ let position = 0;+ for (const attribute of store.attributes.values()) {+ attribute.data.set(saved[position], index * attribute.size);+ position++;+ }+}++function clearTags(edit, face) {+ for (const [name, attribute] of edit.faces.attributes) {+ if (name.startsWith(TAG_PREFIX)) attribute.data[face] = 0;+ }+}++/** Mark faces with a tag, creating the tag attribute when needed. */+export function tagFaces(edit, faces, tag) {+ const attribute = edit.ensureAttribute('face', TAG_PREFIX + tag, Uint8Array, 1);+ for (const face of faces) attribute.data[face] = 1;+}++/** Area-weighted normal (Newell) of one EditMesh face; length is twice the area. */+function faceNormalVector(edit, face) {+ const position = edit.vertices.arrays.position;+ const loops = edit.loops.arrays;+ const first = edit.faces.arrays.loop[face];+ let normalX = 0;+ let normalY = 0;+ let normalZ = 0;+ let loop = first;+ do {+ const current = loops.vertex[loop] * 3;+ const next = loops.vertex[loops.next[loop]] * 3;+ normalX += (position[current + 1] - position[next + 1]) * (position[current + 2] + position[next + 2]);+ normalY += (position[current + 2] - position[next + 2]) * (position[current] + position[next]);+ normalZ += (position[current] - position[next]) * (position[current + 1] + position[next + 1]);+ loop = loops.next[loop];+ } while (loop !== first);+ return [normalX, normalY, normalZ];+}++function normalize(vector) {+ const length = Math.hypot(vector[0], vector[1], vector[2]);+ if (length === 0) return [0, 0, 0];+ return [vector[0] / length, vector[1] / length, vector[2] / length];+}++function cross(first, second) {+ return [+ first[1] * second[2] - first[2] * second[1],+ first[2] * second[0] - first[0] * second[2],+ first[0] * second[1] - first[1] * second[0],+ ];+}++/** Live face indices selected by a mask. */+export function maskedFaces(edit, mask) {+ const faces = [];+ for (let face = 0; face < mask.length; face++) {+ if (mask[face] && edit.faces.isLive(face)) faces.push(face);+ }+ return faces;+}++function regionNormal(edit, faces) {+ const sum = [0, 0, 0];+ for (const face of faces) {+ const normal = faceNormalVector(edit, face);+ sum[0] += normal[0];+ sum[1] += normal[1];+ sum[2] += normal[2];+ }+ return normalize(sum);+}++/**+ * Split a face region from the rest of the mesh along its boundary, as BMesh's extrude_face_region does:+ * boundary vertices are duplicated, region faces are rebuilt on the duplicates, and one quad per boundary edge+ * joins old and new vertices. Interior region vertices are shared, not duplicated.+ * Returns the rebuilt cap faces, the new side faces, the boundary loops (as vertex pairs with their face normal)+ * and the map from original boundary vertex to duplicate.+ */+function splitRegion(edit, faces) {+ const inRegion = new Uint8Array(edit.faces.count);+ for (const face of faces) inRegion[face] = 1;+ const loops = edit.loops.arrays;+ const boundary = [];+ for (const face of faces) {+ const normal = normalize(faceNormalVector(edit, face));+ const first = edit.faces.arrays.loop[face];+ let loop = first;+ do {+ let sharedWithRegion = false;+ let other = loops.radialNext[loop];+ while (other !== loop) {+ if (inRegion[loops.face[other]]) sharedWithRegion = true;+ other = loops.radialNext[other];+ }+ if (!sharedWithRegion) {+ boundary.push({+ from: loops.vertex[loop], to: loops.vertex[loops.next[loop]], face, normal,+ fromCorner: saveElementAttributes(edit.loops, loop),+ toCorner: saveElementAttributes(edit.loops, loops.next[loop]),+ faceAttributes: saveElementAttributes(edit.faces, face),+ });+ }+ loop = loops.next[loop];+ } while (loop !== first);+ }+ const duplicateOf = new Map();+ for (const { from, to } of boundary) {+ for (const vertex of [from, to]) {+ if (duplicateOf.has(vertex)) continue;+ const position = edit.vertexPosition(vertex);+ const duplicate = edit.createVertex(position[0], position[1], position[2]);+ copyElementAttributes(edit.vertices, vertex, duplicate);+ duplicateOf.set(vertex, duplicate);+ }+ }+ const regionEdges = new Set();+ for (const face of faces) {+ for (const loop of edit.faceLoops(face)) regionEdges.add(loops.edge[loop]);+ }+ const capFaces = [];+ for (const face of faces) {+ const faceLoops = edit.faceLoops(face);+ const vertices = faceLoops.map(loop => loops.vertex[loop]);+ const cornerAttributes = faceLoops.map(loop => saveElementAttributes(edit.loops, loop));+ const faceAttributes = saveElementAttributes(edit.faces, face);+ edit.removeFace(face);+ const rebuilt = edit.createFace(vertices.map(vertex => duplicateOf.get(vertex) ?? vertex));+ restoreElementAttributes(edit.faces, rebuilt, faceAttributes);+ edit.faceLoops(rebuilt).forEach((loop, index) => restoreElementAttributes(edit.loops, loop, cornerAttributes[index]));+ capFaces.push(rebuilt);+ }+ const sideFaces = [];+ for (const edge of boundary) {+ const side = edit.createFace([edge.from, edge.to, duplicateOf.get(edge.to), duplicateOf.get(edge.from)]);+ restoreElementAttributes(edit.faces, side, edge.faceAttributes);+ clearTags(edit, side);+ const [fromLoop, toLoop, toDuplicateLoop, fromDuplicateLoop] = edit.faceLoops(side);+ restoreElementAttributes(edit.loops, fromLoop, edge.fromCorner);+ restoreElementAttributes(edit.loops, fromDuplicateLoop, edge.fromCorner);+ restoreElementAttributes(edit.loops, toLoop, edge.toCorner);+ restoreElementAttributes(edit.loops, toDuplicateLoop, edge.toCorner);+ sideFaces.push(side);+ }+ // Region edges whose faces moved onto duplicates are left as wire edges; drop them so the result stays clean.+ for (const edge of regionEdges) {+ if (edit.edges.isLive(edge) && edit.edgeFaceCount(edge) === 0) edit.removeEdge(edge);+ }+ return { capFaces, sideFaces, boundary, duplicateOf };+}++function faceVertexSet(edit, faces) {+ const vertices = new Set();+ for (const face of faces) {+ for (const vertex of edit.faceVertices(face)) vertices.add(vertex);+ }+ return vertices;+}++function moveVertices(edit, vertices, offset) {+ const position = edit.vertices.arrays.position;+ for (const vertex of vertices) {+ position[vertex * 3] += offset[0];+ position[vertex * 3 + 1] += offset[1];+ position[vertex * 3 + 2] += offset[2];+ }+}++function offsetVector(edit, faces, { offset, direction }) {+ if (direction !== undefined) {+ const unit = normalize(direction);+ if (unit.every(value => value === 0)) throw new RangeError('direction cannot be zero.');+ return unit.map(value => value * offset);+ }+ const normal = regionNormal(edit, faces);+ if (normal.every(value => value === 0)) throw new RangeError('The selected faces face opposite ways, so their average normal cancels out. Use extrude_individual or inset_individual, select fewer faces, or pass direction.');+ return normal.map(value => value * offset);+}++/** Groups of selected faces connected through shared edges. */+export function connectedRegions(edit, faces) {+ const selected = new Set(faces);+ const visited = new Set();+ const regions = [];+ for (const start of faces) {+ if (visited.has(start)) continue;+ const region = [];+ const stack = [start];+ visited.add(start);+ while (stack.length) {+ const face = stack.pop();+ region.push(face);+ for (const neighbor of edit.faceNeighbors(face)) {+ if (selected.has(neighbor) && !visited.has(neighbor)) {+ visited.add(neighbor);+ stack.push(neighbor);+ }+ }+ }+ regions.push(region);+ }+ return regions;+}++/**+ * Extrude the selected faces and move each cap by `offset` along its region's normal or along `direction`.+ * Faces connected by edges extrude together as one region; separate groups extrude separately.+ */+export function extrudeFaceRegion(edit, mask, options) {+ const capFaces = [];+ const sideFaces = [];+ for (const region of connectedRegions(edit, maskedFaces(edit, mask))) {+ const vector = offsetVector(edit, region, options);+ const result = splitRegion(edit, region);+ moveVertices(edit, faceVertexSet(edit, result.capFaces), vector);+ capFaces.push(...result.capFaces);+ sideFaces.push(...result.sideFaces);+ }+ return { capFaces, sideFaces };+}++/** Extrude every selected face on its own, each along its own normal (or `direction`). */+export function extrudeIndividual(edit, mask, options) {+ const capFaces = [];+ const sideFaces = [];+ for (const face of maskedFaces(edit, mask)) {+ const vector = offsetVector(edit, [face], options);+ const result = splitRegion(edit, [face]);+ moveVertices(edit, faceVertexSet(edit, result.capFaces), vector);+ capFaces.push(...result.capFaces);+ sideFaces.push(...result.sideFaces);+ }+ return { capFaces, sideFaces };+}++/**+ * Inset the selected region: a rim of quads `thickness` wide along the region boundary, measured in the plane of the+ * neighbouring region faces with even-thickness correction at corners, then the inner faces move `depth` along the+ * region normal (negative depth pushes in).+ */+export function insetRegion(edit, mask, options) {+ const capFaces = [];+ const sideFaces = [];+ for (const region of connectedRegions(edit, maskedFaces(edit, mask))) {+ const result = insetFaces(edit, region, options);+ capFaces.push(...result.capFaces);+ sideFaces.push(...result.sideFaces);+ }+ return { capFaces, sideFaces };+}++/** Inset every selected face on its own, as Blender's inset with "individual". */+export function insetIndividual(edit, mask, options) {+ const capFaces = [];+ const sideFaces = [];+ for (const face of maskedFaces(edit, mask)) {+ const result = insetFaces(edit, [face], options);+ capFaces.push(...result.capFaces);+ sideFaces.push(...result.sideFaces);+ }+ return { capFaces, sideFaces };+}++function insetFaces(edit, faces, { thickness, depth = 0 }) {+ const normal = regionNormal(edit, faces);+ const { capFaces, sideFaces, boundary, duplicateOf } = splitRegion(edit, faces);+ const incoming = new Map();+ const outgoing = new Map();+ for (const edge of boundary) {+ outgoing.set(edge.from, edge);+ incoming.set(edge.to, edge);+ }+ const position = edit.vertices.arrays.position;+ const point = vertex => [position[vertex * 3], position[vertex * 3 + 1], position[vertex * 3 + 2]];+ const inwardOf = edge => {+ const start = point(edge.from);+ const end = point(edge.to);+ return normalize(cross(edge.normal, [end[0] - start[0], end[1] - start[1], end[2] - start[2]]));+ };+ for (const [vertex, duplicate] of duplicateOf) {+ const before = incoming.get(vertex);+ const after = outgoing.get(vertex);+ const directions = [before, after].filter(Boolean).map(inwardOf);+ const sum = directions.reduce((total, value) => [total[0] + value[0], total[1] + value[1], total[2] + value[2]], [0, 0, 0]);+ const inward = normalize(sum);+ // Even thickness: divide by the cosine between the corner bisector and each edge's inward direction.+ const cosine = Math.max(0.25, ...directions.map(value => value[0] * inward[0] + value[1] * inward[1] + value[2] * inward[2]));+ const distance = thickness / cosine;+ position[duplicate * 3] += inward[0] * distance;+ position[duplicate * 3 + 1] += inward[1] * distance;+ position[duplicate * 3 + 2] += inward[2] * distance;+ }+ if (depth !== 0) moveVertices(edit, faceVertexSet(edit, capFaces), normal.map(value => value * depth));+ return { capFaces, sideFaces };+}++/** Delete the selected faces, then edges and vertices that no face uses any more. */+export function deleteFaces(edit, mask) {+ const faces = maskedFaces(edit, mask);+ const edges = new Set();+ const vertices = new Set();+ for (const face of faces) {+ for (const loop of edit.faceLoops(face)) {+ edges.add(edit.loops.arrays.edge[loop]);+ vertices.add(edit.loops.arrays.vertex[loop]);+ }+ }+ for (const face of faces) edit.removeFace(face);+ for (const edge of edges) {+ if (edit.edges.isLive(edge) && edit.edgeFaceCount(edge) === 0) edit.removeEdge(edge);+ }+ for (const vertex of vertices) {+ if (edit.vertices.isLive(vertex) && edit.vertexDegree(vertex) === 0) edit.removeVertex(vertex);+ }+ return { deletedFaces: faces.length };+}++/** Reverse the winding of the selected faces, carrying corner attributes with their vertices. */+export function flipFaces(edit, mask) {+ const flipped = [];+ for (const face of maskedFaces(edit, mask)) {+ const faceLoops = edit.faceLoops(face);+ const vertices = faceLoops.map(loop => edit.loops.arrays.vertex[loop]).reverse();+ const cornerAttributes = faceLoops.map(loop => saveElementAttributes(edit.loops, loop)).reverse();+ const faceAttributes = saveElementAttributes(edit.faces, face);+ edit.removeFace(face);+ const rebuilt = edit.createFace(vertices);+ restoreElementAttributes(edit.faces, rebuilt, faceAttributes);+ edit.faceLoops(rebuilt).forEach((loop, index) => restoreElementAttributes(edit.loops, loop, cornerAttributes[index]));+ flipped.push(rebuilt);+ }+ return { flippedFaces: flipped };+}++// Blender's proportional-editing falloff curves, as functions of t = distance / radius in [0, 1].+export const FALLOFF_CURVES = Object.freeze({+ smooth: t => 3 * (1 - t) ** 2 - 2 * (1 - t) ** 3,+ sphere: t => Math.sqrt(Math.max(0, 1 - t * t)),+ root: t => Math.sqrt(1 - t),+ sharp: t => (1 - t) ** 2,+ linear: t => 1 - t,+ constant: () => 1,+ inverseSquare: t => 1 - t * t,+});++class MinimumHeap {+ constructor() {+ this.keys = [];+ this.values = [];+ }++ push(key, value) {+ const keys = this.keys;+ const values = this.values;+ let index = keys.length;+ keys.push(key);+ values.push(value);+ while (index > 0) {+ const parent = (index - 1) >> 1;+ if (keys[parent] <= key) break;+ keys[index] = keys[parent];+ values[index] = values[parent];+ index = parent;+ }+ keys[index] = key;+ values[index] = value;+ }++ pop() {+ const keys = this.keys;+ const values = this.values;+ const top = { key: keys[0], value: values[0] };+ const lastKey = keys.pop();+ const lastValue = values.pop();+ if (keys.length) {+ let index = 0;+ for (;;) {+ const left = index * 2 + 1;+ if (left >= keys.length) break;+ const right = left + 1;+ const child = right < keys.length && keys[right] < keys[left] ? right : left;+ if (keys[child] >= lastKey) break;+ keys[index] = keys[child];+ values[index] = values[child];+ index = child;+ }+ keys[index] = lastKey;+ values[index] = lastValue;+ }+ return top;+ }++ get size() {+ return this.keys.length;+ }+}++/** Distance from the seed vertices along edges (geodesic on the mesh), up to `radius`. */+function connectedDistances(edit, seeds, radius) {+ const distances = new Map();+ const heap = new MinimumHeap();+ for (const seed of seeds) heap.push(0, seed);+ const position = edit.vertices.arrays.position;+ while (heap.size) {+ const { key: distance, value: vertex } = heap.pop();+ if (distances.has(vertex)) continue;+ distances.set(vertex, distance);+ for (const edge of edit.vertexEdges(vertex)) {+ const neighbor = edit.edgeOtherVertex(edge, vertex);+ if (distances.has(neighbor)) continue;+ const step = Math.hypot(+ position[neighbor * 3] - position[vertex * 3],+ position[neighbor * 3 + 1] - position[vertex * 3 + 1],+ position[neighbor * 3 + 2] - position[vertex * 3 + 2],+ );+ if (distance + step <= radius) heap.push(distance + step, neighbor);+ }+ }+ return distances;+}++/** Straight-line distance from the nearest seed vertex, up to `radius`, for every live vertex. */+function spatialDistances(edit, seeds, radius, maxVisits) {+ const seedList = [...seeds];+ const liveCount = edit.vertexCount;+ if (seedList.length * liveCount > maxVisits) {+ throw new RangeError('Proportional falloff exceeds its distance budget. Use connected: true or a smaller selection.');+ }+ const distances = new Map();+ const position = edit.vertices.arrays.position;+ for (const vertex of edit.liveIndices('point')) {+ let best = Infinity;+ for (const seed of seedList) {+ const distance = Math.hypot(+ position[vertex * 3] - position[seed * 3],+ position[vertex * 3 + 1] - position[seed * 3 + 1],+ position[vertex * 3 + 2] - position[seed * 3 + 2],+ );+ if (distance < best) best = distance;+ }+ if (best <= radius) distances.set(vertex, best);+ }+ return distances;+}++/**+ * Move the vertices of the selected faces by `offset`. With `falloff: { radius, curve, connected }`, nearby+ * vertices follow with a weight from Blender's proportional-editing curves (distance along edges when connected).+ */+export function translateFaces(edit, mask, { offset, falloff }, { maxFalloffVisits = 50_000_000 } = {}) {+ const seeds = faceVertexSet(edit, maskedFaces(edit, mask));+ if (!falloff) {+ moveVertices(edit, seeds, offset);+ return { movedVertices: seeds.size };+ }+ const curve = FALLOFF_CURVES[falloff.curve ?? 'smooth'];+ const distances = falloff.connected+ ? connectedDistances(edit, seeds, falloff.radius)+ : spatialDistances(edit, seeds, falloff.radius, maxFalloffVisits);+ const position = edit.vertices.arrays.position;+ for (const [vertex, distance] of distances) {+ const weight = seeds.has(vertex) ? 1 : curve(distance / falloff.radius);+ position[vertex * 3] += offset[0] * weight;+ position[vertex * 3 + 1] += offset[1] * weight;+ position[vertex * 3 + 2] += offset[2] * weight;+ }+ return { movedVertices: distances.size };+}++/**+ * Weld vertices closer than `distance` (MeshData in, MeshData out), as Blender's Merge by Distance.+ * Faces lose corners that collapse onto their neighbour; faces left with fewer than three distinct vertices are+ * removed, and so are vertices no face uses. Attributes follow the kept elements.+ */+export function mergeByDistance(mesh, distance) {+ const { weldMap, representatives } = weldVertices(mesh.positions, distance);+ const keptCorners = [];+ const keptFaces = [];+ const faceOffsets = [0];+ const corners = [];+ for (let face = 0; face < mesh.faceCount; face++) {+ corners.length = 0;+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const vertex = weldMap[mesh.cornerVertices[corner]];+ if (corners.length && weldMap[mesh.cornerVertices[corners.at(-1)]] === vertex) continue;+ corners.push(corner);+ }+ while (corners.length > 1 && weldMap[mesh.cornerVertices[corners[0]]] === weldMap[mesh.cornerVertices[corners.at(-1)]]) corners.pop();+ const unique = new Set(corners.map(corner => weldMap[mesh.cornerVertices[corner]]));+ if (corners.length < 3 || unique.size !== corners.length) continue;+ keptCorners.push(...corners);+ keptFaces.push(face);+ faceOffsets.push(keptCorners.length);+ }+ if (!keptFaces.length) throw new RangeError('merge_by_distance removed every face. Use a smaller distance.');+ const usedWelded = new Int32Array(representatives.length).fill(-1);+ const keptVertices = [];+ for (const corner of keptCorners) {+ const welded = weldMap[mesh.cornerVertices[corner]];+ if (usedWelded[welded] === -1) {+ usedWelded[welded] = keptVertices.length;+ keptVertices.push(representatives[welded]);+ }+ }+ const positions = new Float32Array(keptVertices.length * 3);+ keptVertices.forEach((vertex, index) => positions.set(mesh.positions.subarray(vertex * 3, vertex * 3 + 3), index * 3));+ const cornerVertices = Uint32Array.from(keptCorners, corner => usedWelded[weldMap[mesh.cornerVertices[corner]]]);+ const offsets = Uint32Array.from(faceOffsets);+ const edges = deriveEdges(keptVertices.length, offsets, cornerVertices);+ const gather = (attribute, sources) => {+ const data = new attribute.data.constructor(sources.length * attribute.size);+ sources.forEach((source, index) => data.set(attribute.data.subarray(source * attribute.size, (source + 1) * attribute.size), index * attribute.size));+ return { data, size: attribute.size };+ };+ const edgeSources = new Uint32Array(edges.edgeCount);+ for (let corner = 0; corner < cornerVertices.length; corner++) edgeSources[edges.cornerEdges[corner]] = mesh.cornerEdges[keptCorners[corner]];+ const attributes = {};+ const sourcesByDomain = { point: keptVertices, edge: edgeSources, face: keptFaces, corner: keptCorners };+ for (const domain of DOMAINS) {+ attributes[domain] = {};+ for (const [name, attribute] of Object.entries(mesh.attributes[domain])) attributes[domain][name] = gather(attribute, sourcesByDomain[domain]);+ }+ const result = createMeshData({+ positions, faceOffsets: offsets, cornerVertices,+ edgeVertices: edges.edgeVertices, cornerEdges: edges.cornerEdges, attributes,+ });+ return { mesh: result, removedVertices: mesh.vertexCount - result.vertexCount, removedFaces: mesh.faceCount - result.faceCount };+}diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsnew file mode 100644index 00000000..66d9db83--- /dev/null+++ b/src/mesh-recipe.js@@ -0,0 +1,175 @@+import { editMesh, meshData } from './mesh-edit.js';+import { countSelected, selectFaces } from './mesh-select.js';+import {+ extrudeFaceRegion, extrudeIndividual, insetRegion, insetIndividual, deleteFaces, flipFaces, translateFaces, mergeByDistance, tagFaces,+ FALLOFF_CURVES,+} from './mesh-ops.js';++// Replayable edit log for agent recipes. Each edit is plain JSON; names follow Blender's bmesh.ops where they match.++export const MAX_MESH_EDITS = 64;+const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;+const MAX_OFFSET = 1e6;++export const MESH_EDIT_OPERATIONS = Object.freeze({+ extrude_face_region: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },+ extrude_individual: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },+ inset_region: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },+ inset_individual: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },+ delete: { fields: ['select'], tags: [] },+ flip_normals: { fields: ['select'], tags: [] },+ translate: { fields: ['select', 'offset', 'falloff'], tags: [] },+ merge_by_distance: { fields: ['distance'], tags: [] },+ tag: { fields: ['select', 'name'], tags: [] },+});++function editError(index, message) {+ return new TypeError(`Mesh edit ${index} (${message})`);+}++function finiteNumber(value, index, label, { minimum = -MAX_OFFSET, maximum = MAX_OFFSET, exclusiveMinimum = false } = {}) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum || (exclusiveMinimum && value === minimum)) {+ throw editError(index, `${label} must be a number ${exclusiveMinimum ? 'above' : 'from'} ${minimum}${maximum < MAX_OFFSET ? ` to ${maximum}` : ''}`);+ }+ return value;+}++function vector(value, index, label) {+ if (!Array.isArray(value) || value.length !== 3) throw editError(index, `${label} needs three numbers`);+ return value.map(component => finiteNumber(component, index, label));+}++/** Validate an edit list without running it. Returns normalized copies with default names filled in. */+export function normalizeMeshEdits(edits) {+ if (!Array.isArray(edits)) throw new TypeError('edits must be an array.');+ if (edits.length > MAX_MESH_EDITS) throw new RangeError(`A mesh holds at most ${MAX_MESH_EDITS} edits. Apply fewer or start from a new base.`);+ return edits.map((edit, index) => {+ if (!edit || typeof edit !== 'object' || Array.isArray(edit)) throw editError(index, 'each edit must be an object');+ const definition = MESH_EDIT_OPERATIONS[edit.op];+ if (!definition) throw editError(index, `op must be one of ${Object.keys(MESH_EDIT_OPERATIONS).join(', ')}`);+ for (const key of Object.keys(edit)) {+ if (key !== 'op' && !definition.fields.includes(key)) throw editError(index, `${edit.op} does not take ${key}; fields: ${definition.fields.join(', ')}`);+ }+ const normalized = { op: edit.op };+ if (definition.fields.includes('select')) {+ if (edit.select === undefined && ['delete', 'tag'].includes(edit.op)) throw editError(index, `${edit.op} needs select`);+ normalized.select = edit.select ?? { all: true };+ }+ if (definition.fields.includes('name')) {+ const name = edit.name ?? (edit.op === 'tag' ? undefined : `${edit.op.split('_')[0]}-${index + 1}`);+ if (typeof name !== 'string' || !NAME_PATTERN.test(name)) throw editError(index, 'name must be 1 to 48 letters, digits, dots, dashes or underscores');+ normalized.name = name;+ }+ switch (edit.op) {+ case 'extrude_face_region':+ case 'extrude_individual':+ normalized.offset = finiteNumber(edit.offset, index, 'offset');+ if (edit.direction !== undefined) normalized.direction = vector(edit.direction, index, 'direction');+ break;+ case 'inset_region':+ case 'inset_individual':+ normalized.thickness = finiteNumber(edit.thickness, index, 'thickness', { minimum: 0, exclusiveMinimum: true });+ normalized.depth = edit.depth === undefined ? 0 : finiteNumber(edit.depth, index, 'depth');+ break;+ case 'translate':+ normalized.offset = vector(edit.offset, index, 'offset');+ if (edit.falloff !== undefined) {+ const falloff = edit.falloff;+ if (!falloff || typeof falloff !== 'object') throw editError(index, 'falloff must be { radius, curve, connected }');+ for (const key of Object.keys(falloff)) {+ if (!['radius', 'curve', 'connected'].includes(key)) throw editError(index, `falloff does not take ${key}`);+ }+ const curve = falloff.curve ?? 'smooth';+ if (!Object.hasOwn(FALLOFF_CURVES, curve)) throw editError(index, `falloff curve must be one of ${Object.keys(FALLOFF_CURVES).join(', ')}`);+ if (falloff.connected !== undefined && typeof falloff.connected !== 'boolean') throw editError(index, 'falloff.connected must be boolean');+ normalized.falloff = {+ radius: finiteNumber(falloff.radius, index, 'falloff.radius', { minimum: 0, exclusiveMinimum: true }),+ curve, connected: falloff.connected ?? false,+ };+ }+ break;+ case 'merge_by_distance':+ normalized.distance = finiteNumber(edit.distance ?? 1e-4, index, 'distance', { minimum: 0, maximum: 1e3 });+ break;+ }+ return normalized;+ });+}++function checkBudget(mesh, limits, index, op) {+ if (mesh.vertexCount > limits.maxVertices || mesh.faceCount > limits.maxFaces) {+ throw new RangeError(`Mesh edit ${index} (${op}) grows the mesh to ${mesh.vertexCount} vertices and ${mesh.faceCount} faces, over the limit of ${limits.maxVertices} vertices or ${limits.maxFaces} faces.`);+ }+}++/**+ * Run an edit log on MeshData. Returns the final mesh and one compact result per edit: how many faces it selected,+ * the tags it created (and their face counts) and the mesh size after it.+ * An edit that selects no faces throws, because silently doing nothing hides a wrong selection from the agent.+ */+export function applyMeshEdits(mesh, edits, { maxVertices = 250_000, maxFaces = 250_000 } = {}) {+ const normalized = normalizeMeshEdits(edits);+ const limits = { maxVertices, maxFaces };+ const results = [];+ let current = mesh;+ normalized.forEach((edit, index) => {+ const result = { op: edit.op };+ if (edit.name) result.name = edit.name;+ if (edit.op === 'merge_by_distance') {+ const merged = mergeByDistance(current, edit.distance);+ current = merged.mesh;+ result.removedVertices = merged.removedVertices;+ result.removedFaces = merged.removedFaces;+ } else {+ let mask;+ try {+ mask = selectFaces(current, edit.select);+ } catch (error) {+ throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);+ }+ const selected = countSelected(mask);+ if (selected === 0) throw new RangeError(`Mesh edit ${index} (${edit.op}) selects no faces. Check the rule with mesh_inspect tags and counts.`);+ result.selected = selected;+ const editable = editMesh(current);+ let created = null;+ switch (edit.op) {+ case 'extrude_face_region':+ created = extrudeFaceRegion(editable, mask, edit);+ break;+ case 'extrude_individual':+ created = extrudeIndividual(editable, mask, edit);+ break;+ case 'inset_region':+ case 'inset_individual': {+ const inset = edit.op === 'inset_region' ? insetRegion(editable, mask, edit) : insetIndividual(editable, mask, edit);+ created = { capFaces: inset.capFaces, sideFaces: inset.sideFaces, sideTag: 'rim' };+ break;+ }+ case 'delete':+ result.deletedFaces = deleteFaces(editable, mask).deletedFaces;+ break;+ case 'flip_normals':+ flipFaces(editable, mask);+ break;+ case 'translate':+ result.movedVertices = translateFaces(editable, mask, edit).movedVertices;+ break;+ case 'tag':+ tagFaces(editable, Array.from(mask.keys()).filter(face => mask[face]), edit.name);+ result.tags = { [edit.name]: selected };+ break;+ }+ if (created) {+ const sideTag = `${edit.name}.${created.sideTag ?? 'side'}`;+ tagFaces(editable, created.capFaces, `${edit.name}.cap`);+ tagFaces(editable, created.sideFaces, sideTag);+ result.tags = { [`${edit.name}.cap`]: created.capFaces.length, [sideTag]: created.sideFaces.length };+ }+ current = meshData(editable);+ }+ checkBudget(current, limits, index, edit.op);+ result.after = { vertices: current.vertexCount, faces: current.faceCount };+ results.push(result);+ });+ return { mesh: current, results };+}diff --git a/src/mesh-select.js b/src/mesh-select.jsnew file mode 100644index 00000000..dc31938c--- /dev/null+++ b/src/mesh-select.js@@ -0,0 +1,197 @@+import { TAG_PREFIX, meshTags } from './mesh-data.js';+import { faceNormals } from './mesh-normals.js';+import { cornerFaces, edgeCornerTable } from './mesh-topology.js';++// Semantic face selection for agents. A rule is plain JSON; the result is a Uint8Array mask with one byte per face.+//+// { "all": true }+// { "tag": "top" } faces carrying a tag (tags double as named selections)+// { "normal": [0, 1, 0], "maxAngle": 10 } faces whose normal is within maxAngle degrees of a direction+// { "inside": { "min": [x, y, z], "max": [x, y, z] } } faces whose centroid lies in a box+// { "faces": [0, 4, 7] } explicit face indices+// { "and": [rule, ...] }, { "or": [rule, ...] }, { "not": rule }+// { "grow": rule, "steps": 1 } add faces sharing an edge, repeated+// { "boundary": rule } faces of the selection that touch an unselected face or an open edge++export const MAX_RULE_DEPTH = 16;+const MAX_RULE_NODES = 256;+const RULE_KEYS = ['all', 'tag', 'normal', 'inside', 'faces', 'and', 'or', 'not', 'grow', 'boundary'];++function ruleError(message) {+ return new TypeError(`Selection rule: ${message}`);+}++function vector3(value, label) {+ if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) throw ruleError(`${label} needs three finite numbers.`);+ return value;+}++function faceCentroids(mesh) {+ const centroids = new Float64Array(mesh.faceCount * 3);+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const vertex = mesh.cornerVertices[corner] * 3;+ centroids[face * 3] += mesh.positions[vertex];+ centroids[face * 3 + 1] += mesh.positions[vertex + 1];+ centroids[face * 3 + 2] += mesh.positions[vertex + 2];+ }+ const size = end - start;+ centroids[face * 3] /= size;+ centroids[face * 3 + 1] /= size;+ centroids[face * 3 + 2] /= size;+ }+ return centroids;+}++/** Faces sharing an edge with each face, as compressed rows (built lazily once per selection call). */+function faceAdjacency(mesh) {+ const table = edgeCornerTable(mesh);+ const facesOfCorners = cornerFaces(mesh);+ const neighbors = Array.from({ length: mesh.faceCount }, () => []);+ const openFaces = new Uint8Array(mesh.faceCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const start = table.edgeOffsets[edge];+ const end = table.edgeOffsets[edge + 1];+ if (end - start === 1) openFaces[facesOfCorners[table.edgeCorners[start]]] = 1;+ for (let first = start; first < end; first++) {+ for (let second = first + 1; second < end; second++) {+ const faceFirst = facesOfCorners[table.edgeCorners[first]];+ const faceSecond = facesOfCorners[table.edgeCorners[second]];+ neighbors[faceFirst].push(faceSecond);+ neighbors[faceSecond].push(faceFirst);+ }+ }+ }+ return { neighbors, openFaces };+}++/**+ * Evaluate a selection rule on a mesh. Throws a TypeError naming the bad part of the rule, and a RangeError for an+ * unknown tag (listing the known ones).+ */+export function selectFaces(mesh, rule) {+ const cache = {};+ let nodes = 0;+ const normals = () => (cache.normals ??= faceNormals(mesh).normals);+ const centroids = () => (cache.centroids ??= faceCentroids(mesh));+ const adjacency = () => (cache.adjacency ??= faceAdjacency(mesh));++ function evaluate(node, depth) {+ nodes++;+ if (nodes > MAX_RULE_NODES) throw ruleError(`more than ${MAX_RULE_NODES} rule nodes.`);+ if (depth > MAX_RULE_DEPTH) throw ruleError(`nesting deeper than ${MAX_RULE_DEPTH}.`);+ if (!node || typeof node !== 'object' || Array.isArray(node)) throw ruleError('each rule must be an object.');+ const keys = Object.keys(node);+ const kind = keys.find(key => RULE_KEYS.includes(key));+ if (!kind) throw ruleError(`use one of ${RULE_KEYS.join(', ')}; got ${keys.join(', ') || 'nothing'}.`);+ const mask = new Uint8Array(mesh.faceCount);+ switch (kind) {+ case 'all':+ if (node.all !== true || keys.length !== 1) throw ruleError('"all" must be true and alone.');+ mask.fill(1);+ return mask;+ case 'tag': {+ if (typeof node.tag !== 'string' || keys.length !== 1) throw ruleError('"tag" needs one tag name.');+ const attribute = mesh.attributes.face[TAG_PREFIX + node.tag];+ if (!attribute) throw new RangeError(`Unknown tag ${node.tag}. Known tags: ${meshTags(mesh).join(', ') || 'none'}.`);+ mask.set(attribute.data);+ return mask;+ }+ case 'normal': {+ const extra = keys.filter(key => key !== 'normal' && key !== 'maxAngle');+ if (extra.length) throw ruleError(`unknown fields ${extra.join(', ')} in a normal rule.`);+ const direction = vector3(node.normal, 'normal');+ const length = Math.hypot(...direction);+ if (length === 0) throw ruleError('normal cannot be zero.');+ const maxAngle = node.maxAngle ?? 10;+ if (!Number.isFinite(maxAngle) || maxAngle < 0 || maxAngle > 180) throw ruleError('maxAngle is degrees from 0 to 180.');+ const limit = Math.cos(maxAngle * Math.PI / 180) - 1e-9;+ const faceNormal = normals();+ for (let face = 0; face < mesh.faceCount; face++) {+ const cosine = (faceNormal[face * 3] * direction[0] + faceNormal[face * 3 + 1] * direction[1] + faceNormal[face * 3 + 2] * direction[2]) / length;+ if (cosine >= limit) mask[face] = 1;+ }+ return mask;+ }+ case 'inside': {+ if (keys.length !== 1 || !node.inside || typeof node.inside !== 'object') throw ruleError('"inside" needs { min, max }.');+ const minimum = vector3(node.inside.min, 'inside.min');+ const maximum = vector3(node.inside.max, 'inside.max');+ const centroid = centroids();+ for (let face = 0; face < mesh.faceCount; face++) {+ let contained = true;+ for (let axis = 0; axis < 3; axis++) {+ const value = centroid[face * 3 + axis];+ if (value < minimum[axis] || value > maximum[axis]) contained = false;+ }+ if (contained) mask[face] = 1;+ }+ return mask;+ }+ case 'faces': {+ if (keys.length !== 1 || !Array.isArray(node.faces) || node.faces.length > mesh.faceCount) throw ruleError('"faces" needs an array of face indices.');+ for (const face of node.faces) {+ if (!Number.isInteger(face) || face < 0 || face >= mesh.faceCount) throw new RangeError(`Face index ${face} is outside 0..${mesh.faceCount - 1}.`);+ mask[face] = 1;+ }+ return mask;+ }+ case 'and':+ case 'or': {+ const children = node[kind];+ if (keys.length !== 1 || !Array.isArray(children) || children.length === 0) throw ruleError(`"${kind}" needs a nonempty array of rules.`);+ if (kind === 'and') mask.fill(1);+ for (const child of children) {+ const childMask = evaluate(child, depth + 1);+ for (let face = 0; face < mesh.faceCount; face++) {+ mask[face] = kind === 'and' ? mask[face] & childMask[face] : mask[face] | childMask[face];+ }+ }+ return mask;+ }+ case 'not': {+ if (keys.length !== 1) throw ruleError('"not" takes one rule.');+ const childMask = evaluate(node.not, depth + 1);+ for (let face = 0; face < mesh.faceCount; face++) mask[face] = childMask[face] ? 0 : 1;+ return mask;+ }+ case 'grow': {+ const extra = keys.filter(key => key !== 'grow' && key !== 'steps');+ if (extra.length) throw ruleError(`unknown fields ${extra.join(', ')} in a grow rule.`);+ const steps = node.steps ?? 1;+ if (!Number.isInteger(steps) || steps < 1 || steps > 64) throw ruleError('grow steps must be an integer from 1 to 64.');+ mask.set(evaluate(node.grow, depth + 1));+ const { neighbors } = adjacency();+ for (let step = 0; step < steps; step++) {+ const previous = mask.slice();+ for (let face = 0; face < mesh.faceCount; face++) {+ if (!previous[face]) continue;+ for (const neighbor of neighbors[face]) mask[neighbor] = 1;+ }+ }+ return mask;+ }+ case 'boundary': {+ if (keys.length !== 1) throw ruleError('"boundary" takes one rule.');+ const inner = evaluate(node.boundary, depth + 1);+ const { neighbors, openFaces } = adjacency();+ for (let face = 0; face < mesh.faceCount; face++) {+ if (!inner[face]) continue;+ if (openFaces[face] || neighbors[face].some(neighbor => !inner[neighbor])) mask[face] = 1;+ }+ return mask;+ }+ }+ throw ruleError(`unsupported rule ${kind}.`);+ }++ return evaluate(rule, 0);+}++export function countSelected(mask) {+ let count = 0;+ for (let index = 0; index < mask.length; index++) count += mask[index];+ return count;+}diff --git a/src/mesh.js b/src/mesh.jsindex bca34a21..ad1dbea1 100644--- a/src/mesh.js+++ b/src/mesh.js@@ -10,4 +10,10 @@ export { faceNormals, cornerNormals } from './mesh-normals.js';export { triangulateMesh, extractRender, gatherRenderPositions } from './mesh-render.js';export { meshFromGeometry, joinTriangles, tagFacesByAxis, weldVertices, rebuildFromCorners, withFaceAttributes } from './mesh-convert.js';export { lintMesh } from './mesh-lint.js';+export { selectFaces, countSelected } from './mesh-select.js';+export { applyMeshEdits, normalizeMeshEdits, MESH_EDIT_OPERATIONS, MAX_MESH_EDITS } from './mesh-recipe.js';+export {+ extrudeFaceRegion, extrudeIndividual, insetRegion, insetIndividual, deleteFaces, flipFaces, translateFaces,+ mergeByDistance, tagFaces, connectedRegions, FALLOFF_CURVES,+} from './mesh-ops.js';export { cornerFaces, cornerCycles, edgeCornerTable, faceParts } from './mesh-topology.js';diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex e6fc3f16..7deb8dcf 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -43,6 +43,12 @@ async function connect(context) {assert.equal(requested, sessionId);return { sessionId, ...scene.inspectMeshes(options) };},+ async editMesh({ sessionId: requested, expectedRevision, geometry, edits, replace }) {+ calls++;+ assert.equal(requested, sessionId);+ scene.apply([{ type: 'edit-mesh', geometry, edits, ...(replace === undefined ? {} : { replace }) }], { expectedRevision });+ return { ...status(), mesh: scene.inspectMeshes({ geometries: [geometry] }).meshes[0] };+ },async apply({ expectedRevision, operations }) {calls++;scene.apply(operations, { expectedRevision });@@ -110,7 +116,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'const { client } = await connect(context);const { tools } = await client.listTools();assert.deepEqual(tools.map(tool => tool.name).sort(), [- 'mesh_inspect', 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose',+ 'mesh_edit', 'mesh_inspect', 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose','scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_review', 'scene_release_checkpoint', 'scene_restore','scene_render_cancel', 'scene_render_release', 'scene_render_result', 'scene_render_status', 'scene_render_submit',].sort());@@ -131,7 +137,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'assert.equal(recipeSchema.properties.materials.maxItems, 256);assert.equal(recipeSchema.properties.geometries.maxItems, 256);const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;- assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']);+ assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']);assert.ok(variants.every(variant => variant.additionalProperties === false));assert.equal(recipeSchema.properties.environment.additionalProperties, false);assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 8);@@ -148,7 +154,7 @@ test('review SDK exposes one image and rejects unknown or unbounded shot fieldsawait client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });const { tools } = await client.listTools();const tool = tools.find(tool => tool.name === 'scene_review');- assert.equal(tools.length, 19);+ assert.equal(tools.length, 20);assert.equal(tool.annotations.readOnlyHint, true);assert.equal(tool.inputSchema.properties.shots.maxItems, 4);assert.equal(tool.inputSchema.properties.shots.items.additionalProperties, false);@@ -228,6 +234,40 @@ test('mesh_inspect reports polygon counts, tags and lint for recipe geometries',await rejected(client, 'mesh_inspect', { sessionId, path: '../file' });});+test('mesh_edit builds a mesh from a base and an edit log through the SDK', async context => {+ const { client, sessionId } = await connect(context);+ await client.callTool({ name: 'scene_create', arguments: { recipe: {+ ...recipe(),+ geometries: [{ id: 'cube', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.1, name: 'lid' },+ ] }],+ } } });+ const edited = await client.callTool({ name: 'mesh_edit', arguments: { sessionId, expectedRevision: 0, geometry: 'cube',+ edits: [{ op: 'extrude_face_region', select: { tag: 'lid.cap' }, offset: 0.25, name: 'knob' }] } });+ assert.equal(edited.isError, undefined, edited.content?.[0]?.text);+ const { revision, mesh } = edited.structuredContent;+ assert.equal(revision, 1);+ assert.equal(mesh.ok, true);+ assert.equal(mesh.parts.closed, 1);+ assert.deepEqual(mesh.edits.map(result => result.tags), [{ 'lid.cap': 1, 'lid.rim': 4 }, { 'knob.cap': 1, 'knob.side': 4 }]);+ assert.equal(mesh.bounds.max[1], 0.75);+ const empty = await client.callTool({ name: 'mesh_edit', arguments: { sessionId, expectedRevision: 1, geometry: 'cube',+ edits: [{ op: 'delete', select: { normal: [0, 1, 0], maxAngle: 0, faces: [] } }] } });+ assert.equal(empty.isError, true);+ const none = await client.callTool({ name: 'mesh_edit', arguments: { sessionId, expectedRevision: 1, geometry: 'cube',+ edits: [{ op: 'delete', select: { tag: 'lid.rim' } }, { op: 'delete', select: { tag: 'lid.rim' } }] } });+ assert.equal(none.isError, true);+ assert.match(none.content[0].text, /Unknown tag lid\.rim|selects no faces/);+ const exported = await client.callTool({ name: 'scene_export_recipe', arguments: { sessionId } });+ assert.equal(exported.structuredContent.recipe.geometries[0].edits.length, 2, 'failed edits leave the log unchanged');+ const replaced = await client.callTool({ name: 'mesh_edit', arguments: { sessionId, expectedRevision: 1, geometry: 'cube', replace: true,+ edits: [{ op: 'extrude_individual', select: { tag: 'side' }, offset: 0.1 }] } });+ assert.equal(replaced.structuredContent.mesh.edits.length, 1);+ await rejected(client, 'mesh_edit', { sessionId, expectedRevision: 2, geometry: 'cube', edits: [{ op: 'bevel', select: { all: true } }] });+ await rejected(client, 'mesh_edit', { sessionId, expectedRevision: 2, geometry: 'cube', edits: [] });+ await rejected(client, 'mesh_edit', { sessionId, expectedRevision: 2, geometry: 'cube', edits: [{ op: 'translate', offset: [0, 1, 0], code: 'run()' }] });+});+test('real SDK round trip authors motion, seeks without revisions and rejects unknown track fields', async context => {const { client, sessionId } = await connect(context);const motion = { duration: 1, tracks: [{ kind: 'node', id: 'mesh', property: 'translation',diff --git a/tests/mesh-edit.test.js b/tests/mesh-edit.test.jsnew file mode 100644index 00000000..50edc30d--- /dev/null+++ b/tests/mesh-edit.test.js@@ -0,0 +1,209 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, sphere, cylinder } from '../src/geometry.js';+import {+ createMeshData, editMesh, validateTopology, meshFromGeometry, lintMesh, facesWithTag, extractRender, meshBounds,+} from '../src/mesh.js';+import { selectFaces, countSelected } from '../src/mesh-select.js';+import { applyMeshEdits, normalizeMeshEdits } from '../src/mesh-recipe.js';+import { createAgentScene } from '../src/agent-scene.js';++const cube = () => meshFromGeometry(box(0, 1));++function quadPlane() {+ return createMeshData({+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 1, 0, -1, 0, 0, -1]),+ faceOffsets: new Uint32Array([0, 4]),+ cornerVertices: new Uint32Array([0, 1, 2, 3]),+ });+}++function edited(mesh, edits) {+ const result = applyMeshEdits(mesh, edits);+ validateTopology(editMesh(result.mesh));+ return result;+}++test('selection rules combine tags, normals, regions and growth', () => {+ const mesh = cube();+ assert.equal(countSelected(selectFaces(mesh, { all: true })), 6);+ assert.equal(countSelected(selectFaces(mesh, { tag: 'side' })), 4);+ assert.equal(countSelected(selectFaces(mesh, { normal: [0, 1, 0], maxAngle: 1 })), 1);+ assert.equal(countSelected(selectFaces(mesh, { normal: [1, 1, 0], maxAngle: 46 })), 2);+ assert.equal(countSelected(selectFaces(mesh, { inside: { min: [0.4, -1, -1], max: [1, 1, 1] } })), 1);+ assert.equal(countSelected(selectFaces(mesh, { and: [{ tag: 'side' }, { not: { tag: 'front' } }] })), 3);+ assert.equal(countSelected(selectFaces(mesh, { or: [{ tag: 'top' }, { tag: 'bottom' }] })), 2);+ assert.equal(countSelected(selectFaces(mesh, { grow: { tag: 'top' } })), 5);+ assert.equal(countSelected(selectFaces(mesh, { boundary: { or: [{ tag: 'top' }, { tag: 'front' }] } })), 2);+ assert.throws(() => selectFaces(mesh, { tag: 'lid' }), /Unknown tag lid\. Known tags: .*top/);+ assert.throws(() => selectFaces(mesh, { colour: 'red' }), /use one of/);+ assert.throws(() => selectFaces(mesh, { faces: [6] }), /outside 0\.\.5/);+ assert.throws(() => selectFaces(mesh, { normal: [0, 1, 0], radius: 2 }), /unknown fields radius/);+});++test('extrude_face_region on a closed box keeps it closed and moves the cap along the normal', () => {+ const { mesh, results } = edited(cube(), [{ op: 'extrude_face_region', select: { tag: 'top' }, offset: 0.5, name: 'tower' }]);+ assert.deepEqual([mesh.vertexCount, mesh.edgeCount, mesh.faceCount], [12, 20, 10]);+ assert.deepEqual(results[0].tags, { 'tower.cap': 1, 'tower.side': 4 });+ assert.equal(meshBounds(mesh).max[1], 1);+ const report = lintMesh(mesh);+ assert.equal(report.ok, true);+ assert.equal(report.parts.closed, 1);+ assert.deepEqual(facesWithTag(mesh, 'top'), facesWithTag(mesh, 'tower.cap'), 'the cap keeps its old tags');+ for (const face of facesWithTag(mesh, 'tower.side')) {+ assert.ok(!facesWithTag(mesh, 'top').includes(face), 'side faces do not inherit base tags');+ }+});++test('extruding a plane gives an open box with outward sides', () => {+ const { mesh } = edited(quadPlane(), [{ op: 'extrude_face_region', offset: 1 }]);+ assert.equal(mesh.faceCount, 5);+ const report = lintMesh(mesh);+ assert.equal(report.problems.length, 1);+ assert.equal(report.problems[0].kind, 'boundary-edge');+ const { geometry } = extractRender(mesh, { sharpAngle: Math.PI / 6 });+ // Sides point away from the centre: their normals agree with the direction from the centre to their vertices.+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ const normal = geometry.normals.subarray(vertex * 3, vertex * 3 + 3);+ if (Math.abs(normal[1]) > 0.5) continue;+ const outward = (geometry.positions[vertex * 3] - 0.5) * normal[0] + (geometry.positions[vertex * 3 + 2] + 0.5) * normal[2];+ assert.ok(outward > 0);+ }+});++test('extrude_face_region extrudes separate groups separately and refuses cancelling regions', () => {+ const { mesh, results } = edited(cube(), [{ op: 'extrude_face_region', select: { or: [{ tag: 'left' }, { tag: 'right' }] }, offset: 0.25 }]);+ assert.deepEqual(results[0].tags, { 'extrude-1.cap': 2, 'extrude-1.side': 8 });+ const bounds = meshBounds(mesh);+ assert.deepEqual([bounds.min[0], bounds.max[0]], [-0.75, 0.75]);+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'extrude_face_region', select: { tag: 'side' }, offset: 1 }]), /extrude_individual/);+ const along = edited(cube(), [{ op: 'extrude_face_region', select: { tag: 'side' }, offset: 1, direction: [0, 1, 0] }]);+ assert.equal(meshBounds(along.mesh).max[1], 1.5);+});++test('extrude_individual and inset_individual handle every face on its own', () => {+ const panels = edited(cube(), [+ { op: 'inset_individual', select: { tag: 'side' }, thickness: 0.1, name: 'panel' },+ { op: 'extrude_individual', select: { tag: 'panel.cap' }, offset: -0.05, name: 'recess' },+ ]);+ assert.deepEqual(panels.results.map(result => result.tags), [+ { 'panel.cap': 4, 'panel.rim': 16 },+ { 'recess.cap': 4, 'recess.side': 16 },+ ]);+ const report = lintMesh(panels.mesh);+ assert.equal(report.ok, true, JSON.stringify(report.problems));+ assert.equal(report.parts.closed, 1);+ const bounds = meshBounds(panels.mesh);+ assert.deepEqual(bounds.max.map(value => Math.round(value * 1e5) / 1e5), [0.5, 0.5, 0.5], 'recesses stay inside the box');+});++test('inset_region keeps an even rim and depth moves the inner face', () => {+ const { mesh } = edited(cube(), [{ op: 'inset_region', select: { tag: 'top' }, thickness: 0.1, depth: -0.2, name: 'well' }]);+ const cap = facesWithTag(mesh, 'well.cap')[0];+ const xs = [];+ for (let corner = mesh.faceOffsets[cap]; corner < mesh.faceOffsets[cap + 1]; corner++) {+ const vertex = mesh.cornerVertices[corner];+ xs.push(Math.abs(mesh.positions[vertex * 3]));+ assert.ok(Math.abs(mesh.positions[vertex * 3 + 1] - 0.3) < 1e-6, 'depth moves the cap down');+ }+ assert.ok(xs.every(value => Math.abs(value - 0.4) < 1e-6), 'corners sit thickness away from both edges');+ assert.equal(lintMesh(mesh).ok, true);+});++test('delete, flip_normals and merge_by_distance report what they changed', () => {+ const opened = edited(cube(), [{ op: 'delete', select: { tag: 'top' } }]);+ assert.equal(opened.results[0].deletedFaces, 1);+ assert.equal(lintMesh(opened.mesh).problems[0].kind, 'boundary-edge');+ const flipped = edited(cube(), [{ op: 'flip_normals' }]);+ assert.equal(lintMesh(flipped.mesh).problems[0].kind, 'inverted-part');+ const twice = edited(cube(), [{ op: 'flip_normals', select: { tag: 'top' } }]);+ assert.ok(lintMesh(twice.mesh).problems.some(problem => problem.kind === 'inconsistent-winding'));+ const loose = meshFromGeometry(box(0, 1), { weld: 0 });+ const merged = applyMeshEdits(loose, [{ op: 'merge_by_distance', distance: 1e-4 }]);+ assert.equal(merged.results[0].removedVertices, 0, 'already welded');+ const split = createMeshData({+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 1, 0, -1, 0, 0, -1, 1.00001, 0, 0, 2, 0, 0, 2, 0, -1, 1.00001, 0, -1]),+ faceOffsets: new Uint32Array([0, 4, 8]),+ cornerVertices: new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7]),+ });+ const welded = edited(split, [{ op: 'merge_by_distance', distance: 1e-3 }]);+ assert.equal(welded.results[0].removedVertices, 2);+ assert.equal(welded.mesh.edgeCount, 7);+});++test('translate with connected falloff moves nearby vertices less', () => {+ const mesh = meshFromGeometry(sphere(16, 8));+ const { mesh: moved } = edited(mesh, [+ { op: 'translate', select: { normal: [0, 1, 0], maxAngle: 30 }, offset: [0, 0.5, 0], falloff: { radius: 1, curve: 'smooth', connected: true } },+ ]);+ const before = meshBounds(mesh);+ const after = meshBounds(moved);+ assert.ok(Math.abs(after.max[1] - before.max[1] - 0.5) < 1e-6);+ assert.ok(Math.abs(after.min[1] - before.min[1]) < 1e-6, 'the far pole stays put');+ let partlyMoved = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const delta = moved.positions[vertex * 3 + 1] - mesh.positions[vertex * 3 + 1];+ if (delta > 1e-4 && delta < 0.499) partlyMoved++;+ }+ assert.ok(partlyMoved > 0);+});++test('edit validation names the op, field and allowed values', () => {+ assert.throws(() => normalizeMeshEdits([{ op: 'bevel' }]), /op must be one of extrude_face_region/);+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, depth: 2 }]), /does not take depth/);+ assert.throws(() => normalizeMeshEdits([{ op: 'inset_region', thickness: 0 }]), /thickness must be a number above 0/);+ assert.throws(() => normalizeMeshEdits([{ op: 'delete' }]), /delete needs select/);+ assert.throws(() => normalizeMeshEdits([{ op: 'tag', select: { all: true }, name: 'bad name' }]), /name must be/);+ assert.throws(() => normalizeMeshEdits([{ op: 'translate', offset: [0, 1, 0], falloff: { radius: 1, curve: 'wobbly' } }]), /curve must be one of smooth/);+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'extrude_individual', select: { tag: 'top' }, offset: 1 }, { op: 'delete', select: { faces: [99] } }]), /Mesh edit 1 \(delete\): Face index 99/);+ assert.throws(() => applyMeshEdits(cube(), Array.from({ length: 8 }, () => ({ op: 'extrude_individual', offset: 0.1 })), { maxFaces: 1000 }), /over the limit/);+});++test('random edit sequences keep a valid topology', () => {+ let seed = 11;+ const random = () => {+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;+ return seed / 0x7fffffff;+ };+ const operations = [+ () => ({ op: 'extrude_individual', select: { faces: [] }, offset: random() - 0.3 }),+ () => ({ op: 'inset_individual', select: { faces: [] }, thickness: 0.02 + random() * 0.05 }),+ () => ({ op: 'extrude_face_region', select: { faces: [] }, offset: random() * 0.2, direction: [0, 1, 0] }),+ () => ({ op: 'translate', select: { faces: [] }, offset: [0, random() * 0.1, 0], falloff: { radius: 0.3, connected: true } }),+ ];+ let mesh = meshFromGeometry(cylinder(12, 0.05, 2));+ for (let step = 0; step < 30; step++) {+ const edit = operations[Math.floor(random() * operations.length)]();+ const count = 1 + Math.floor(random() * 3);+ edit.select = { faces: Array.from({ length: count }, () => Math.floor(random() * mesh.faceCount)) };+ mesh = applyMeshEdits(mesh, [edit], { maxVertices: 1_000_000, maxFaces: 1_000_000 }).mesh;+ validateTopology(editMesh(mesh));+ assert.equal(lintMesh(mesh).problems.filter(problem => problem.kind === 'non-manifold-edge').length, 0);+ }+});++test('recipe mesh geometry renders, reports edits and rejects bad edits atomically', () => {+ const scene = createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, smoothAngle: 30, edits: [+ { op: 'inset_individual', select: { tag: 'side' }, thickness: 0.06, name: 'panel' },+ ] }],+ materials: [{ id: 'wood', color: [0.6, 0.4, 0.2] }],+ nodes: [{ id: 'crate', geometry: 'crate', material: 'wood' }],+ });+ const [report] = scene.inspectMeshes().meshes;+ assert.equal(report.counts.faces, 22, 'mesh_inspect reports the polygon mesh, not re-welded triangles');+ assert.equal(report.edits[0].tags['panel.cap'], 4);+ scene.apply([{ type: 'edit-mesh', geometry: 'crate', edits: [{ op: 'extrude_individual', select: { tag: 'panel.cap' }, offset: -0.03 }] }], { expectedRevision: 0 });+ assert.equal(scene.revision, 1);+ assert.throws(() => scene.apply([{ type: 'edit-mesh', geometry: 'crate', edits: [{ op: 'delete', select: { tag: 'nope' } }] }], { expectedRevision: 1 }), /Unknown tag nope/);+ assert.equal(scene.revision, 1);+ assert.equal(scene.exportRecipe().geometries[0].edits.length, 2);+ assert.throws(() => createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'plain', type: 'box', bevel: 0 }, { id: 'nested', type: 'mesh', base: { type: 'mesh', base: { type: 'box' } } }],+ materials: [], nodes: [],+ }), /mesh base must be a primitive/);+ const plain = createAgentScene({ format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'plain', type: 'box', bevel: 0 }], materials: [], nodes: [] });+ assert.throws(() => plain.apply([{ type: 'edit-mesh', geometry: 'plain', edits: [] }], { expectedRevision: 0 }), /Add a mesh geometry with base/);+});