3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Name the field, value and an example in tube, lathe, extrude and torus errors (#2074)
Nguyen Xuan An2c5aa591d100
diff --git a/changes/2074.md b/changes/2074.mdnew file mode 100644index 00000000..e7c3f43d--- /dev/null+++ b/changes/2074.md@@ -0,0 +1 @@+- Fix: `tube`, `lathe`, `extrude` and `torus` input errors now name the field (`geometries[1].path[2]`, `radius`, `profile`, `contour`, `arc`, `tubeRadius`), the value received and a working example; the tube radius and closed checks are two messages, a repeated point names its index and a self-crossing contour names the two segment indices (#2074)diff --git a/changes/2074.size.md b/changes/2074.size.mdnew file mode 100644index 00000000..2a96a0c8--- /dev/null+++ b/changes/2074.size.md@@ -0,0 +1,6 @@+- entry:core: Torus errors now name the field, the value and an example (+236 bytes gzip), and field-error.js joins core.+- entry:core+lazy: Same torus error text as entry:core.+- entry:modeling: Tube, lathe and extrude errors name the field, the value and an example, plus exported check functions that the scene path reuses (+536 bytes gzip).+- scene:agent-scene: The scene validator calls the shared check functions (+104 bytes gzip).+- scene:agent-scene+lazy: Same checks plus the modeling error text (+497 bytes gzip).+- goal:agent-scene: Agents that send a bad tube, lathe, extrude or torus now get the field path, the value and a working example instead of guessing, for 104 bytes gzip.diff --git a/docs/learn/procedural-modeling.md b/docs/learn/procedural-modeling.mdindex e2bf731d..eb7cb25c 100644--- a/docs/learn/procedural-modeling.md+++ b/docs/learn/procedural-modeling.md@@ -174,7 +174,7 @@ A `curve` point is `[x, y, z]` with automatic smooth handles, or `{ position, ha- **Expecting a solid Boolean.** These generators do not perform solid Boolean operations or provide a mesh editor. Build the pieces and place them with part matrices.- **A hole that touches the contour.** `extrude` throws `Every hole must lie strictly inside the contour.` Move the hole inward or make it smaller.-- **Consecutive duplicate points.** A path or profile with two identical neighbors throws. Remove the repeat.+- **Consecutive duplicate points.** A path or profile with two identical neighbors throws, naming the repeated point (`path[2]`). Remove the repeat.- **Looking for caps on an open tube.** `tube` leaves its ends open. Use `curve`, which adds flat caps, when the shape must be closed.- **A folded lathe profile.** A profile that doubles back can intersect itself.- **Generating inside the render loop.** Build once, then share the geometry. The renderer does not take new geometry after construction.diff --git a/docs/modeling.md b/docs/modeling.mdindex f83bf8e5..b1ee141d 100644--- a/docs/modeling.md+++ b/docs/modeling.md@@ -46,7 +46,7 @@ The base contour validation does not establish that an arbitrary bevel produces`tube(path, { radius = 0.1, segments = 64, radialSegments = 12, closed = false, maxVertices = 250000 })`sweeps a circular cross-section along a centripetal Catmull-Rom curve through XYZ points.Open paths need two points. Closed paths need three. Closed paths join the final sample back to the first.-Open tube ends have no caps. Paths can intersect themselves.+Open tube ends have no caps. Paths can intersect themselves. A bad radius, `closed` flag, profile, contour or torus arc throws an error that names the field, the value received and an example; in a scene recipe the field starts with `geometries[i]`.Segments range from 3 to 2048. Radial segments range from 3 to 128.diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 70258db9..3276a50b 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1,5 +1,5 @@import { mat4, mat3 } from 'gl-matrix';-import { box, circle, cone, cylinder, grid, icoSphere, sphere, torus } from './geometry.js';+import { box, checkTorusShape, circle, cone, cylinder, grid, icoSphere, sphere, torus } from './geometry.js';import { createSceneGraph } from './scene-graph.js';import { currentFormatName } from './legacy-names.js';import { invalidField, withFieldPrefix } from './field-error.js';@@ -595,14 +595,19 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {return 2 * sides * 2 + 2 * (sides + 1);}case 'torus':+ checkTorusShape(value.tubeRadius, value.arc);return (detail('segments', 96, 3, 2048) + 1) * (detail('sides', 24, 3, 128) + 1) + 2 * ((value.sides ?? 24) + 2);- case 'lathe':- return (detail('segments', 64, 3, 2048) + 1) * points(value.profile, 2, 2, 'profile');+ case 'lathe': {+ const profileCount = points(value.profile, 2, 2, 'profile');+ agentSceneModule('modeling').checkLatheProfile(value.profile);+ return (detail('segments', 64, 3, 2048) + 1) * profileCount;+ }case 'tube':points(value.path, 3, value.closed ? 3 : 2, 'path');if (value.closed !== undefined && typeof value.closed !== 'boolean') {throw invalidField('closed', value.closed, 'true or false', TypeError);}+ agentSceneModule('modeling').checkTubeInputs(value.path, value.radius ?? 0.1, value.closed ?? false);return (detail('segments', 64, 3, 2048) + 1) * (detail('radialSegments', 12, 3, 128) + 1);case 'curve': {if (['shape', 'splines', 'kind', 'weights', 'order', 'knots', 'knotMode', 'trim', 'grow'].some(field => value[field] !== undefined)) {@@ -636,6 +641,7 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {if (count > 4096) {throw invalidField('contour', `${count} points`, 'a contour and holes with at most 4096 points in total; simplify them');}+ agentSceneModule('modeling').checkExtrudeRings(value.contour, holes);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));}diff --git a/src/geometry.js b/src/geometry.jsindex 9d738ea3..165b4520 100644--- a/src/geometry.js+++ b/src/geometry.js@@ -1,3 +1,5 @@+import { invalidField } from './field-error.js';+const FULL_TURN = Math.PI * 2;const MAX_PRIMITIVE_VERTICES = 1_000_000;@@ -210,14 +212,22 @@ export function circle(segments = 64, innerRadius = 0) {return { ...geometry(positions, normals, indices), uvs: new Float32Array(uvs) };}-// The torus lies in XY, facing +Z. Partial arcs are useful for interrupted armor rings.-export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_TURN, start = 0) {+// The torus checks that name the field, so a scene recipe reports them as geometries[i].tubeRadius or geometries[i].arc.+export function checkTorusShape(tubeRadius = 0.08, arc = FULL_TURN) {finiteFloat(tubeRadius, 'tubeRadius');finiteFloat(arc, 'arc');- finiteFloat(start, 'start');- if (Math.fround(tubeRadius) <= 0 || Math.fround(arc) <= 0 || arc > FULL_TURN) {- throw new RangeError('tubeRadius must remain positive at Float32 precision and arc must be within (0, 2PI].');+ if (Math.fround(tubeRadius) <= 0) {+ throw invalidField('tubeRadius', tubeRadius, 'a positive number that is still above 0 as a Float32, such as 0.08');+ }+ if (Math.fround(arc) <= 0 || arc > FULL_TURN) {+ throw invalidField('arc', arc, `a number above 0 and at most ${FULL_TURN} (2 * Math.PI, a full turn), such as ${Math.PI}`);}+}++// The torus lies in XY, facing +Z. Partial arcs are useful for interrupted armor rings.+export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_TURN, start = 0) {+ checkTorusShape(tubeRadius, arc);+ finiteFloat(start, 'start');integer(segments, 3, 2048, 'segments');integer(sides, 3, 128, 'sides');primitiveBudget((segments + 1) * (sides + 1) + (arc === FULL_TURN ? 0 : 2 * (sides + 2)));diff --git a/src/modeling.js b/src/modeling.jsindex 4a6f5157..f2a1c60a 100644--- a/src/modeling.js+++ b/src/modeling.js@@ -1,3 +1,4 @@+import { invalidField } from './field-error.js';import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';import { sweepSamples } from './modeling-bezier.js';import { KNOT_MODES, NURBS_DEFAULT_ORDER, NURBS_MAX_ORDER, resampleSamples, sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';@@ -23,7 +24,11 @@ function pointsFrom(input, size, minimum, name) {return Array.from(point, value => finite(value, name));});for (let index = 1; index < points.length; index++) {- if (points[index].every((value, axis) => value === points[index - 1][axis])) throw new RangeError(`${name} cannot contain consecutive duplicate points.`);+ const previous = points[index - 1];+ if (points[index].every((value, axis) => value === previous[axis])) {+ const moved = previous.map((value, axis) => axis === 0 ? value + 1 : value);+ throw invalidField(`${name}[${index}]`, points[index], `a point different from ${name}[${index - 1}], since consecutive duplicate points are not allowed and both are ${JSON.stringify(previous)}; move or remove one, such as ${JSON.stringify(moved)}`);+ }}return points;}@@ -92,6 +97,15 @@ function meshFrom(source, maximum) {return { positions, normals, uvs, indices };}+/** Check a lathe profile of [radius, height] points and return it as numbers. Errors name the field, so a scene recipe adds geometries[i]. */+export function checkLatheProfile(profile) {+ const points = pointsFrom(profile, 2, 2, 'profile');+ if (points.some(point => point[0] < 0) || !points.some(point => point[0] > 0)) {+ throw invalidField('profile', profile, 'points whose radii (the first number of each) are 0 or more, with at least one radius above 0, such as [[0, 0], [0.5, 1]]');+ }+ return points;+}+/** Revolve a radius/height profile around Y. */export function lathe(profile, { segments = 64, startAngle = 0, sweep = Math.PI * 2, maxVertices = DEFAULT_VERTEX_LIMIT } = {}) {integer(segments, 3, 2048, 'segments');@@ -99,8 +113,7 @@ export function lathe(profile, { segments = 64, startAngle = 0, sweep = Math.PIstartAngle %= Math.PI * 2;finite(sweep, 'sweep');if (sweep <= 0 || sweep > Math.PI * 2) throw new RangeError('sweep must be greater than zero and at most one full turn.');- const points = pointsFrom(profile, 2, 2, 'profile');- if (points.some(point => point[0] < 0) || !points.some(point => point[0] > 0)) throw new RangeError('Profile radii must be nonnegative, with at least one positive radius.');+ const points = checkLatheProfile(profile);checkBudget((segments + 1) * points.length, maxVertices);return meshFrom(buildLathe(points, segments, startAngle, sweep), maxVertices);}@@ -134,7 +147,9 @@ function ringFrom(input, name) {for (let other = index + 1; other < points.length; other++) {const otherNext = (other + 1) % points.length;if (other === next || otherNext === index) continue;- if (intersects(points[index], points[next], points[other], points[otherNext])) throw new RangeError(`${name} cannot intersect or touch itself.`);+ if (intersects(points[index], points[next], points[other], points[otherNext])) {+ throw invalidField(name, `segments ${index} and ${other} cross or touch`, `a contour whose edges never intersect or touch, where segment ${index} runs from ${name}[${index}] to ${name}[${next}] and segment ${other} from ${name}[${other}] to ${name}[${otherNext}]; move one of those points, such as [[0, 0], [1, 0], [1, 1], [0, 1]]`);+ }}}if (area === 0) throw new RangeError(`${name} must enclose a nonzero area.`);@@ -243,6 +258,14 @@ function closeTJunctions(geometry) {};}+/** Check the contour and hole rings of an extrusion. Errors name the field (contour, holes[0]), so a scene recipe adds geometries[i]. */+export function checkExtrudeRings(contour, holes = []) {+ return {+ outer: ringFrom(contour, 'contour'),+ inner: holes.map((hole, index) => ringFrom(hole, `holes[${index}]`)),+ };+}+/** Extrude a simple XY contour and disjoint enclosed holes along positive Z. */export function extrude(contour, {holes = [], depth = 1, steps = 1, bevel = 0, bevelThickness = bevel,@@ -257,8 +280,7 @@ export function extrude(contour, {if (!Array.isArray(holes) || holes.length > 128) throw new RangeError('holes must be an array with at most 128 rings.');const inputPoints = (contour?.length ?? 0) + holes.reduce((count, hole) => count + (hole?.length ?? 0), 0);if (inputPoints > MAX_INPUT_POINTS + holes.length + 1) throw new RangeError(`Contours and holes must contain at most ${MAX_INPUT_POINTS} total points.`);- const outer = ringFrom(contour, 'contour');- const inner = holes.map((hole, index) => ringFrom(hole, `hole ${index}`));+ const { outer, inner } = checkExtrudeRings(contour, holes);const totalPoints = outer.length + inner.reduce((count, ring) => count + ring.length, 0);if (totalPoints > MAX_INPUT_POINTS) throw new RangeError(`Contours and holes must contain at most ${MAX_INPUT_POINTS} total points.`);const beveled = bevel > 0 || bevelThickness > 0;@@ -540,18 +562,27 @@ export function curve(points, {return curveSet([{ points, closed, kind, weights, order, knots, knotMode, trim }], { radius, taper, profile, resolution, radialSegments, maxVertices }, 'points');}+/** Check the radius, closed flag and path of a tube and return the path points. Errors name the field, so a scene recipe adds geometries[i]. */+export function checkTubeInputs(path, radius, closed) {+ if (!(radius > 0)) throw invalidField('radius', radius, 'a number above 0, such as 0.1');+ if (typeof closed !== 'boolean') throw invalidField('closed', closed, 'true or false, such as false', TypeError);+ const points = pointsFrom(path, 3, closed ? 3 : 2, 'path');+ if (closed && points[0].every((value, axis) => value === points.at(-1)[axis])) points.pop();+ if (points.length < (closed ? 3 : 2)) {+ throw invalidField('path', path, `a path with at least ${closed ? 3 : 2} different points once the repeated end point of a closed path is dropped, such as [[0, 0, 0], [1, 0, 0], [1, 1, 0]]`);+ }+ return points;+}+/** Sweep a circular tube along a centripetal Catmull-Rom curve. */export function tube(path, {radius = 0.1, segments = 64, radialSegments = 12, closed = false,maxVertices = DEFAULT_VERTEX_LIMIT,} = {}) {radius = finite(radius, 'radius');- if (radius <= 0 || typeof closed !== 'boolean') throw new RangeError('radius must be positive and closed must be boolean.');integer(segments, 3, 2048, 'segments');integer(radialSegments, 3, 128, 'radialSegments');- const points = pointsFrom(path, 3, closed ? 3 : 2, 'path');- if (closed && points[0].every((value, axis) => value === points.at(-1)[axis])) points.pop();- if (points.length < (closed ? 3 : 2)) throw new RangeError('The path has too few distinct points.');+ const points = checkTubeInputs(path, radius, closed);checkBudget((segments + 1) * (radialSegments + 1), maxVertices);return meshFrom(buildTube(points, closed, radius, segments, radialSegments), maxVertices);}diff --git a/tests/actionable-errors-geometry-builders.test.js b/tests/actionable-errors-geometry-builders.test.jsnew file mode 100644index 00000000..70f14849--- /dev/null+++ b/tests/actionable-errors-geometry-builders.test.js@@ -0,0 +1,54 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';+import { torus } from '../src/geometry.js';+import { extrude, lathe, tube } from '../src/modeling.js';++await loadAllAgentSceneModules();++function recipeWith(geometry) {+ return {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }, { id: 'part', ...geometry }],+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],+ nodes: [{ id: 'part', geometry: 'part', material: 'paint' }],+ };+}++const BOW_TIE = [[0, 0], [1, 1], [1, 0], [0, 1]];++// Each row: the geometry, the field path the agent must see, what it received, and a phrase of the fix with its example.+const CASES = [+ ['tube with a repeated point', { type: 'tube', path: [[0, 0, 0], [1, 0, 0], [1, 0, 0]] }, 'geometries[1].path[2]', '[1,0,0]', 'a point different from path[1], since consecutive duplicate points'],+ ['tube with radius 0', { type: 'tube', path: [[0, 0, 0], [1, 0, 0]], radius: 0 }, 'geometries[1].radius', '0', 'a number above 0, such as 0.1'],+ ['tube with a closed flag that is not a boolean', { type: 'tube', path: [[0, 0, 0], [1, 0, 0], [1, 1, 0]], closed: 'yes' }, 'geometries[1].closed', '"yes"', 'true or false'],+ ['lathe with only zero radii', { type: 'lathe', profile: [[0, 0], [0, 1]] }, 'geometries[1].profile', '[[0,0],[0,1]]', 'such as [[0, 0], [0.5, 1]]'],+ ['extrude with a bow-tie contour', { type: 'extrude', contour: BOW_TIE }, 'geometries[1].contour', '"segments 0 and 2 cross or touch"', 'segment 0 runs from contour[0] to contour[1] and segment 2 from contour[2] to contour[3]'],+ ['extrude with a repeated hole point', { type: 'extrude', contour: [[0, 0], [4, 0], [4, 4], [0, 4]], holes: [[[1, 1], [1, 1], [2, 1], [2, 2]]] }, 'geometries[1].holes[0][1]', '[1,1]', 'a point different from holes[0][0]'],+ ['torus with arc 0', { type: 'torus', arc: 0 }, 'geometries[1].arc', '0', 'a number above 0 and at most 6.283185307179586'],+ ['torus with tubeRadius 0', { type: 'torus', tubeRadius: 0 }, 'geometries[1].tubeRadius', '0', 'a positive number that is still above 0 as a Float32, such as 0.08'],+];++for (const [name, geometry, path, received, expectation] of CASES) {+ test(`${name} names its field, the value received and a fix`, () => {+ assert.throws(() => createAgentScene(recipeWith(geometry), {}, {}), error => {+ assert.ok(error.message.startsWith(`${path}: got ${received}; expected `), `message was: ${error.message}`);+ assert.ok(error.message.includes(expectation), `message was: ${error.message}`);+ assert.equal(error.fieldPath, path);+ return true;+ });+ });+}++test('a geometry nested as a mesh base reports the same field errors', () => {+ const recipe = recipeWith({ type: 'mesh', base: { type: 'tube', path: [[0, 0, 0], [1, 0, 0]], radius: -1 } });+ assert.throws(() => createAgentScene(recipe, {}, {}), /radius: got -1; expected a number above 0, such as 0\.1/);+});++test('the builders called directly report field paths without a geometries index', () => {+ assert.throws(() => tube([[0, 0, 0], [1, 0, 0]], { radius: 0 }), /^RangeError: radius: got 0; expected a number above 0/);+ assert.throws(() => tube([[0, 0, 0], [1, 0, 0]], { closed: 1 }), /^TypeError: closed: got 1; expected true or false/);+ assert.throws(() => lathe([[0, 0], [0, 1]]), /^RangeError: profile: got \[\[0,0\],\[0,1\]\]; expected points/);+ assert.throws(() => extrude(BOW_TIE), /^RangeError: contour: got "segments 0 and 2 cross or touch"; expected/);+ assert.throws(() => torus(0.08, 96, 24, 0), /^RangeError: arc: got 0; expected a number above 0/);+});