3D engine that AI agents drive
Name the field, value and an example in mesh edit errors (issue #653)
Nguyen Xuan An878dc861ba65
diff --git a/changes/653-mesh-edits.md b/changes/653-mesh-edits.mdnew file mode 100644index 00000000..24ee649d--- /dev/null+++ b/changes/653-mesh-edits.md@@ -0,0 +1 @@+- Mesh edit validation errors (cut, deform, generator, modifier, normal and attribute edits, and the parameter checks of the edit log) now read `edits[2].divisions: got 9; expected a whole number from 2 to 8, such as 2.`: the field path, the value received and a range, a list of choices or an example. Inside a recipe the path starts at the geometry (`geometries[0].edits[2].levels`). Size-limit errors for subdivide, array and subdivide_edges now name the field to lower (#653)diff --git a/changes/653-mesh-edits.size.md b/changes/653-mesh-edits.size.mdnew file mode 100644index 00000000..e859e994--- /dev/null+++ b/changes/653-mesh-edits.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: 555 bytes gzip of message text and the small mesh-edit-field helper, so that a rejected mesh edit names the edit field, the value received and an example; nothing new runs unless an edit is rejected.diff --git a/src/mesh-attribute-edits.js b/src/mesh-attribute-edits.jsindex d5020bd0..3ee20c38 100644--- a/src/mesh-attribute-edits.js+++ b/src/mesh-attribute-edits.js@@ -2,6 +2,7 @@ import { createMeshData, GROUP_PREFIX, vertexGroupNames } from './mesh-data.js';import { evaluateField, meshFieldContext } from './mesh-fields.js';import { selectedVertices } from './mesh-field-edits.js';import { selectFaces } from './mesh-select.js';+import { editField } from './mesh-edit-field.js';// Vertex colors (the corner attribute "color", three floats in 0 to 1) and vertex groups (the point attributes// "group:<name>", one weight in 0 to 1 per vertex). Both are set by one value, a field expression or a gradient along@@ -12,34 +13,31 @@ export const MAX_VERTEX_GROUPS = 32;const COLOR_ATTRIBUTE = 'color';const AXIS_OFFSETS = Object.freeze({ x: 0, y: 1, z: 2 });-function editError(index, message) {- return new TypeError(`Mesh edit ${index} (${message})`);-}-function unitNumber(value, index, label, finiteNumber) {return finiteNumber(value, index, label, { minimum: 0, maximum: 1 });}function normalizeGradient(gradient, normalized, index, { finiteNumber, valuesKey, readValue }) {+ const example = valuesKey === 'weights' ? '[0, 1]' : '[[1, 0, 0], [0, 0, 1]]';if (!gradient || typeof gradient !== 'object' || Array.isArray(gradient)) {- throw editError(index, `gradient must be { axis, range: [low, high], ${valuesKey}: [atLow, atHigh] }`);+ throw editField(index, 'gradient', gradient, `an object such as { "axis": "z", "range": [0, 1], "${valuesKey}": ${example} }`);}for (const key of Object.keys(gradient)) {- if (!['axis', 'range', valuesKey].includes(key)) throw editError(index, `gradient does not take ${key}; fields: axis, range, ${valuesKey}`);+ if (!['axis', 'range', valuesKey].includes(key)) throw editField(index, `gradient.${key}`, gradient[key], `one of the gradient fields axis, range, ${valuesKey}; remove "${key}"`);}- if (!GRADIENT_AXES.includes(gradient.axis)) throw editError(index, `gradient.axis must be one of ${GRADIENT_AXES.join(', ')}`);- if (!Array.isArray(gradient.range) || gradient.range.length !== 2) throw editError(index, 'gradient.range needs two numbers, low then high');+ if (!GRADIENT_AXES.includes(gradient.axis)) throw editField(index, 'gradient.axis', gradient.axis, `one of ${GRADIENT_AXES.join(', ')}`);+ if (!Array.isArray(gradient.range) || gradient.range.length !== 2) throw editField(index, 'gradient.range', gradient.range, 'an array of two numbers, low then high, such as [0, 1]');const range = gradient.range.map(value => finiteNumber(value, index, 'gradient.range'));- if (!(range[0] < range[1])) throw editError(index, 'gradient.range must have low below high');+ if (!(range[0] < range[1])) throw editField(index, 'gradient.range', range, 'two numbers with low below high, such as [0, 1]');if (!Array.isArray(gradient[valuesKey]) || gradient[valuesKey].length !== 2) {- throw editError(index, `gradient.${valuesKey} needs two entries, the value at the low end then at the high end`);+ throw editField(index, `gradient.${valuesKey}`, gradient[valuesKey], `an array of two entries, the value at the low end then at the high end, such as ${example}`);}normalized.gradient = { axis: gradient.axis, range, [valuesKey]: gradient[valuesKey].map((value, side) => readValue(value, `gradient.${valuesKey}[${side}]`)) };}function rejectSecondSource(edit, index, sources) {const given = sources.filter(source => edit[source] !== undefined);- if (given.length > 1) throw editError(index, `give only one of ${sources.join(', ')}`);+ if (given.length > 1) throw editField(index, given[1], edit[given[1]], `left out, because only one of ${sources.join(', ')} is allowed, such as keeping ${given[0]}`);return given[0];}@@ -60,7 +58,7 @@ export function normalizeVertexGroupEdit(edit, normalized, index, { finiteNumber/** Validate a vertex_color edit: color [r, g, b], a vector field or a two-color gradient (default white). */export function normalizeVertexColorEdit(edit, normalized, index, { finiteNumber, checkedField }) {const readColor = (value, label) => {- if (!Array.isArray(value) || value.length !== 3) throw editError(index, `${label} needs three numbers from 0 to 1`);+ if (!Array.isArray(value) || value.length !== 3) throw editField(index, label, value, 'an array of three numbers from 0 to 1, such as [1, 0.5, 0]');return value.map(channel => unitNumber(channel, index, label, finiteNumber));};const source = rejectSecondSource(edit, index, ['color', 'field', 'gradient']);diff --git a/src/mesh-cut-edits.js b/src/mesh-cut-edits.jsindex 8f5f4a0e..4eb4ba73 100644--- a/src/mesh-cut-edits.js+++ b/src/mesh-cut-edits.js@@ -7,6 +7,8 @@ import { bisectPlane } from './mesh-bisect.js';import { bridgeEdgeLoops, gridFill } from './mesh-bridge.js';import { subdivideEdges, edgeSplitSize } from './mesh-edgesplit.js';import { knifeCut } from './mesh-knife.js';+import { invalidField } from './field-error.js';+import { editField, editInteger, editBoolean, editRuleObject } from './mesh-edit-field.js';// The cutting edits as recipe operations: validation of their fields and running them on MeshData. The geometry lives// in the modules imported above; this file only connects it to the edit log.@@ -19,28 +21,15 @@ export const CUT_OPERATIONS = Object.freeze([const MAX_PATH_POINTS = 256;const EDGE_RULE_HINT = 'an edge rule such as { "all": true }, { "angle": 30 }, { "along": [x, y, z] } or { "open": true }';-function ruleObject(value, index, label, hint) {- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`Mesh edit ${index} (${label} must be ${hint})`);- return value;-}--function integerInRange(value, index, label, minimum, maximum) {- if (!Number.isInteger(value) || value < minimum || value > maximum) {- throw new TypeError(`Mesh edit ${index} (${label} must be an integer from ${minimum} to ${maximum})`);- }- return value;-}-function booleanField(value, index, label) {- if (value !== undefined && typeof value !== 'boolean') throw new TypeError(`Mesh edit ${index} (${label} must be boolean)`);- return value ?? false;+ return editBoolean(value, index, label) ?? false;}/** Fill in `normalized` for a cutting edit, throwing a TypeError that names the edit when a field is wrong. */export function normalizeCutEdit(edit, normalized, index, { finiteNumber, vector }) {switch (edit.op) {case 'fill_holes':- if (edit.sides !== undefined) normalized.sides = integerInRange(edit.sides, index, 'sides', 3, 4096);+ if (edit.sides !== undefined) normalized.sides = editInteger(edit.sides, index, 'sides', 3, 4096);break;case 'dissolve_faces':break;@@ -48,41 +37,41 @@ export function normalizeCutEdit(edit, normalized, index, { finiteNumber, vectorcase 'bridge_edge_loops':case 'subdivide_edges':case 'grid_fill':- normalized.edges = ruleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);+ normalized.edges = editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);break;case 'dissolve_verts':- normalized.verts = ruleObject(edit.verts, index, 'verts', 'a vertex rule: { "all": true }, { "vertices": [indices] }, { "valence": 2 } or { "inside": { "min": [x, y, z], "max": [x, y, z] } }');+ normalized.verts = editRuleObject(edit.verts, index, 'verts', 'a vertex rule such as { "all": true }, { "vertices": [0, 1] }, { "valence": 2 } or { "inside": { "min": [x, y, z], "max": [x, y, z] } }');break;case 'dissolve_limited':- normalized.edges = edit.edges === undefined ? { all: true } : ruleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);+ normalized.edges = edit.edges === undefined ? { all: true } : editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);normalized.angle = edit.angle === undefined ? 5 : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });break;case 'bisect_plane':normalized.point = vector(edit.point, index, 'point');normalized.normal = vector(edit.normal, index, 'normal');- if (normalized.normal.every(component => component === 0)) throw new TypeError(`Mesh edit ${index} (normal cannot be zero)`);+ if (normalized.normal.every(component => component === 0)) throw editField(index, 'normal', normalized.normal, 'a direction with at least one nonzero number, such as [0, 0, 1]');normalized.distance = edit.distance === undefined ? 1e-4 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1e3 });normalized.clearInner = booleanField(edit.clearInner, index, 'clearInner');normalized.clearOuter = booleanField(edit.clearOuter, index, 'clearOuter');normalized.fill = booleanField(edit.fill, index, 'fill');- if (normalized.clearInner && normalized.clearOuter) throw new TypeError(`Mesh edit ${index} (clearInner and clearOuter together would remove everything)`);+ if (normalized.clearInner && normalized.clearOuter) throw editField(index, 'clearOuter', true, 'false when clearInner is true, such as clearOuter false (both together would remove everything)');break;case 'bridge_edge_loops':break;case 'knife_project':if (!Array.isArray(edit.path) || edit.path.length < 2 || edit.path.length > MAX_PATH_POINTS) {- throw new TypeError(`Mesh edit ${index} (path needs 2 to ${MAX_PATH_POINTS} points [x, y, z] in object space)`);+ throw editField(index, 'path', edit.path, `an array of 2 to ${MAX_PATH_POINTS} points in object space, such as [[0, 0, 0], [1, 0, 0]]`);}- normalized.path = edit.path.map(point => vector(point, index, 'path point'));+ normalized.path = edit.path.map(point => vector(point, index, 'path'));normalized.direction = vector(edit.direction, index, 'direction');- if (normalized.direction.every(component => component === 0)) throw new TypeError(`Mesh edit ${index} (direction cannot be zero)`);+ if (normalized.direction.every(component => component === 0)) throw editField(index, 'direction', normalized.direction, 'a direction with at least one nonzero number, such as [0, 0, -1]');break;}if (edit.op === 'bridge_edge_loops') {- normalized.segments = edit.segments === undefined ? 1 : integerInRange(edit.segments, index, 'segments', 1, 64);- normalized.twistOffset = edit.twistOffset === undefined ? 0 : integerInRange(edit.twistOffset, index, 'twistOffset', -4096, 4096);+ normalized.segments = edit.segments === undefined ? 1 : editInteger(edit.segments, index, 'segments', 1, 64);+ normalized.twistOffset = edit.twistOffset === undefined ? 0 : editInteger(edit.twistOffset, index, 'twistOffset', -4096, 4096);}- if (edit.op === 'subdivide_edges') normalized.cuts = edit.cuts === undefined ? 1 : integerInRange(edit.cuts, index, 'cuts', 1, 16);+ if (edit.op === 'subdivide_edges') normalized.cuts = edit.cuts === undefined ? 1 : editInteger(edit.cuts, index, 'cuts', 1, 16);}/** Refuse a subdivide_edges that would grow past the limits, before it allocates anything. */@@ -91,7 +80,7 @@ export function checkCutBudget(mesh, edit, limits, index) {const mask = selectEdges(mesh, edit.edges, edgeFaces(mesh));const size = edgeSplitSize(mesh, mask, edit.cuts);if (size.vertices > limits.maxVertices || size.faces > limits.maxFaces) {- throw new RangeError(`Mesh edit ${index} (subdivide_edges) would make up to ${size.vertices} vertices and ${size.faces} faces, over the limit of ${limits.maxVertices} vertices and ${limits.maxFaces} faces. Lower cuts or select fewer edges.`);+ throw editField(index, 'cuts', edit.cuts, `a number of cuts that keeps the mesh within ${limits.maxVertices} vertices and ${limits.maxFaces} faces (this edit would make up to ${size.vertices} vertices and ${size.faces} faces), such as 1, or select fewer edges`, RangeError);}}@@ -108,7 +97,7 @@ export function runCutEdit(mesh, edit) {}case 'dissolve_faces': {const mask = selectFaces(mesh, edit.select);- if (countSelected(mask) === 0) throw new RangeError('The rule selects no faces. Check it with mesh_inspect tags and counts.');+ if (countSelected(mask) === 0) throw invalidField('select', edit.select, 'a rule that matches at least one face, such as { "all": true } (check tags and counts with mesh_inspect)');const outcome = dissolveFaces(mesh, mask, { name: edit.name });return { mesh: outcome.mesh, result: { merged: outcome.merged } };}diff --git a/src/mesh-deform-modifiers.js b/src/mesh-deform-modifiers.jsindex ad586234..fa862e75 100644--- a/src/mesh-deform-modifiers.js+++ b/src/mesh-deform-modifiers.js@@ -1,5 +1,7 @@import { withPositions } from './mesh-field-edits.js';import { vertexNormals } from './mesh-normals.js';+import { invalidField } from './field-error.js';+import { editField, editInteger, editBoolean, editAxis } from './mesh-edit-field.js';// Modifiers that only move vertices, each from a few numbers: lattice (a coarse grid of moved control points), curve (bend// along a path), hook (pull the vertices near a point) and wave (a travelling ripple). Every list is bounded, and the@@ -150,7 +152,7 @@ function sampleCurve(path, upAxis) {for (let index = 1; index < points.length; index++) {distances.push(distances[index - 1] + Math.hypot(...points[index].map((value, axis) => value - points[index - 1][axis])));}- if (!(distances.at(-1) > MINIMUM_SPAN)) throw new RangeError('curve path has no length. Give points that are apart.');+ if (!(distances.at(-1) > MINIMUM_SPAN)) throw invalidField('path', path, 'points that are apart, such as [[0, 0, 0], [0, 0, 2]]');const tangents = points.map((point, index) => {const ahead = points[Math.min(index + 1, points.length - 1)];const behind = points[Math.max(index - 1, 0)];@@ -216,31 +218,31 @@ export function curveDeform(mesh, { path, axis }) {}function checkedVector(value, index, label, finiteNumber) {- if (!Array.isArray(value) || value.length !== 3) throw new TypeError(`Mesh edit ${index} (${label} needs three numbers)`);+ if (!Array.isArray(value) || value.length !== 3) throw editField(index, label, value, 'an array of three numbers, such as [0, 1, 0]');return value.map(component => finiteNumber(component, index, label));}-function normalizeLattice(edit, normalized, index, { finiteNumber, integerInRange }) {+function normalizeLattice(edit, normalized, index, { finiteNumber }) {const divisions = edit.divisions ?? [2, 2, 2];- if (!Array.isArray(divisions) || divisions.length !== 3) throw new TypeError(`Mesh edit ${index} (divisions needs three integers from 2 to ${MAX_LATTICE_DIVISIONS})`);- normalized.divisions = divisions.map(count => integerInRange(count, index, 'divisions', 2, MAX_LATTICE_DIVISIONS));+ if (!Array.isArray(divisions) || divisions.length !== 3) throw editField(index, 'divisions', divisions, `an array of three whole numbers from 2 to ${MAX_LATTICE_DIVISIONS}, such as [2, 2, 2]`);+ normalized.divisions = divisions.map(count => editInteger(count, index, 'divisions', 2, MAX_LATTICE_DIVISIONS));const moves = edit.moves ?? [];- if (!Array.isArray(moves) || moves.length > MAX_LATTICE_MOVES) throw new RangeError(`Mesh edit ${index} (moves is a list of at most ${MAX_LATTICE_MOVES} of { point, offset })`);+ if (!Array.isArray(moves) || moves.length > MAX_LATTICE_MOVES) throw editField(index, 'moves', moves, `a list of at most ${MAX_LATTICE_MOVES} moves, such as [{ "point": [0, 0, 0], "offset": [0, 0, 1] }]`, RangeError);normalized.moves = moves.map((move, moveIndex) => {- if (!move || typeof move !== 'object' || Array.isArray(move)) throw new TypeError(`Mesh edit ${index} (moves[${moveIndex}] must be { point, offset })`);- if (!Array.isArray(move.point) || move.point.length !== 3) throw new TypeError(`Mesh edit ${index} (moves[${moveIndex}].point needs three grid indices)`);- const point = move.point.map((cell, axis) => integerInRange(cell, index, `moves[${moveIndex}].point`, 0, normalized.divisions[axis] - 1));+ if (!move || typeof move !== 'object' || Array.isArray(move)) throw editField(index, `moves[${moveIndex}]`, move, 'an object such as { "point": [0, 0, 0], "offset": [0, 0, 1] }');+ if (!Array.isArray(move.point) || move.point.length !== 3) throw editField(index, `moves[${moveIndex}].point`, move.point, 'three grid indices, such as [0, 1, 0]');+ const point = move.point.map((cell, axis) => editInteger(cell, index, `moves[${moveIndex}].point`, 0, normalized.divisions[axis] - 1));return { point, offset: checkedVector(move.offset, index, `moves[${moveIndex}].offset`, finiteNumber) };});}function normalizeCurve(edit, normalized, index, { finiteNumber }) {if (!Array.isArray(edit.path) || edit.path.length < 2 || edit.path.length > MAX_CURVE_POINTS) {- throw new TypeError(`Mesh edit ${index} (path needs 2 to ${MAX_CURVE_POINTS} points of three numbers)`);+ throw editField(index, 'path', edit.path, `an array of 2 to ${MAX_CURVE_POINTS} points of three numbers, such as [[0, 0, 0], [0, 0, 2]]`);}normalized.path = edit.path.map(point => checkedVector(point, index, 'path', finiteNumber));normalized.axis = edit.axis ?? 'x';- if (!Object.hasOwn(AXIS_NAMES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);+ editAxis(normalized.axis, index);}function normalizeHook(edit, normalized, index, { finiteNumber }) {@@ -249,7 +251,7 @@ function normalizeHook(edit, normalized, index, { finiteNumber }) {normalized.translation = checkedVector(edit.translation ?? [0, 0, 0], index, 'translation', finiteNumber);normalized.strength = edit.strength === undefined ? 1 : finiteNumber(edit.strength, index, 'strength', { minimum: 0, maximum: 1 });normalized.falloff = edit.falloff ?? 'smooth';- if (!HOOK_FALLOFFS.includes(normalized.falloff)) throw new TypeError(`Mesh edit ${index} (falloff must be one of ${HOOK_FALLOFFS.join(', ')})`);+ if (!HOOK_FALLOFFS.includes(normalized.falloff)) throw editField(index, 'falloff', normalized.falloff, `one of ${HOOK_FALLOFFS.join(', ')}`);}function normalizeWave(edit, normalized, index, { finiteNumber }) {@@ -260,13 +262,14 @@ function normalizeWave(edit, normalized, index, { finiteNumber }) {normalized.time = edit.time === undefined ? 0 : finiteNumber(edit.time, index, 'time', { minimum: -1e6, maximum: 1e6 });normalized.timeOffset = edit.timeOffset === undefined ? 0 : finiteNumber(edit.timeOffset, index, 'timeOffset', { minimum: -1e6, maximum: 1e6 });const start = edit.start ?? [0, 0];- if (!Array.isArray(start) || start.length !== 2) throw new TypeError(`Mesh edit ${index} (start needs two numbers, x and y)`);+ if (!Array.isArray(start) || start.length !== 2) throw editField(index, 'start', start, 'an array of two numbers, x and y, such as [0, 0]');normalized.start = start.map(value => finiteNumber(value, index, 'start'));normalized.cyclic = edit.cyclic ?? true;normalized.normal = edit.normal ?? false;- if (typeof normalized.cyclic !== 'boolean' || typeof normalized.normal !== 'boolean') throw new TypeError(`Mesh edit ${index} (cyclic and normal must be booleans)`);+ editBoolean(normalized.cyclic, index, 'cyclic');+ editBoolean(normalized.normal, index, 'normal');normalized.axes = edit.axes ?? 'xy';- if (!WAVE_AXES.includes(normalized.axes)) throw new TypeError(`Mesh edit ${index} (axes must be one of ${WAVE_AXES.join(', ')})`);+ if (!WAVE_AXES.includes(normalized.axes)) throw editField(index, 'axes', normalized.axes, `one of ${WAVE_AXES.join(', ')}`);}const NORMALIZERS = Object.freeze({ lattice: normalizeLattice, curve: normalizeCurve, hook: normalizeHook, wave: normalizeWave });diff --git a/src/mesh-edit-field.js b/src/mesh-edit-field.jsnew file mode 100644index 00000000..d38dbf81--- /dev/null+++ b/src/mesh-edit-field.js@@ -0,0 +1,32 @@+import { invalidField } from './field-error.js';++// Shared validation errors for the fields of one mesh edit. The path is edits[index].field, which the recipe and the+// edit-mesh operation both extend to a full path when the edit sits inside a geometry.++export function editField(index, field, value, expected, ErrorType = TypeError) {+ return invalidField(`edits[${index}].${field}`, value, expected, ErrorType);+}++export function editInteger(value, index, label, minimum, maximum) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw editField(index, label, value, `a whole number from ${minimum} to ${maximum}, such as ${Math.min(Math.max(1, minimum), maximum)}`);+ }+ return value;+}++export function editBoolean(value, index, label) {+ if (value !== undefined && typeof value !== 'boolean') throw editField(index, label, value, 'true or false');+ return value;+}++const AXES = ['x', 'y', 'z'];++export function editAxis(value, index, label = 'axis') {+ if (!AXES.includes(value)) throw editField(index, label, value, 'one of "x", "y", "z"');+ return value;+}++export function editRuleObject(value, index, label, hint) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw editField(index, label, value, hint);+ return value;+}diff --git a/src/mesh-generator-modifiers.js b/src/mesh-generator-modifiers.jsindex 5c49d1a5..2f75715d 100644--- a/src/mesh-generator-modifiers.js+++ b/src/mesh-generator-modifiers.js@@ -1,6 +1,8 @@import { createMeshData } from './mesh-data.js';import { vertexNormals, faceNormals } from './mesh-normals.js';import { evaluateField, meshFieldContext } from './mesh-fields.js';+import { invalidField } from './field-error.js';+import { editInteger, editBoolean, editAxis } from './mesh-edit-field.js';// Modifiers that build new surface from the mesh they are given: screw revolves its edges, wireframe turns its faces into// struts and skin puts a square tube on every edge. Each one checks the size of its result against the limits before it@@ -173,7 +175,7 @@ function skinRadii(mesh, radius) {const { values } = evaluateField(radius, meshFieldContext(mesh, 'point'), { kind: 'scalar' });for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {if (!(values[vertex] > 0) || !Number.isFinite(values[vertex])) {- throw new RangeError(`skin radius must be above zero at every vertex; vertex ${vertex} has ${values[vertex]}. Change the radius field, for example wrap it in max.`);+ throw invalidField('radius', values[vertex], `above 0 at every vertex, such as 0.1 (vertex ${vertex} breaks this); change the radius field, for example wrap it in max`);}}return values;@@ -227,14 +229,14 @@ export function skinMesh(mesh, { radius }, limits) {};}-export function normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField }) {+export function normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, checkedField }) {switch (edit.op) {case 'screw':normalized.axis = edit.axis ?? 'z';- if (!Object.hasOwn(AXIS_NAMES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);+ editAxis(normalized.axis, index);normalized.angle = edit.angle === undefined ? 360 : finiteNumber(edit.angle, index, 'angle', { minimum: -3600, maximum: 3600 });- normalized.steps = edit.steps === undefined ? 16 : integerInRange(edit.steps, index, 'steps', 1, MAX_SCREW_STEPS);- normalized.iterations = edit.iterations === undefined ? 1 : integerInRange(edit.iterations, index, 'iterations', 1, MAX_SCREW_ITERATIONS);+ normalized.steps = edit.steps === undefined ? 16 : editInteger(edit.steps, index, 'steps', 1, MAX_SCREW_STEPS);+ normalized.iterations = edit.iterations === undefined ? 1 : editInteger(edit.iterations, index, 'iterations', 1, MAX_SCREW_ITERATIONS);normalized.lift = edit.lift === undefined ? 0 : finiteNumber(edit.lift, index, 'lift', { minimum: -1e4, maximum: 1e4 });break;case 'wireframe':@@ -242,9 +244,8 @@ export function normalizeGeneratorEdit(edit, normalized, index, { finiteNumber,normalized.offset = edit.offset === undefined ? 0 : finiteNumber(edit.offset, index, 'offset', { minimum: -1, maximum: 1 });normalized.evenOffset = edit.evenOffset ?? true;normalized.replace = edit.replace ?? true;- if (typeof normalized.evenOffset !== 'boolean' || typeof normalized.replace !== 'boolean') {- throw new TypeError(`Mesh edit ${index} (evenOffset and replace must be booleans)`);- }+ editBoolean(normalized.evenOffset, index, 'evenOffset');+ editBoolean(normalized.replace, index, 'replace');break;case 'skin':if (edit.radius === undefined) {diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.jsindex 334ac628..95575c77 100644--- a/src/mesh-modifiers.js+++ b/src/mesh-modifiers.js@@ -2,6 +2,7 @@ import { withPositions } from './mesh-field-edits.js';import { mergeByDistance } from './mesh-ops.js';import { triangulateFaces, splitSharpEdges } from './mesh-restructure.js';import { MODIFIER_OPERATIONS } from './mesh-operations.js';+import { editField, editInteger, editAxis } from './mesh-edit-field.js';import { normalizeGeneratorEdit, GENERATOR_RUNNERS } from './mesh-generator-modifiers.js';import { normalizeNormalEdit, NORMAL_RUNNERS } from './mesh-normal-modifiers.js';import { isDeformModifier, normalizeDeformEdit, runDeformEdit } from './mesh-deform-modifiers.js';@@ -18,37 +19,30 @@ export function isModifierOperation(operation) {return Object.hasOwn(MODIFIER_OPERATIONS, operation);}-function integerInRange(value, index, label, minimum, maximum) {- if (!Number.isInteger(value) || value < minimum || value > maximum) {- throw new TypeError(`Mesh edit ${index} (${label} must be an integer from ${minimum} to ${maximum})`);- }- return value;-}--function rejectField(edit, index, field, reason) {- if (edit[field] !== undefined) throw new TypeError(`Mesh edit ${index} (${edit.op} ${edit.mode ?? ''} does not take ${field}: ${reason})`);+function rejectField(edit, index, field, usedInstead) {+ if (edit[field] !== undefined) throw editField(index, field, edit[field], `left out, because ${edit.op} ${edit.mode} takes ${usedInstead}`);}function normalizeSimpleDeform(edit, normalized, index, finiteNumber) {if (!SIMPLE_DEFORM_MODES.includes(edit.mode)) {- throw new TypeError(`Mesh edit ${index} (mode must be one of ${SIMPLE_DEFORM_MODES.join(', ')})`);+ throw editField(index, 'mode', edit.mode, `one of ${SIMPLE_DEFORM_MODES.join(', ')}`);}normalized.mode = edit.mode;normalized.axis = edit.axis ?? 'z';- if (!Object.hasOwn(AXIS_NAMES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);+ editAxis(normalized.axis, index);if (edit.mode === 'twist' || edit.mode === 'bend') {- rejectField(edit, index, 'factor', 'it uses angle in degrees');+ rejectField(edit, index, 'factor', 'angle in degrees, such as "angle": 45');normalized.angle = edit.angle === undefined ? 45 : finiteNumber(edit.angle, index, 'angle', { minimum: -3600, maximum: 3600 });return;}- rejectField(edit, index, 'angle', 'it uses factor');+ rejectField(edit, index, 'angle', 'factor, such as "factor": 0.5');normalized.factor = edit.factor === undefined ? 0.5 : finiteNumber(edit.factor, index, 'factor', { minimum: -10, maximum: 10 });}/** Fill in `normalized` for a modifier edit, throwing a TypeError that names the edit when a field is wrong. */export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, checkedField }) {if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) {- normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField });+ normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, checkedField });return;}if (Object.hasOwn(NORMAL_RUNNERS, edit.op)) {@@ -56,7 +50,7 @@ export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, creturn;}if (isDeformModifier(edit.op)) {- normalizeDeformEdit(edit, normalized, index, { finiteNumber, integerInRange });+ normalizeDeformEdit(edit, normalized, index, { finiteNumber });return;}switch (edit.op) {@@ -64,14 +58,14 @@ export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, cnormalized.distance = edit.distance === undefined ? 0.001 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1e3, exclusiveMinimum: true });break;case 'triangulate':- normalized.minVertices = edit.minVertices === undefined ? 4 : integerInRange(edit.minVertices, index, 'minVertices', 4, 4096);+ normalized.minVertices = edit.minVertices === undefined ? 4 : editInteger(edit.minVertices, index, 'minVertices', 4, 4096);break;case 'edge_split':normalized.angle = edit.angle === undefined ? 30 : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });break;case 'smooth':normalized.factor = edit.factor === undefined ? 0.5 : finiteNumber(edit.factor, index, 'factor', { minimum: -2, maximum: 2 });- normalized.iterations = edit.iterations === undefined ? 1 : integerInRange(edit.iterations, index, 'iterations', 1, MAX_SMOOTH_ITERATIONS);+ normalized.iterations = edit.iterations === undefined ? 1 : editInteger(edit.iterations, index, 'iterations', 1, MAX_SMOOTH_ITERATIONS);break;case 'simple_deform':normalizeSimpleDeform(edit, normalized, index, finiteNumber);diff --git a/src/mesh-normal-modifiers.js b/src/mesh-normal-modifiers.jsindex bbf8f91d..a6c12b3e 100644--- a/src/mesh-normal-modifiers.js+++ b/src/mesh-normal-modifiers.js@@ -1,6 +1,7 @@import { createMeshData } from './mesh-data.js';import { faceNormals, cornerNormals } from './mesh-normals.js';import { edgeCornerTable, cornerFaces } from './mesh-topology.js';+import { editBoolean } from './mesh-edit-field.js';// Modifiers that decide how a mesh is shaded without moving it. smooth_by_angle writes the edge attributes `sharp` and// `smooth` that corner normals read, weighted_normal writes one normal per corner that the render extraction uses as is.@@ -80,8 +81,7 @@ export function weightedNormals(mesh, { angle, weight }) {export function normalizeNormalEdit(edit, normalized, index, { finiteNumber }) {normalized.angle = edit.angle === undefined ? DEFAULT_NORMAL_ANGLE : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });if (edit.op === 'smooth_by_angle') {- normalized.ignoreSharp = edit.ignoreSharp ?? false;- if (typeof normalized.ignoreSharp !== 'boolean') throw new TypeError(`Mesh edit ${index} (ignoreSharp must be a boolean)`);+ normalized.ignoreSharp = editBoolean(edit.ignoreSharp, index, 'ignoreSharp') ?? false;return;}normalized.weight = edit.weight === undefined ? WEIGHT_REFERENCE : finiteNumber(edit.weight, index, 'weight', { minimum: 1, maximum: MAXIMUM_NORMAL_WEIGHT });diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex 6d49c3e8..40ec2495 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -1,5 +1,6 @@import { editMesh, meshData } from './mesh-edit.js';import { invalidField } from './field-error.js';+import { editField } from './mesh-edit-field.js';import { countSelected, selectFaces } from './mesh-select.js';import {extrudeFaceRegion, extrudeIndividual, insetRegion, insetIndividual, deleteFaces, flipFaces, translateFaces, mergeByDistance, tagFaces,@@ -38,10 +39,6 @@ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;const MAX_OFFSET = 1e6;-function editField(index, field, value, expected) {- return invalidField(`edits[${index}].${field}`, value, expected, TypeError);-}-// A failure inside an edit keeps its field path when it has one, so the agent sees edits[2].maxDistance, and otherwise// gets the edit position and name in front of the message.function editFailure(error, index, label) {@@ -53,10 +50,6 @@ function editFailure(error, index, label) {return new error.constructor(`Mesh edit ${index} (${label}): ${error.message}`);}-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 editField(index, label, value, `a number ${exclusiveMinimum ? 'above' : 'from'} ${minimum}${maximum < MAX_OFFSET ? ` to ${maximum}` : ''}, such as ${exclusiveMinimum ? minimum + 1 : Math.min(Math.max(1, minimum), maximum)}`);@@ -73,7 +66,7 @@ function checkedField(expression, index, label, kind) {try {validateField(expression, { kind });} catch (error) {- throw editError(index, `${label}: ${error.message}`);+ throw editField(index, label, expression, `a ${kind} field expression such as ${kind === 'vector' ? '[0, 1, 0]' : '0.5'} (${error.message})`);}return expression;}@@ -82,55 +75,55 @@ function checkedField(expression, index, label, kind) {function normalizePlacement(edit, normalized, index) {normalized.translation = edit.translation === undefined ? [0, 0, 0] : vector(edit.translation, index, 'translation');normalized.scale = edit.scale === undefined ? [1, 1, 1] : vector(edit.scale, index, 'scale');- if (normalized.scale.some(value => value <= 0)) throw editError(index, 'scale components must be positive');+ if (normalized.scale.some(value => value <= 0)) throw editField(index, 'scale', normalized.scale, 'three numbers above 0, such as [1, 1, 1]');if (edit.rotation === undefined) {normalized.rotation = [0, 0, 0, 1];return;}- if (!Array.isArray(edit.rotation) || edit.rotation.length !== 4) throw editError(index, 'rotation is an XYZW quaternion');+ if (!Array.isArray(edit.rotation) || edit.rotation.length !== 4) throw editField(index, 'rotation', edit.rotation, 'an XYZW quaternion of four numbers, such as [0, 0, 0, 1]');const rotation = edit.rotation.map(component => finiteNumber(component, index, 'rotation'));const length = Math.hypot(...rotation);- if (length === 0) throw editError(index, 'rotation quaternion must be nonzero');+ if (length === 0) throw editField(index, 'rotation', rotation, 'a nonzero XYZW quaternion, such as [0, 0, 0, 1]');normalized.rotation = rotation.map(component => component / length);}function normalizeStroke(stroke, index, strokeIndex) {const label = `strokes[${strokeIndex}]`;- if (!stroke || typeof stroke !== 'object' || Array.isArray(stroke)) throw editError(index, `${label} must be an object`);+ if (!stroke || typeof stroke !== 'object' || Array.isArray(stroke)) throw editField(index, label, stroke, `an object such as { "type": "${SCULPT_STROKE_TYPES[0]}", "center": [0, 0, 0], "radius": 0.5, "strength": 0.2 }`);for (const key of Object.keys(stroke)) {- if (!['type', 'center', 'radius', 'strength', 'direction'].includes(key)) throw editError(index, `${label} does not take ${key}; fields: type, center, radius, strength, direction`);+ if (!['type', 'center', 'radius', 'strength', 'direction'].includes(key)) throw editField(index, `${label}.${key}`, stroke[key], `one of the stroke fields type, center, radius, strength, direction; remove "${key}"`);}- if (!SCULPT_STROKE_TYPES.includes(stroke.type)) throw editError(index, `${label}.type must be one of ${SCULPT_STROKE_TYPES.join(', ')}`);+ if (!SCULPT_STROKE_TYPES.includes(stroke.type)) throw editField(index, `${label}.type`, stroke.type, `one of ${SCULPT_STROKE_TYPES.join(', ')}`);const normalized = {type: stroke.type,center: vector(stroke.center, index, `${label}.center`),radius: finiteNumber(stroke.radius, index, `${label}.radius`, { minimum: 0, exclusiveMinimum: true }),strength: finiteNumber(stroke.strength, index, `${label}.strength`),};- if (stroke.type === 'smooth' && (normalized.strength < 0 || normalized.strength > 1)) throw editError(index, `${label}.strength of a smooth stroke is from 0 to 1`);+ if (stroke.type === 'smooth' && (normalized.strength < 0 || normalized.strength > 1)) throw editField(index, `${label}.strength`, normalized.strength, 'a number from 0 to 1 for a smooth stroke, such as 0.5');if (stroke.type === 'displace') {normalized.direction = vector(stroke.direction, index, `${label}.direction`);- if (normalized.direction.every(component => component === 0)) throw editError(index, `${label}.direction must be nonzero`);+ if (normalized.direction.every(component => component === 0)) throw editField(index, `${label}.direction`, normalized.direction, 'a nonzero direction, such as [0, 0, 1]');} else if (stroke.direction !== undefined) {- throw editError(index, `${label}.direction applies only to a displace stroke`);+ throw editField(index, `${label}.direction`, stroke.direction, 'left out, because only a displace stroke takes direction');}return normalized;}/** 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 (!Array.isArray(edits)) throw invalidField('edits', edits, 'an array of edits, such as [{ "op": "subdivide", "levels": 1 }]', TypeError);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');+ if (!edit || typeof edit !== 'object' || Array.isArray(edit)) throw invalidField(`edits[${index}]`, edit, 'an object such as { "op": "subdivide", "levels": 1 }', TypeError);const definition = MESH_EDIT_OPERATIONS[edit.op];if (!definition) throw editField(index, 'op', edit.op, `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(', ')}`);+ if (key !== 'op' && !definition.fields.includes(key)) throw editField(index, key, edit[key], `one of the fields ${edit.op} takes: ${definition.fields.join(', ')}; remove "${key}"`);}const normalized = { op: edit.op };if (definition.fields.includes('select')) {- if (edit.select === undefined && ['delete', 'tag', 'dissolve_faces'].includes(edit.op)) throw editError(index, `${edit.op} needs select`);+ if (edit.select === undefined && ['delete', 'tag', 'dissolve_faces'].includes(edit.op)) throw editField(index, 'select', edit.select, 'a face rule such as { "all": true } or { "tag": "top" }');normalized.select = edit.select ?? { all: true };}if (definition.fields.includes('name')) {@@ -145,7 +138,7 @@ export function normalizeMeshEdits(edits) {if (edit.direction !== undefined) normalized.direction = vector(edit.direction, index, 'direction');if (edit.alongNormals !== undefined) {if (typeof edit.alongNormals !== 'boolean') throw editField(index, 'alongNormals', edit.alongNormals, 'true or false');- if (edit.alongNormals && edit.direction !== undefined) throw editError(index, 'alongNormals and direction cannot be combined');+ if (edit.alongNormals && edit.direction !== undefined) throw editField(index, 'direction', edit.direction, 'left out when alongNormals is true');normalized.alongNormals = edit.alongNormals;}break;@@ -158,13 +151,13 @@ export function normalizeMeshEdits(edits) {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 }');+ if (!falloff || typeof falloff !== 'object') throw editField(index, 'falloff', falloff, 'an object such as { "radius": 1, "curve": "smooth", "connected": false }');for (const key of Object.keys(falloff)) {- if (!['radius', 'curve', 'connected'].includes(key)) throw editError(index, `falloff does not take ${key}`);+ if (!['radius', 'curve', 'connected'].includes(key)) throw editField(index, `falloff.${key}`, falloff[key], `one of the falloff fields radius, curve, connected; remove "${key}"`);}const curve = falloff.curve ?? 'smooth';if (!Object.hasOwn(FALLOFF_CURVES, curve)) throw editField(index, 'falloff.curve', curve, `one of ${Object.keys(FALLOFF_CURVES).join(', ')}`);- if (falloff.connected !== undefined && typeof falloff.connected !== 'boolean') throw editError(index, 'falloff.connected must be boolean');+ if (falloff.connected !== undefined && typeof falloff.connected !== 'boolean') throw editField(index, 'falloff.connected', falloff.connected, 'true or false');normalized.falloff = {radius: finiteNumber(falloff.radius, index, 'falloff.radius', { minimum: 0, exclusiveMinimum: true }),curve, connected: falloff.connected ?? false,@@ -175,7 +168,7 @@ export function normalizeMeshEdits(edits) {if (!BOOLEAN_OPERATIONS.includes(edit.operation)) throw editField(index, 'operation', edit.operation, `one of ${BOOLEAN_OPERATIONS.join(', ')}`);normalized.operation = edit.operation;if (!edit.cutter || typeof edit.cutter !== 'object' || Array.isArray(edit.cutter) || typeof edit.cutter.type !== 'string') {- throw editError(index, 'cutter must be a primitive record such as { "type": "cylinder", "segments": 32 }');+ throw editField(index, 'cutter', edit.cutter, 'a primitive record such as { "type": "cylinder", "segments": 32 }');}normalized.cutter = edit.cutter;normalizePlacement(edit, normalized, index);@@ -183,13 +176,13 @@ export function normalizeMeshEdits(edits) {}case 'sculpt':if (!Array.isArray(edit.strokes) || edit.strokes.length < 1 || edit.strokes.length > MAX_SCULPT_STROKES) {- throw editError(index, `strokes must be an array of 1 to ${MAX_SCULPT_STROKES} brush strokes`);+ throw editField(index, 'strokes', edit.strokes, `an array of 1 to ${MAX_SCULPT_STROKES} brush strokes, such as [{ "type": "${SCULPT_STROKE_TYPES[0]}", "center": [0, 0, 0], "radius": 0.5, "strength": 0.2 }]`);}normalized.strokes = edit.strokes.map((stroke, strokeIndex) => normalizeStroke(stroke, index, strokeIndex));break;case 'shrinkwrap':if (!edit.target || typeof edit.target !== 'object' || Array.isArray(edit.target) || typeof edit.target.type !== 'string') {- throw editError(index, 'target must be a primitive record such as { "type": "sphere", "radius": 0.5 }');+ throw editField(index, 'target', edit.target, 'a primitive record such as { "type": "sphere", "radius": 0.5 }');}normalized.target = edit.target;normalizePlacement(edit, normalized, index);@@ -197,9 +190,9 @@ export function normalizeMeshEdits(edits) {normalized.mode = edit.mode ?? 'nearest';if (normalized.mode === 'project') {normalized.direction = vector(edit.direction, index, 'direction');- if (normalized.direction.every(component => component === 0)) throw editError(index, 'direction must be nonzero');+ if (normalized.direction.every(component => component === 0)) throw editField(index, 'direction', normalized.direction, 'a nonzero direction, such as [0, -1, 0]');} else if (edit.direction !== undefined) {- throw editError(index, 'direction applies only to mode project');+ throw editField(index, 'direction', edit.direction, 'left out unless mode is "project"');}normalized.offset = edit.offset === undefined ? 0 : finiteNumber(edit.offset, index, 'offset', { minimum: 0 });if (edit.maxDistance !== undefined) normalized.maxDistance = finiteNumber(edit.maxDistance, index, 'maxDistance', { minimum: 0 });@@ -226,7 +219,7 @@ export function normalizeMeshEdits(edits) {break;case 'bevel':if (edit.edges !== undefined && (!edit.edges || typeof edit.edges !== 'object' || Array.isArray(edit.edges))) {- throw editError(index, 'edges must be a rule: { "between": [faceRule, faceRule] }, { "angle": degrees }, { "boundaryOf": faceRule } or { "all": true }');+ throw editField(index, 'edges', edit.edges, 'an edge rule such as { "all": true }, { "angle": 30 }, { "between": [faceRule, faceRule] } or { "boundaryOf": faceRule }');}normalized.edges = edit.edges ?? { angle: 30 };normalized.width = finiteNumber(edit.width, index, 'width', { minimum: 0, exclusiveMinimum: true });@@ -238,18 +231,18 @@ export function normalizeMeshEdits(edits) {break;case 'loop_cut':if (!edit.edges || typeof edit.edges !== 'object' || Array.isArray(edit.edges)) {- throw editError(index, 'edges must be a rule that picks the ring, for example { "along": [0, 1, 0] } for the vertical edges');+ throw editField(index, 'edges', edit.edges, 'a rule that picks the ring, such as { "along": [0, 1, 0] } for the vertical edges');}normalized.edges = edit.edges;if (!Number.isInteger(edit.cuts ?? 1) || (edit.cuts ?? 1) < 1 || (edit.cuts ?? 1) > 16) throw editField(index, 'cuts', edit.cuts, 'a whole number from 1 to 16, such as 1');normalized.cuts = edit.cuts ?? 1;- if (edit.factor !== undefined && normalized.cuts !== 1) throw editError(index, 'factor applies only to a single cut');+ if (edit.factor !== undefined && normalized.cuts !== 1) throw editField(index, 'factor', edit.factor, 'left out when cuts is above 1, because factor applies only to a single cut');normalized.factor = edit.factor === undefined ? 0.5 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1 });if (normalized.factor === 0 || normalized.factor === 1) throw editField(index, 'factor', normalized.factor, 'a number above 0 and below 1, such as 0.5');break;case 'uv_unwrap':if (edit.seams !== undefined && (!edit.seams || typeof edit.seams !== 'object' || Array.isArray(edit.seams))) {- throw editError(index, 'seams must be an edge rule, for example { "angle": 60 } or { "boundaryOf": { "tag": "lid.cap" } }');+ throw editField(index, 'seams', edit.seams, 'an edge rule such as { "angle": 60 } or { "boundaryOf": { "tag": "lid.cap" } }');}normalized.seams = edit.seams ?? { angle: 60 };normalized.margin = edit.margin === undefined ? 0.01 : finiteNumber(edit.margin, index, 'margin', { minimum: 0, maximum: 0.2 });@@ -262,18 +255,18 @@ export function normalizeMeshEdits(edits) {normalized.levels = edit.levels ?? 1;if (edit.crease !== undefined) {if (!edit.crease || typeof edit.crease !== 'object' || Array.isArray(edit.crease)) {- throw editError(index, 'crease must be an edge rule, for example { "angle": 60 } or { "between": [faceRule, faceRule] }');+ throw editField(index, 'crease', edit.crease, 'an edge rule such as { "angle": 60 } or { "between": [faceRule, faceRule] }');}normalized.crease = edit.crease;normalized.sharpness = edit.sharpness === undefined? MAX_CREASE_SHARPNESS: finiteNumber(edit.sharpness, index, 'sharpness', { minimum: 0, maximum: MAX_CREASE_SHARPNESS, exclusiveMinimum: true });} else if (edit.sharpness !== undefined) {- throw editError(index, 'sharpness needs a crease rule');+ throw editField(index, 'sharpness', edit.sharpness, 'left out unless a crease rule is given, such as "crease": { "angle": 60 }');}break;case 'set_position':- if (edit.position === undefined && edit.offset === undefined) throw editError(index, 'set_position needs a position or an offset expression');+ if (edit.position === undefined && edit.offset === undefined) throw editField(index, 'position', undefined, 'a vector field expression such as [0, 1, 0], given as position or as offset');if (edit.position !== undefined) normalized.position = checkedField(edit.position, index, 'position', 'vector');if (edit.offset !== undefined) normalized.offset = checkedField(edit.offset, index, 'offset', 'vector');break;@@ -284,7 +277,7 @@ export function normalizeMeshEdits(edits) {if (edit.direction !== undefined && !DISPLACE_DIRECTIONS.includes(edit.direction)) throw editField(index, 'direction', edit.direction, `one of ${DISPLACE_DIRECTIONS.join(', ')}`);normalized.direction = edit.direction ?? 'normal';if (edit.group !== undefined) {- if (typeof edit.group !== 'string' || !NAME_PATTERN.test(edit.group)) throw editError(index, 'group must be the name of a vertex group');+ if (typeof edit.group !== 'string' || !NAME_PATTERN.test(edit.group)) throw editField(index, 'group', edit.group, '1 to 48 letters, digits, dots, dashes or underscores naming a vertex group, such as "mask"');normalized.group = edit.group;}break;@@ -298,11 +291,11 @@ export function normalizeMeshEdits(edits) {normalized.ratio = finiteNumber(edit.ratio, index, 'ratio', { minimum: 0, maximum: 1, exclusiveMinimum: true });break;case 'remesh':- if ((edit.voxelSize === undefined) === (edit.resolution === undefined)) throw editError(index, 'remesh needs exactly one of voxelSize or resolution');+ if ((edit.voxelSize === undefined) === (edit.resolution === undefined)) throw editField(index, 'voxelSize', edit.voxelSize, 'exactly one of voxelSize and resolution, such as "voxelSize": 0.1');if (edit.voxelSize !== undefined) normalized.voxelSize = finiteNumber(edit.voxelSize, index, 'voxelSize', { minimum: 0, exclusiveMinimum: true });if (edit.resolution !== undefined) {if (!Number.isInteger(edit.resolution) || edit.resolution < 4 || edit.resolution > MAX_REMESH_RESOLUTION) {- throw editError(index, `resolution must be an integer from 4 to ${MAX_REMESH_RESOLUTION}`);+ throw editField(index, 'resolution', edit.resolution, `a whole number from 4 to ${MAX_REMESH_RESOLUTION}, such as 32`);}normalized.resolution = edit.resolution;}@@ -321,7 +314,7 @@ export function normalizeMeshEdits(edits) {function checkSubdivideBudget(mesh, edit, limits, index) {const size = subdivisionSize(mesh, edit.levels);if (size.vertices > limits.maxVertices || size.faces > limits.maxFaces) {- throw new RangeError(`Mesh edit ${index} (subdivide) would make ${size.vertices} vertices and ${size.faces} faces, over the limit of ${limits.maxVertices} vertices and ${limits.maxFaces} faces. Lower levels, or use a simpler mesh.`);+ throw editField(index, 'levels', edit.levels, `a number of levels that keeps the mesh within ${limits.maxVertices} vertices and ${limits.maxFaces} faces (this edit would make ${size.vertices} vertices and ${size.faces} faces), such as 1, or use a simpler mesh`, RangeError);}}@@ -351,7 +344,7 @@ function checkArrayBudget(mesh, edit, limits, index) {const vertices = mesh.vertexCount * edit.count;const faces = mesh.faceCount * edit.count;if (vertices > limits.maxVertices || faces > limits.maxFaces) {- throw new RangeError(`Mesh edit ${index} (array) would make ${vertices} vertices and ${faces} faces, over the limit of ${limits.maxVertices} vertices and ${limits.maxFaces} faces. Lower count, or use a simpler mesh.`);+ throw editField(index, 'count', edit.count, `a count that keeps the mesh within ${limits.maxVertices} vertices and ${limits.maxFaces} faces (this edit would make ${vertices} vertices and ${faces} faces), such as 2, or use a simpler mesh`, RangeError);}}@@ -573,7 +566,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {throw editFailure(error, index, `${edit.op}`);}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.`);+ if (selected === 0) throw editField(index, 'select', edit.select, 'a rule that matches at least one face, such as { "all": true } (check tags and counts with mesh_inspect)', RangeError);result.selected = selected;const editable = editMesh(current);let created = null;diff --git a/tests/actionable-errors-mesh-edits.test.js b/tests/actionable-errors-mesh-edits.test.jsnew file mode 100644index 00000000..4c24bd36--- /dev/null+++ b/tests/actionable-errors-mesh-edits.test.js@@ -0,0 +1,173 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { createAgentScene } from '../src/agent-scene.js';+import { loadAgentSceneModules } from '../src/agent-scene-modules.js';++// Mesh edit validators (cut, deform, generator, modifier, normal, attribute edits and the recipe checks) report through+// edits[N].field, with the value received and what is accepted. Each case is reached through the public scene API.++function baseRecipe() {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'block', type: 'mesh', base: { type: 'box', bevel: 0 } }],+ materials: [{ id: 'plain', color: [0.5, 0.5, 0.5] }],+ nodes: [{ id: 'body', geometry: 'block', material: 'plain' }],+ };+}++function badEdit(edit) {+ return async () => {+ const recipe = baseRecipe();+ await loadAgentSceneModules(recipe);+ const scene = createAgentScene(recipe);+ const operation = { type: 'edit-mesh', geometry: 'block', edits: [edit] };+ await loadAgentSceneModules(operation);+ return scene.apply([operation], { expectedRevision: 0 });+ };+}++function badRecipeEdit(edit) {+ return async () => {+ const recipe = baseRecipe();+ recipe.geometries[0].edits = [edit];+ await loadAgentSceneModules(recipe);+ return createAgentScene(recipe);+ };+}++const CURVE_PATH = [[0, 0, 0], [1, 0, 0]];++// Each case: the source file it belongs to, how an agent reaches the error, the full field path and the value echoed.+const CASES = [+ ['src/mesh-cut-edits.js', 'fill_holes sides below range', badEdit({ op: 'fill_holes', sides: 2 }), 'edits[0].sides', '2'],+ ['src/mesh-cut-edits.js', 'bisect_plane normal all zero', badEdit({ op: 'bisect_plane', point: [0, 0, 0], normal: [0, 0, 0] }), 'edits[0].normal', '[0,0,0]'],+ ['src/mesh-cut-edits.js', 'bisect_plane clears both sides', badEdit({ op: 'bisect_plane', point: [0, 0, 0], normal: [0, 1, 0], clearInner: true, clearOuter: true }), 'edits[0].clearOuter', 'true'],+ ['src/mesh-cut-edits.js', 'bisect_plane fill as text', badEdit({ op: 'bisect_plane', point: [0, 0, 0], normal: [0, 1, 0], fill: 'yes' }), 'edits[0].fill', '"yes"'],+ ['src/mesh-cut-edits.js', 'knife_project path with one point', badEdit({ op: 'knife_project', path: [[0, 0, 0]], direction: [0, 0, -1] }), 'edits[0].path', '[[0,0,0]]'],+ ['src/mesh-cut-edits.js', 'knife_project direction all zero', badEdit({ op: 'knife_project', path: CURVE_PATH, direction: [0, 0, 0] }), 'edits[0].direction', '[0,0,0]'],+ ['src/mesh-cut-edits.js', 'dissolve_edges rule as a list', badEdit({ op: 'dissolve_edges', edges: [] }), 'edits[0].edges', '[]'],+ ['src/mesh-cut-edits.js', 'subdivide_edges cuts too many', badEdit({ op: 'subdivide_edges', edges: { all: true }, cuts: 99 }), 'edits[0].cuts', '99'],+ ['src/mesh-cut-edits.js', 'dissolve_faces rule selects nothing', badEdit({ op: 'dissolve_faces', select: { faces: [] } }), 'edits[0].select', '{"faces":[]}'],+ ['src/mesh-deform-modifiers.js', 'lattice divisions too high', badEdit({ op: 'lattice', divisions: [9, 2, 2] }), 'edits[0].divisions', '9'],+ ['src/mesh-deform-modifiers.js', 'lattice move without an offset', badEdit({ op: 'lattice', moves: [{ point: [0, 0, 0] }] }), 'edits[0].moves[0].offset', 'undefined'],+ ['src/mesh-deform-modifiers.js', 'lattice move point out of the grid', badEdit({ op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [2, 0, 0], offset: [0, 0, 1] }] }), 'edits[0].moves[0].point', '2'],+ ['src/mesh-deform-modifiers.js', 'curve path with one point', badEdit({ op: 'curve', path: [[0, 0, 0]] }), 'edits[0].path', '[[0,0,0]]'],+ ['src/mesh-deform-modifiers.js', 'curve axis unknown', badEdit({ op: 'curve', path: CURVE_PATH, axis: 'q' }), 'edits[0].axis', '"q"'],+ ['src/mesh-deform-modifiers.js', 'curve path without length', badEdit({ op: 'curve', path: [[1, 1, 1], [1, 1, 1]] }), 'edits[0].path', '[[1,1,1],[1,1,1]]'],+ ['src/mesh-deform-modifiers.js', 'hook falloff unknown', badEdit({ op: 'hook', falloff: 'sharp' }), 'edits[0].falloff', '"sharp"'],+ ['src/mesh-deform-modifiers.js', 'wave axes unknown', badEdit({ op: 'wave', axes: 'z' }), 'edits[0].axes', '"z"'],+ ['src/mesh-deform-modifiers.js', 'wave start with one number', badEdit({ op: 'wave', start: [1] }), 'edits[0].start', '[1]'],+ ['src/mesh-deform-modifiers.js', 'wave cyclic as text', badEdit({ op: 'wave', cyclic: 'yes' }), 'edits[0].cyclic', '"yes"'],+ ['src/mesh-generator-modifiers.js', 'screw steps too high', badEdit({ op: 'screw', steps: 999 }), 'edits[0].steps', '999'],+ ['src/mesh-generator-modifiers.js', 'screw axis unknown', badEdit({ op: 'screw', axis: 'w' }), 'edits[0].axis', '"w"'],+ ['src/mesh-generator-modifiers.js', 'wireframe replace as text', badEdit({ op: 'wireframe', replace: 'yes' }), 'edits[0].replace', '"yes"'],+ ['src/mesh-generator-modifiers.js', 'wireframe evenOffset as number', badEdit({ op: 'wireframe', evenOffset: 1 }), 'edits[0].evenOffset', '1'],+ ['src/mesh-generator-modifiers.js', 'skin radius field reaching zero', badEdit({ op: 'skin', radius: { mul: [0, { attr: 'position', component: 'z' }] } }), 'edits[0].radius', '0'],+ ['src/mesh-modifiers.js', 'simple_deform mode unknown', badEdit({ op: 'simple_deform', mode: 'melt' }), 'edits[0].mode', '"melt"'],+ ['src/mesh-modifiers.js', 'simple_deform axis unknown', badEdit({ op: 'simple_deform', mode: 'twist', axis: 'w' }), 'edits[0].axis', '"w"'],+ ['src/mesh-modifiers.js', 'simple_deform twist given a factor', badEdit({ op: 'simple_deform', mode: 'twist', factor: 2 }), 'edits[0].factor', '2'],+ ['src/mesh-modifiers.js', 'triangulate minVertices too low', badEdit({ op: 'triangulate', minVertices: 2 }), 'edits[0].minVertices', '2'],+ ['src/mesh-modifiers.js', 'smooth iterations too high', badEdit({ op: 'smooth', iterations: 1000 }), 'edits[0].iterations', '1000'],+ ['src/mesh-normal-modifiers.js', 'smooth_by_angle ignoreSharp as number', badEdit({ op: 'smooth_by_angle', ignoreSharp: 1 }), 'edits[0].ignoreSharp', '1'],+ ['src/mesh-normal-modifiers.js', 'smooth_by_angle angle too wide', badEdit({ op: 'smooth_by_angle', angle: 500 }), 'edits[0].angle', '500'],+ ['src/mesh-normal-modifiers.js', 'weighted_normal weight below range', badEdit({ op: 'weighted_normal', weight: 0 }), 'edits[0].weight', '0'],+ ['src/mesh-attribute-edits.js', 'vertex_group weight above one', badEdit({ op: 'vertex_group', name: 'mask', weight: 2 }), 'edits[0].weight', '2'],+ ['src/mesh-attribute-edits.js', 'vertex_group weight and gradient together', badEdit({ op: 'vertex_group', name: 'mask', weight: 1, gradient: { axis: 'y', range: [0, 1], weights: [0, 1] } }), 'edits[0].gradient', '{"axis":"y","range":[0,1],"weights":[...'],+ ['src/mesh-attribute-edits.js', 'vertex_group gradient axis unknown', badEdit({ op: 'vertex_group', name: 'mask', gradient: { axis: 'w', range: [0, 1], weights: [0, 1] } }), 'edits[0].gradient.axis', '"w"'],+ ['src/mesh-attribute-edits.js', 'vertex_group gradient range reversed', badEdit({ op: 'vertex_group', name: 'mask', gradient: { axis: 'y', range: [1, 0], weights: [0, 1] } }), 'edits[0].gradient.range', '[1,0]'],+ ['src/mesh-attribute-edits.js', 'vertex_group gradient with one weight', badEdit({ op: 'vertex_group', name: 'mask', gradient: { axis: 'y', range: [0, 1], weights: [0] } }), 'edits[0].gradient.weights', '[0]'],+ ['src/mesh-attribute-edits.js', 'vertex_group gradient unknown key', badEdit({ op: 'vertex_group', name: 'mask', gradient: { axis: 'y', range: [0, 1], weights: [0, 1], colors: 3 } }), 'edits[0].gradient.colors', '3'],+ ['src/mesh-attribute-edits.js', 'vertex_color with two channels', badEdit({ op: 'vertex_color', color: [1, 0] }), 'edits[0].color', '[1,0]'],+ ['src/mesh-attribute-edits.js', 'vertex_color gradient end color too bright', badEdit({ op: 'vertex_color', gradient: { axis: 'y', range: [0, 1], colors: [[1, 0, 0], [0, 4, 0]] } }), 'edits[0].gradient.colors[1]', '4'],+ ['src/mesh-recipe.js', 'edit that is not an object', badEdit('extrude'), 'edits[0]', '"extrude"'],+ ['src/mesh-recipe.js', 'edit with a field the op does not take', badEdit({ op: 'extrude_individual', offset: 1, depth: 2 }), 'edits[0].depth', '2'],+ ['src/mesh-recipe.js', 'delete without select', badEdit({ op: 'delete' }), 'edits[0].select', 'undefined'],+ ['src/mesh-recipe.js', 'boolean scale not positive', badEdit({ op: 'boolean', operation: 'union', cutter: { type: 'box' }, scale: [1, -1, 1] }), 'edits[0].scale', '[1,-1,1]'],+ ['src/mesh-recipe.js', 'boolean rotation with three numbers', badEdit({ op: 'boolean', operation: 'union', cutter: { type: 'box' }, rotation: [0, 0, 1] }), 'edits[0].rotation', '[0,0,1]'],+ ['src/mesh-recipe.js', 'boolean cutter as text', badEdit({ op: 'boolean', operation: 'union', cutter: 'box' }), 'edits[0].cutter', '"box"'],+ ['src/mesh-recipe.js', 'sculpt without strokes', badEdit({ op: 'sculpt', strokes: [] }), 'edits[0].strokes', '[]'],+ ['src/mesh-recipe.js', 'sculpt stroke type unknown', badEdit({ op: 'sculpt', strokes: [{ type: 'carve', center: [0, 0, 0], radius: 1, strength: 1 }] }), 'edits[0].strokes[0].type', '"carve"'],+ ['src/mesh-recipe.js', 'sculpt smooth stroke too strong', badEdit({ op: 'sculpt', strokes: [{ type: 'smooth', center: [0, 0, 0], radius: 1, strength: 3 }] }), 'edits[0].strokes[0].strength', '3'],+ ['src/mesh-recipe.js', 'shrinkwrap target as text', badEdit({ op: 'shrinkwrap', target: 'sphere' }), 'edits[0].target', '"sphere"'],+ ['src/mesh-recipe.js', 'shrinkwrap direction without project mode', badEdit({ op: 'shrinkwrap', target: { type: 'sphere' }, direction: [0, 1, 0] }), 'edits[0].direction', '[0,1,0]'],+ ['src/mesh-recipe.js', 'bevel rule as a list', badEdit({ op: 'bevel', width: 0.1, edges: [] }), 'edits[0].edges', '[]'],+ ['src/mesh-recipe.js', 'loop_cut without a ring rule', badEdit({ op: 'loop_cut' }), 'edits[0].edges', 'undefined'],+ ['src/mesh-recipe.js', 'loop_cut factor with several cuts', badEdit({ op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, factor: 0.3 }), 'edits[0].factor', '0.3'],+ ['src/mesh-recipe.js', 'uv_unwrap seams as a list', badEdit({ op: 'uv_unwrap', seams: [1] }), 'edits[0].seams', '[1]'],+ ['src/mesh-recipe.js', 'subdivide sharpness without crease', badEdit({ op: 'subdivide', sharpness: 2 }), 'edits[0].sharpness', '2'],+ ['src/mesh-recipe.js', 'translate falloff as text', badEdit({ op: 'translate', offset: [0, 1, 0], falloff: 'wide' }), 'edits[0].falloff', '"wide"'],+ ['src/mesh-recipe.js', 'remesh with neither voxelSize nor resolution', badEdit({ op: 'remesh' }), 'edits[0].voxelSize', 'undefined'],+ ['src/mesh-recipe.js', 'remesh resolution too low', badEdit({ op: 'remesh', resolution: 1 }), 'edits[0].resolution', '1'],+ ['src/mesh-recipe.js', 'set_position without position or offset', badEdit({ op: 'set_position' }), 'edits[0].position', 'undefined'],+ ['src/mesh-recipe.js', 'displace field of the wrong kind', badEdit({ op: 'displace', field: [0, 1, 0] }), 'edits[0].field', '[0,1,0]'],+ ['src/mesh-recipe.js', 'displace group not a name', badEdit({ op: 'displace', field: 1, group: 'bad name!' }), 'edits[0].group', '"bad name!"'],+ ['src/mesh-recipe.js', 'array count zero', badEdit({ op: 'array', count: 0 }), 'edits[0].count', '0'],+ ['src/mesh-recipe.js', 'recipe edit keeps its geometry path', badRecipeEdit({ op: 'subdivide', levels: 9 }), 'geometries[0].edits[0].levels', '9'],+];++// A message is actionable when it gives a way to fix the input: a range, a list of choices or an example.+const ACCEPTED = /such as|\bfrom -?[\d.e]+ to -?[\d.e]+|one of |true or false|above \d|left out|\bor more\b/;++const SOURCE_FILES = [...new Set(CASES.map(([file]) => file))];++assert.ok(CASES.length >= 50, 'the walk covers at least 50 bad inputs');+for (const file of SOURCE_FILES) {+ assert.ok(CASES.filter(([caseFile]) => caseFile === file).length >= 3, `${file} has at least 3 cases`);+}++for (const [file, label, trigger, path, received] of CASES) {+ test(`${file}: error for ${label} names the field, the value and what is accepted`, async () => {+ let message;+ try {+ await trigger();+ } catch (error) {+ message = error.message;+ }+ assert.ok(message, `${label} must throw`);+ assert.ok(message.includes(`${path}: got ${received}`), `"${path}: got ${received}" missing in: ${message}`);+ assert.match(message, /expected /, `no expectation in: ${message}`);+ assert.match(message, ACCEPTED, `no example or range in: ${message}`);+ });+}++// The guard: a throw in these files reports through invalidField or editField, which name the path, the value and what+// is accepted. The throws listed stay raw on purpose: whole-input size limits, host wiring and engine invariants no edit+// field can fix, and the mesh stack checks, which have their own path. A new raw throw fails until it is converted or listed.+const RAW_THROWS_LEFT = {+ 'src/mesh-cut-edits.js': [+ '`Not a cutting edit: ${edit.op}`);',+ ],+ 'src/mesh-deform-modifiers.js': [],+ 'src/mesh-generator-modifiers.js': [+ '`${operation} would make ${vertices} ver',+ '`skin edge ${edge} has no length. Weld t',+ ],+ 'src/mesh-modifiers.js': [+ '`Not a modifier: ${edit.op}`);',+ ],+ 'src/mesh-normal-modifiers.js': [],+ 'src/mesh-attribute-edits.js': [+ '`A mesh holds at most ${MAX_VERTEX_GROUP',+ ],+ 'src/mesh-edit-field.js': [],+ 'src/mesh-recipe.js': [+ '`A mesh holds at most ${MAX_MESH_EDITS} ',+ '`Mesh edit ${index} (${op}) grows the me',+ "'shrinkwrap needs a target resolver; rec",+ "'A mesh edit field reads a surface given",+ '`Mesh edit ${index} (boolean) needs a cu',+ "'stack must be an array.');",+ '`A stack holds at most ${MAX_STACK_NODES',+ '`Stack node ${index} op must be one of $',+ ],+};+const THROW_PATTERN = /throw new (?:Range|Type)?Error\((.{0,40})/;++for (const [file, listed] of Object.entries(RAW_THROWS_LEFT)) {+ test(`${file} adds no raw throw that lacks a field path and an expectation`, () => {+ const lines = readFileSync(new URL(`../${file}`, import.meta.url), 'utf8').split(/\r?\n/);+ const found = lines.map(line => line.match(THROW_PATTERN)?.[1]).filter(Boolean);+ assert.deepEqual(found, listed, `${file}: report agent input mistakes with editField(index, field, value, expected) from src/mesh-edit-field.js; list a throw here only when no input field can cause it`);+ });+}diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex ca4b80c8..87215265 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -319,7 +319,7 @@ test('mesh_edit builds a mesh from a base and an edit log through the SDK', asynconst 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/);+ assert.match(none.content[0].text, /Unknown tag lid\.rim|edits\[3\]\.select: got \{"tag":"lid\.rim"\}; expected a rule that matches at least one face/);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,diff --git a/tests/mesh-bevel.test.js b/tests/mesh-bevel.test.jsindex de76aeb3..b57f7a1a 100644--- a/tests/mesh-bevel.test.js+++ b/tests/mesh-bevel.test.js@@ -133,7 +133,7 @@ test('bevel on an open surface keeps the opening as the only problem, and validaassert.equal(beveled.bevelEdges, 8, 'only edges with two faces bevel');assert.throws(() => normalizeMeshEdits([{ op: 'bevel', width: 0 }]), /edits\[0\]\.width: got 0; expected a number above 0/);assert.throws(() => normalizeMeshEdits([{ op: 'bevel', width: 0.1, segments: 40 }]), /edits\[0\]\.segments: got 40; expected a whole number from 1 to 16/);- assert.throws(() => normalizeMeshEdits([{ op: 'bevel', width: 0.1, edges: [] }]), /edges must be a rule/);+ assert.throws(() => normalizeMeshEdits([{ op: 'bevel', width: 0.1, edges: [] }]), /edits\[0\]\.edges: got \[\]; expected an edge rule/);assert.deepEqual(normalizeMeshEdits([{ op: 'bevel', width: 0.1 }])[0].edges, { angle: 30 });});diff --git a/tests/mesh-boolean.test.js b/tests/mesh-boolean.test.jsindex 10fcc072..c5dd48f9 100644--- a/tests/mesh-boolean.test.js+++ b/tests/mesh-boolean.test.js@@ -87,7 +87,7 @@ test('boolean errors explain open inputs, empty results and bad fields', () => {assert.throws(() => meshBoolean(open, cube(), 'union'), /must be closed for a boolean: 4 boundary-edge/);assert.throws(() => meshBoolean(cube(), transformMesh(cube(), { translation: [5, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] }), 'intersect'), /leaves nothing/);assert.throws(() => applyMeshEdits(cube(), [{ op: 'boolean', operation: 'xor', cutter: { type: 'box' } }], { resolveCutter }), /edits\[0\]\.operation: got "xor"; expected one of union/);- assert.throws(() => applyMeshEdits(cube(), [{ op: 'boolean', operation: 'union', cutter: { type: 'box' }, scale: [1, -1, 1] }], { resolveCutter }), /scale components must be positive/);+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'boolean', operation: 'union', cutter: { type: 'box' }, scale: [1, -1, 1] }], { resolveCutter }), /edits\[0\]\.scale: got \[1,-1,1\]; expected three numbers above 0/);assert.throws(() => applyMeshEdits(cube(), [{ op: 'boolean', operation: 'union', cutter: { type: 'box' } }]), /needs a cutter resolver/);});diff --git a/tests/mesh-cut-tools.test.js b/tests/mesh-cut-tools.test.jsindex 36cfd005..da549544 100644--- a/tests/mesh-cut-tools.test.js+++ b/tests/mesh-cut-tools.test.js@@ -94,7 +94,7 @@ test('subdivide_edges grids quads whose edges are all split', () => {});test('subdivide_edges refuses to grow past the limits before allocating', () => {- assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide_edges', edges: { all: true }, cuts: 16 }], { maxFaces: 100 }), /over the limit/);+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide_edges', edges: { all: true }, cuts: 16 }], { maxFaces: 100 }), /edits\[0\]\.cuts: got 16; expected a number of cuts that keeps the mesh within/);});test('grid_fill fills an even loop with quads', () => {diff --git a/tests/mesh-deform-modifiers.test.js b/tests/mesh-deform-modifiers.test.jsindex 2351bd2f..f499a476 100644--- a/tests/mesh-deform-modifiers.test.js+++ b/tests/mesh-deform-modifiers.test.js@@ -35,10 +35,10 @@ test('lattice moves a control point fully at its vertex and by the blend elsewhe});test('lattice refuses bad grids and moves with the limit in the message', () => {- assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [9, 2, 2] }]), /divisions must be an integer from 2 to 8/);- assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [2, 0, 0], offset: [0, 0, 1] }] }]), /point must be an integer from 0 to 1/);+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [9, 2, 2] }]), /edits\[0\]\.divisions: got 9; expected a whole number from 2 to 8/);+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [2, 0, 0], offset: [0, 0, 1] }] }]), /edits\[0\]\.moves\[0\]\.point: got 2; expected a whole number from 0 to 1/);assert.throws(() => normalizeMeshEdits([{ op: 'lattice', moves: new Array(65).fill({ point: [0, 0, 0], offset: [0, 0, 0] }) }]), /at most 64/);- assert.throws(() => normalizeMeshEdits([{ op: 'lattice', moves: [{ point: [0, 0, 0] }] }]), /offset needs three numbers/);+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', moves: [{ point: [0, 0, 0] }] }]), /edits\[0\]\.moves\[0\]\.offset: got undefined; expected an array of three numbers/);});test('curve leaves a beam alone on a straight path along its axis and bends it along an arc', () => {@@ -53,9 +53,9 @@ test('curve leaves a beam alone on a straight path along its axis and bends it a});test('curve names its limits', () => {- assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0]] }]), /path needs 2 to 64 points/);- assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0], [1, 0, 0]], axis: 'q' }]), /axis must be x, y or z/);- assert.throws(() => run(beam(), { op: 'curve', path: [[1, 1, 1], [1, 1, 1]] }), /path has no length/);+ assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0]] }]), /edits\[0\]\.path: got \[\[0,0,0\]\]; expected an array of 2 to 64 points/);+ assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0], [1, 0, 0]], axis: 'q' }]), /edits\[0\]\.axis: got "q"; expected one of "x", "y", "z"/);+ assert.throws(() => run(beam(), { op: 'curve', path: [[1, 1, 1], [1, 1, 1]] }), /edits\[0\]\.path: got \[\[1,1,1\],\[1,1,1\]\]; expected points that are apart/);});test('hook pulls the vertices inside the radius by the falloff weight and none outside', () => {@@ -66,7 +66,7 @@ test('hook pulls the vertices inside the radius by the falloff weight and none oconst soft = run(cube(), { op: 'hook', center: [0.5, 0.5, 0.5], radius: 1.2, translation: [0, 0, 1], strength: 0.5 });assert.ok(soft.positions[2 + 3 * 6] > 0.5 && soft.positions[2 + 3 * 6] < 1.1);assert.throws(() => normalizeMeshEdits([{ op: 'hook', radius: 0 }]), /edits\[0\]\.radius: got 0; expected a number above 0/);- assert.throws(() => normalizeMeshEdits([{ op: 'hook', falloff: 'sharp' }]), /falloff must be one of smooth, linear, constant/);+ assert.throws(() => normalizeMeshEdits([{ op: 'hook', falloff: 'sharp' }]), /edits\[0\]\.falloff: got "sharp"; expected one of smooth, linear, constant/);assert.throws(() => normalizeMeshEdits([{ op: 'hook', strength: 2 }]), /edits\[0\]\.strength: got 2; expected a number from 0 to 1/);});@@ -82,9 +82,9 @@ test('wave lifts vertices inside its ring along z, moves with time and can folloassert.equal(later.positions[2], 0, 'the single ripple has left the face');const alongNormal = run(flat, { op: 'wave', normal: true });assert.ok(Math.abs(alongNormal.positions[2]) > 0 && alongNormal.positions[0] === 0);- assert.throws(() => normalizeMeshEdits([{ op: 'wave', axes: 'z' }]), /axes must be one of xy, x, y/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wave', axes: 'z' }]), /edits\[0\]\.axes: got "z"; expected one of xy, x, y/);assert.throws(() => normalizeMeshEdits([{ op: 'wave', narrowness: 51 }]), /edits\[0\]\.narrowness: got 51; expected a number from 0 to 50/);- assert.throws(() => normalizeMeshEdits([{ op: 'wave', start: [1] }]), /start needs two numbers/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wave', start: [1] }]), /edits\[0\]\.start: got \[1\]; expected an array of two numbers/);});test('the deforming modifiers run as stack nodes', () => {diff --git a/tests/mesh-edit.test.js b/tests/mesh-edit.test.jsindex 9c4b6897..d6ec3c58 100644--- a/tests/mesh-edit.test.js+++ b/tests/mesh-edit.test.js@@ -151,9 +151,9 @@ test('translate with connected falloff moves nearby vertices less', () => {test('edit validation names the op, field and allowed values', () => {assert.throws(() => normalizeMeshEdits([{ op: 'knife' }]), /edits\[0\]\.op: got "knife"; expected one of extrude_face_region/);- assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, depth: 2 }]), /does not take depth/);+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, depth: 2 }]), /edits\[0\]\.depth: got 2; expected one of the fields extrude_individual takes/);assert.throws(() => normalizeMeshEdits([{ op: 'inset_region', thickness: 0 }]), /edits\[0\]\.thickness: got 0; expected a number above 0/);- assert.throws(() => normalizeMeshEdits([{ op: 'delete' }]), /delete needs select/);+ assert.throws(() => normalizeMeshEdits([{ op: 'delete' }]), /edits\[0\]\.select: got undefined; expected a face rule/);assert.throws(() => normalizeMeshEdits([{ op: 'tag', select: { all: true }, name: 'bad name' }]), /edits\[0\]\.name: got "bad name"; expected 1 to 48 letters/);assert.throws(() => normalizeMeshEdits([{ op: 'translate', offset: [0, 1, 0], falloff: { radius: 1, curve: 'wobbly' } }]), /edits\[0\]\.falloff\.curve: got "wobbly"; expected 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/);diff --git a/tests/mesh-fields.test.js b/tests/mesh-fields.test.jsindex a2ce8218..4989e674 100644--- a/tests/mesh-fields.test.js+++ b/tests/mesh-fields.test.js@@ -130,7 +130,7 @@ test('set_position moves vertices by a field and leaves the rest alone', () => {const stretched = applyMeshEdits(mesh, [{ op: 'set_position', position: { vec: [{ attr: 'position', component: 'x' }, { mul: [{ attr: 'position', component: 'y' }, 2] }, { attr: 'position', component: 'z' }] } }]).mesh;assert.equal(stretched.positions[1], mesh.positions[1] * 2);assert.equal(stretched.faceCount, mesh.faceCount);- assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position' }]), /position or an offset/);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position' }]), /edits\[0\]\.position: got undefined; expected a vector field expression/);assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position', offset: 1 }]), /vector/);assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position', offset: { eval: 'x' } }]), /unknown operator/);});diff --git a/tests/mesh-generator-modifiers.test.js b/tests/mesh-generator-modifiers.test.jsindex 63bfbee6..8247c2e0 100644--- a/tests/mesh-generator-modifiers.test.js+++ b/tests/mesh-generator-modifiers.test.js@@ -36,8 +36,8 @@ test('screw turns about the chosen axis and a negative angle turns the other waytest('screw names the limit and what to change when it would make too many vertices', () => {assert.throws(() => run(profileQuad(), { op: 'screw', steps: 256, iterations: 64 }, { maxVertices: 1000, maxFaces: 1000 }), /screw would make .* Lower steps or iterations/);- assert.throws(() => normalizeMeshEdits([{ op: 'screw', steps: 257 }]), /steps must be an integer from 1 to 256/);- assert.throws(() => normalizeMeshEdits([{ op: 'screw', axis: 'w' }]), /axis must be x, y or z/);+ assert.throws(() => normalizeMeshEdits([{ op: 'screw', steps: 257 }]), /edits\[0\]\.steps: got 257; expected a whole number from 1 to 256/);+ assert.throws(() => normalizeMeshEdits([{ op: 'screw', axis: 'w' }]), /edits\[0\]\.axis: got "w"; expected one of "x", "y", "z"/);});test('wireframe makes two quads per face edge, stays closed and puts the strut either side of the surface', () => {@@ -56,7 +56,7 @@ test('wireframe refuses a result over the limits and bad fields', () => {assert.throws(() => run(cube(), { op: 'wireframe' }, { maxVertices: 10, maxFaces: 1000 }), /wireframe would make 40 vertices/);assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', thickness: 0 }]), /edits\[0\]\.thickness: got 0; expected a number above 0/);assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', offset: 2 }]), /edits\[0\]\.offset: got 2; expected a number from -1 to 1/);- assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', replace: 'yes' }]), /booleans/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', replace: 'yes' }]), /edits\[0\]\.replace: got "yes"; expected true or false/);});test('skin puts a closed square tube on every edge and takes a radius per vertex from a field', () => {@@ -66,7 +66,7 @@ test('skin puts a closed square tube on every edge and takes a radius per vertexconst fat = run(cube(), { op: 'skin', radius: { add: [0.1, { mul: [0.1, { attr: 'position', component: 'z' }] }] } }).mesh;const upperReach = Math.max(...Array.from({ length: fat.vertexCount }, (_, vertex) => fat.positions[vertex * 3]));assert.ok(upperReach > 0.6 && upperReach < 0.7);- assert.throws(() => run(cube(), { op: 'skin', radius: { mul: [0, { attr: 'position', component: 'z' }] } }), /radius must be above zero at every vertex/);+ assert.throws(() => run(cube(), { op: 'skin', radius: { mul: [0, { attr: 'position', component: 'z' }] } }), /edits\[0\]\.radius: got 0; expected above 0 at every vertex/);assert.throws(() => run(cube(), { op: 'skin' }, { maxVertices: 50, maxFaces: 1000 }), /skin would make 96 vertices/);assert.throws(() => normalizeMeshEdits([{ op: 'skin', radius: -1 }]), /edits\[0\]\.radius: got -1; expected a number above 0/);});diff --git a/tests/mesh-loopcut.test.js b/tests/mesh-loopcut.test.jsindex 3b819532..10cba199 100644--- a/tests/mesh-loopcut.test.js+++ b/tests/mesh-loopcut.test.js@@ -90,13 +90,13 @@ test('a band around a cylinder extrudes along normals as one joined hoop', () =>assert.ok(Math.abs(radius - 1.1) < 0.01, `cap vertex radius ${radius}`);}}- assert.throws(() => normalizeMeshEdits([{ op: 'extrude_face_region', offset: 1, alongNormals: true, direction: [0, 1, 0] }]), /cannot be combined/);- assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, alongNormals: true }]), /does not take alongNormals/);+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_face_region', offset: 1, alongNormals: true, direction: [0, 1, 0] }]), /edits\[0\]\.direction: got \[0,1,0\]; expected left out when alongNormals is true/);+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, alongNormals: true }]), /edits\[0\]\.alongNormals: got true; expected one of the fields extrude_individual takes/);});test('loop cut validation and errors are explicit', () => {- assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut' }]), /edges must be a rule that picks the ring/);- assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, factor: 0.3 }]), /factor applies only to a single cut/);+ assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut' }]), /edits\[0\]\.edges: got undefined; expected a rule that picks the ring/);+ assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, factor: 0.3 }]), /edits\[0\]\.factor: got 0\.3; expected left out when cuts is above 1/);assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut', edges: { along: [0, 1, 0] }, factor: 1 }]), /edits\[0\]\.factor: got 1; expected a number above 0 and below 1/);assert.throws(() => loopCut(cube(), { along: [1, 1, 1], maxAngle: 1 }), /selects no edges/);assert.throws(() => loopCut(cube(), { all: true }), /rings cross/);diff --git a/tests/mesh-normal-modifiers.test.js b/tests/mesh-normal-modifiers.test.jsindex 97326a08..83febf1d 100644--- a/tests/mesh-normal-modifiers.test.js+++ b/tests/mesh-normal-modifiers.test.js@@ -71,7 +71,7 @@ test('a higher weight leans further toward the large face and sharp bends stay stest('the normal modifiers name their limits and run as stack nodes', () => {assert.throws(() => normalizeMeshEdits([{ op: 'weighted_normal', weight: 0 }]), /edits\[0\]\.weight: got 0; expected a number from 1 to 100/);assert.throws(() => normalizeMeshEdits([{ op: 'weighted_normal', angle: 181 }]), /edits\[0\]\.angle: got 181; expected a number from 0 to 180/);- assert.throws(() => normalizeMeshEdits([{ op: 'smooth_by_angle', ignoreSharp: 1 }]), /ignoreSharp must be a boolean/);+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_by_angle', ignoreSharp: 1 }]), /edits\[0\]\.ignoreSharp: got 1; expected true or false/);const outcome = evaluateMeshStack(cube(), [{ op: 'smooth_by_angle', angle: 100 }, { op: 'weighted_normal' }]);assert.equal(outcome.results.length, 2);assert.ok(outcome.mesh.attributes.corner.normal);diff --git a/tests/mesh-stack.test.js b/tests/mesh-stack.test.jsindex 2839212b..6cad6d19 100644--- a/tests/mesh-stack.test.js+++ b/tests/mesh-stack.test.js@@ -142,6 +142,6 @@ test('recipe meshes evaluate stacks, reuse cached prefixes and apply nodes intotest('an array over the budget fails before it allocates, and names the fix', () => {const edits = [{ op: 'array', count: 200 }];- assert.throws(() => applyMeshEdits(cube(), edits, { maxVertices: 100, maxFaces: 100 }), /would make 1600 vertices .* Lower count/);+ assert.throws(() => applyMeshEdits(cube(), edits, { maxVertices: 100, maxFaces: 100 }), /edits\[0\]\.count: got 200; expected a count that keeps the mesh within 100 vertices and 100 faces \(this edit would make 1600 vertices/);assert.throws(() => evaluateMeshStack(cube(), edits, { maxVertices: 100, maxFaces: 100 }), /would make 1600 vertices/);});diff --git a/tests/mesh-subdivide.test.js b/tests/mesh-subdivide.test.jsindex e6477083..048e599e 100644--- a/tests/mesh-subdivide.test.js+++ b/tests/mesh-subdivide.test.js@@ -93,14 +93,14 @@ test('a crease of sharpness 1 holds for one level only', () => {});test('the budget is checked before the mesh grows', () => {- assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide', levels: 4 }], { maxFaces: 1000 }), /subdivide\) would make \d+ vertices and 1536 faces/);+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide', levels: 4 }], { maxFaces: 1000 }), /edits\[0\]\.levels: got 4; .*\(this edit would make \d+ vertices and 1536 faces\)/);assert.throws(() => evaluateMeshStack(cube(), [{ op: 'subdivide', levels: 4 }], { maxVertices: 100 }), RangeError);});test('the recipe rejects levels out of range and a sharpness without a crease', () => {assert.throws(() => normalizeMeshEdits([{ op: 'subdivide', levels: 5 }]), /edits\[0\]\.levels: got 5; expected a whole number from 1 to 4/);assert.throws(() => normalizeMeshEdits([{ op: 'subdivide', levels: 0 }]), /levels/);- assert.throws(() => normalizeMeshEdits([{ op: 'subdivide', sharpness: 2 }]), /sharpness needs a crease rule/);+ assert.throws(() => normalizeMeshEdits([{ op: 'subdivide', sharpness: 2 }]), /edits\[0\]\.sharpness: got 2; expected left out unless a crease rule is given/);assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide', crease: { angle: 179 } }]), /selects no edges/);});diff --git a/tests/mesh-uv.test.js b/tests/mesh-uv.test.jsindex ce20e1ea..5ce84d13 100644--- a/tests/mesh-uv.test.js+++ b/tests/mesh-uv.test.js@@ -111,9 +111,9 @@ test('the edited crate unwraps into flat panels and renders with uvs', () => {test('uv_unwrap validates its fields and works as an unnamed stack node', () => {assert.deepEqual(normalizeMeshEdits([{ op: 'uv_unwrap' }])[0], { op: 'uv_unwrap', seams: { angle: 60 }, margin: 0.01, maxDistortion: 0.25 });- assert.throws(() => normalizeMeshEdits([{ op: 'uv_unwrap', seams: [1] }]), /seams must be an edge rule/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_unwrap', seams: [1] }]), /edits\[0\]\.seams: got \[1\]; expected an edge rule/);assert.throws(() => normalizeMeshEdits([{ op: 'uv_unwrap', margin: 0.5 }]), /margin/);- assert.throws(() => normalizeMeshEdits([{ op: 'uv_unwrap', name: 'x' }]), /does not take name/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_unwrap', name: 'x' }]), /edits\[0\]\.name: got "x"; expected one of the fields uv_unwrap takes/);assert.equal(normalizeMeshStack([{ op: 'uv_unwrap' }])[0].name, undefined);const scene = createAgentScene({format: '67js.scene', schemaVersion: 1,