Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Name the field, the value and an example in physics, drive, asset, placement and shrinkwrap errors (issue #653)

Nguyen Xuan An6812e05e1ba9
diff --git a/changes/653.md b/changes/653.md
index c442c999..6264f806 100644
--- a/changes/653.md
+++ b/changes/653.md
@@ -1 +1,2 @@
- Validation errors for materials, nodes, the camera, lights, fog, bake, mesh edits and motion now read `materials[2].emissiveColor: got [-1,0,0]; expected three numbers of 0 or more, such as [1, 0.5, 0.2].`: the full field path, the value received (cut at 40 characters) and a range, a list of choices or an example. Schema errors from the MCP tools add the received value too (`recipe.materials.0.color.2: Too big: expected number to be <=1 (got 2)`). Mesh edit errors keep the position of the edit (`edits[1].segments`). Not every message in the engine is converted yet; the rest keep their older wording (#653)
+- The same readable errors now cover physics bodies, joints and ragdolls, vehicle drives (`motion.drive`, wheels, path, speed, lights), asset recipes and operations (root, overrides, animation, inspect, checkpoints), placed assets and the shrinkwrap edit: `motion.drive.wheels[1].node: got "Nope"; expected the name of a node in the asset, such as one scene_inspect lists.` Mesh-edit parameter checks that still say `Mesh edit 2 (...)` are not converted yet (#653)
diff --git a/changes/653.size.md b/changes/653.size.md
index 1b723f76..29ee69c6 100644
--- a/changes/653.size.md
+++ b/changes/653.size.md
@@ -1,3 +1,6 @@
- scene:agent-scene: error text grows by about 0.9 KB gzip (field path, received value and an example in each converted message, plus the 30-line field-error module); an agent that reads "emissiveColor: got [-1,0,0]; expected three numbers of 0 or more, such as [1, 0.5, 0.2]" fixes the input in one retry instead of guessing.
- goal:agent-scene: 888 bytes gzip of message text only, so that agent errors name the field, the value and an example; this is the issue's goal and nothing new runs unless a recipe is rejected.
- scene:agent-scene+lazy: the same message text, 1.5 KB gzip with the lazy mesh, motion and bake modules; nothing new runs unless a recipe is rejected.
+- entry:vehicle: 592 bytes gzip of message text in the vehicle kit (wheel, path, speed and light errors now name the field, the value and an example); nothing new runs unless a drive is rejected.
+- scene:agent-scene+lazy: another 1.5 KB gzip of message text in the physics, drive, asset, placement and shrinkwrap validators; nothing new runs unless a recipe is rejected, and an agent fixes the input in one retry.
+- goal:agent-scene: 11 bytes gzip in the core bundle, the rest of the text sits in lazy modules.
diff --git a/src/agent-asset-mesh.js b/src/agent-asset-mesh.js
index 8a7ccade..9eab4cb8 100644
--- a/src/agent-asset-mesh.js
+++ b/src/agent-asset-mesh.js
@@ -1,4 +1,5 @@
import { agentSceneModule } from './agent-scene-modules.js';
+import { invalidField, withFieldPrefix } from './field-error.js';
import { generateCutterGeometry } from './agent-scene.js';
import { IMPORTED_MESH_EDIT_LIMITS } from './mesh-operations.js';
import { MESH_SMOOTH_ANGLE_DEFAULT } from './agent-scene-capabilities.js';
@@ -19,20 +20,20 @@ function partIdList(records) {
export function normalizeMeshEditEntries(input, records) {
if (input === undefined) return [];
if (!Array.isArray(input) || input.length > IMPORTED_MESH_EDIT_LIMITS.maxEditedParts) {
- throw new RangeError(`meshEdits must be an array of at most ${IMPORTED_MESH_EDIT_LIMITS.maxEditedParts} parts.`);
+ throw invalidField('meshEdits', Array.isArray(input) ? input.length : input, `an array of at most ${IMPORTED_MESH_EDIT_LIMITS.maxEditedParts} parts, such as [{ "id": "mesh-0", "edits": [] }]`);
}
const seen = new Set();
const entries = [];
- for (const entry of input) {
+ for (const [index, entry] of input.entries()) {
const unknownKey = Object.keys(entry ?? {}).find(key => key !== 'id' && key !== 'edits');
if (!entry || typeof entry !== 'object' || unknownKey || !Array.isArray(entry.edits)) {
- throw new TypeError('Each meshEdits entry is { id, edits } with an edits array.');
+ throw invalidField(`meshEdits[${index}]${unknownKey ? `.${unknownKey}` : ''}`, unknownKey ? entry[unknownKey] : entry, 'an object with only id and edits, such as { "id": "mesh-0", "edits": [] }', TypeError);
}
if (!records.some(record => record.id === entry.id) || seen.has(entry.id)) {
- throw new RangeError(`Unknown or repeated mesh ID: ${entry.id}. Imported mesh IDs are ${partIdList(records.slice(0, 8))}...; scene_inspect lists them.`);
+ throw invalidField(`meshEdits[${index}].id`, entry.id, `an imported mesh ID used once, such as ${partIdList(records.slice(0, 3))}; scene_inspect lists them`);
}
seen.add(entry.id);
- agentSceneModule('mesh').normalizeMeshEdits(entry.edits);
+ withFieldPrefix(`meshEdits[${index}]`, () => agentSceneModule('mesh').normalizeMeshEdits(entry.edits));
if (entry.edits.length) entries.push({ id: entry.id, edits: structuredClone(entry.edits) });
}
return entries;
@@ -41,13 +42,13 @@ export function normalizeMeshEditEntries(input, records) {
/** The recipe's meshEdits after one `edit-mesh` operation: edits append to the part's log, or replace it. */
export function meshEditEntriesAfter(entries, operation, records) {
if (!records.some(record => record.id === operation.geometry)) {
- throw new RangeError(`Unknown mesh ID: ${operation.geometry}. Imported mesh IDs are ${partIdList(records.slice(0, 8))}...; scene_inspect lists them.`);
+ throw invalidField('geometry', operation.geometry, `an imported mesh ID such as ${partIdList(records.slice(0, 3))}; scene_inspect lists them`);
}
if (typeof operation.replace !== 'undefined' && typeof operation.replace !== 'boolean') {
- throw new TypeError('replace must be boolean.');
+ throw invalidField('replace', operation.replace, 'true or false', TypeError);
}
if (!Array.isArray(operation.edits)) {
- throw new TypeError('edit-mesh needs an edits array.');
+ throw invalidField('edits', operation.edits, 'an array of edits, such as [{ "op": "subdivide", "levels": 1 }]', TypeError);
}
const existing = entries.find(entry => entry.id === operation.geometry);
const edits = operation.replace || !existing ? operation.edits : [...existing.edits, ...operation.edits];
diff --git a/src/agent-asset.js b/src/agent-asset.js
index bbde83de..b7035c5a 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -12,6 +12,7 @@ import { createFootLock } from './foot-lock.js';
import { clipFromGltfAnimation, createAssetLayerEvaluator, morphClipFromGltfAnimation } from './skeleton-pose.js';
import { registerAgentSceneModule, agentSceneModule } from './agent-scene-modules.js';
import { normalizeMeshEditEntries, meshEditEntriesAfter, realizeMeshEdits, meshEditSignature } from './agent-asset-mesh.js';
+import { invalidField, withFieldPrefix } from './field-error.js';
registerAgentSceneModule('motion', agentMotion);
@@ -44,11 +45,11 @@ export const AGENT_ASSET_CAPABILITIES = Object.freeze({
function knownKeys(value, fields, label) {
if (!value || typeof value !== 'object' || Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) {
- throw new TypeError(`${label} must be a plain JSON object.`);
+ throw invalidField(label, value, 'a plain JSON object, such as {}', TypeError);
}
for (const key of Object.keys(value)) {
if (!fields.includes(key)) {
- throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${fields.join(", ")}.`);
+ throw invalidField(`${label}.${key}`, value[key], `no such field; use one of ${fields.join(', ')}`, TypeError);
}
}
}
@@ -128,21 +129,24 @@ function copiedJson(input) {
function vector(value, length, label) {
if (!Array.isArray(value) || value.length !== length ||
!value.every(component => typeof component === 'number' && Number.isFinite(Math.fround(component)))) {
- throw new TypeError(`${label} requires ${length} finite Float32 numbers.`);
+ throw invalidField(label, value, `an array of ${length} finite numbers, such as [${Array(length).fill(1).join(', ')}]`, TypeError);
}
return [...value];
}
-function rootFrom(input = {}) {
- knownKeys(input, ROOT_FIELDS, 'root');
+function rootFrom(input = {}, path = 'root') {
+ knownKeys(input, ROOT_FIELDS, path);
const root = {
- translation: vector(input.translation === undefined ? [0, 0, 0] : input.translation, 3, 'root translation'),
- rotation: vector(input.rotation === undefined ? [0, 0, 0, 1] : input.rotation, 4, 'root rotation'),
- scale: vector(input.scale === undefined ? [1, 1, 1] : input.scale, 3, 'root scale'),
+ translation: vector(input.translation === undefined ? [0, 0, 0] : input.translation, 3, `${path}.translation`),
+ rotation: vector(input.rotation === undefined ? [0, 0, 0, 1] : input.rotation, 4, `${path}.rotation`),
+ scale: vector(input.scale === undefined ? [1, 1, 1] : input.scale, 3, `${path}.scale`),
};
const rotationLength = Math.hypot(...root.rotation);
if (rotationLength === 0 || root.scale.some(component => Math.fround(component) <= 0)) {
- throw new RangeError('Root needs a nonzero quaternion and positive Float32 scales.');
+ if (rotationLength === 0) {
+ throw invalidField(`${path}.rotation`, input.rotation, 'a quaternion that is not all zero, such as [0, 0, 0, 1]');
+ }
+ throw invalidField(`${path}.scale`, root.scale, 'positive numbers, such as [1, 1, 1]');
}
root.rotation = root.rotation.map(component => component / rotationLength);
return root;
@@ -328,7 +332,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
const initialRecipe = copiedJson(inputRecipe);
const assetId = initialRecipe?.assetId;
if (typeof assetId !== 'string' || !/^[a-f0-9]{64}$/i.test(assetId)) {
- throw new TypeError('assetId must contain 64 SHA256 hexadecimal characters.');
+ throw invalidField('assetId', assetId, '64 hexadecimal characters, such as "ab12..." (the SHA256 that scene_create_asset returned)', TypeError);
}
const canonicalAssetId = assetId.toLowerCase();
const cameraOmitted = !Object.hasOwn(initialRecipe, 'camera');
@@ -375,15 +379,15 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
}
const sourceNode = sourceNodes.get(id);
if (!sourceNode) {
- throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; call scene_inspect without ids to list them, or with kind hierarchy for source nodes.`);
+ throw invalidField('geometry', id, 'an imported mesh ID such as "mesh-0"; call scene_inspect without ids to list them, or with kind hierarchy for source nodes');
}
const partIds = sourceNode.meshIds ?? [];
if (partIds.length === 0) {
- throw new RangeError(`Source node ${id} has no mesh of its own. Inspect a mesh ID such as mesh-0, or call scene_inspect with kind hierarchy to see which nodes hold parts.`);
+ throw invalidField('geometry', id, 'a source node with a mesh of its own, or a mesh ID such as "mesh-0"; call scene_inspect with kind hierarchy to see which nodes hold parts');
}
if (partIds.length > 1) {
const listed = partIds.slice(0, 8).join(', ');
- throw new RangeError(`Source node ${id} holds ${partIds.length} parts: ${listed}${partIds.length > 8 ? ', ...' : ''}. Pass the part IDs you want.`);
+ throw invalidField('geometry', id, `one part ID, such as "${partIds[0]}"; this source node holds ${partIds.length} parts: ${listed}${partIds.length > 8 ? ', ...' : ''}`);
}
return records.find(value => value.id === partIds[0]);
}
@@ -438,18 +442,20 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion', 'physics', 'meshEdits'], 'asset recipe');
if (candidate.format !== '67js.asset' || candidate.schemaVersion !== 1 ||
typeof candidate.assetId !== 'string' || candidate.assetId.toLowerCase() !== canonicalAssetId) {
- throw new RangeError('Expected the bound 67js.asset schemaVersion 1 assetId.');
+ const wrongField = candidate.format !== '67js.asset' ? 'format' : candidate.schemaVersion !== 1 ? 'schemaVersion' : 'assetId';
+ const expectedValue = wrongField === 'format' ? '"67js.asset"' : wrongField === 'schemaVersion' ? '1' : `the bound asset ID, such as "${canonicalAssetId.slice(0, 8)}..."`;
+ throw invalidField(wrongField, candidate[wrongField], expectedValue);
}
const overrides = candidate.materialOverrides === undefined ? [] : candidate.materialOverrides;
if (!Array.isArray(overrides) || overrides.length > materialRecords.size) {
- throw new RangeError('materialOverrides must be an array within the decoded material count.');
+ throw invalidField('materialOverrides', Array.isArray(overrides) ? `${overrides.length} entries` : overrides, `an array of at most ${materialRecords.size} entries, one per decoded material, such as []`);
}
const seen = new Set();
- const definitions = overrides.map(override => {
- knownKeys(override, ['id', ...MATERIAL_FIELDS], 'material override');
+ const definitions = overrides.map((override, index) => {
+ knownKeys(override, ['id', ...MATERIAL_FIELDS], `materialOverrides[${index}]`);
const original = materialRecords.get(override.id);
if (!original || seen.has(override.id)) {
- throw new RangeError('Material override IDs must exist and be distinct.');
+ throw invalidField(`materialOverrides[${index}].id`, override.id, `the ID of a decoded material, used once; one of ${[...materialRecords.keys()].slice(0, 5).join(', ')}`);
}
seen.add(override.id);
return { id: override.id, ...original.baseline, ...override };
@@ -467,29 +473,33 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
const animation = candidate.animation === undefined ? null : candidate.animation;
if (animation !== null) {
knownKeys(animation, ['clip', 'time'], 'animation');
+ const clipCount = asset.animations.length;
const clip = asset.animations[animation.clip];
if (!Number.isInteger(animation.clip) || !clip || !Number.isFinite(animation.time) ||
animation.time < 0 || animation.time > clip.duration) {
- throw new RangeError('Animation needs an existing clip and time within its duration.');
+ if (!Number.isInteger(animation.clip) || !clip) {
+ throw invalidField('animation.clip', animation.clip, clipCount === 0 ? 'no animation, since this asset has no clips; drop it, such as null' : `a clip index from 0 to ${clipCount - 1}, such as 0`);
+ }
+ throw invalidField('animation.time', animation.time, `seconds from 0 to ${clip.duration}, such as 0`);
}
}
const nodeOverrides = candidate.nodeOverrides === undefined ? [] : candidate.nodeOverrides;
if (!Array.isArray(nodeOverrides) || nodeOverrides.length > sourceNodes.size) {
- throw new RangeError('nodeOverrides must fit the decoded source-node count.');
+ throw invalidField('nodeOverrides', Array.isArray(nodeOverrides) ? `${nodeOverrides.length} entries` : nodeOverrides, `an array of at most ${sourceNodes.size} entries, one per source node, such as []`);
}
const seenNodes = new Set();
- const normalizedNodes = nodeOverrides.map(override => {
- knownKeys(override, ['id', ...ROOT_FIELDS], 'node override');
+ const normalizedNodes = nodeOverrides.map((override, index) => {
+ knownKeys(override, ['id', ...ROOT_FIELDS], `nodeOverrides[${index}]`);
const node = sourceNodes.get(override.id);
if (!node || seenNodes.has(override.id) || !node.editable) {
- throw new RangeError('Node override IDs must exist, be editable and be distinct.');
+ throw invalidField(`nodeOverrides[${index}].id`, override.id, 'the ID of an editable source node, used once; call scene_inspect with kind hierarchy to list them');
}
seenNodes.add(override.id);
const fields = Object.keys(override).filter(field => field !== 'id');
if (!fields.length) {
- throw new RangeError('Node overrides need at least one local transform component.');
+ throw invalidField(`nodeOverrides[${index}]`, override, 'an id plus at least one of translation, rotation or scale, such as { "id": "node-1", "translation": [0, 1, 0] }');
}
- const transform = rootFrom(Object.fromEntries(fields.map(field => [field, override[field]])));
+ const transform = rootFrom(Object.fromEntries(fields.map(field => [field, override[field]])), `nodeOverrides[${index}]`);
return { id: override.id, ...Object.fromEntries(fields.map(field => [field, transform[field]])) };
});
const result = copiedJson({
@@ -502,7 +512,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
result.meshEdits = meshEdits;
}
if ((candidate.motion?.ik?.length || candidate.motion?.footLock) && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {
- throw new RangeError('Motion ik and footLock need a uniform asset root scale.');
+ throw invalidField('root.scale', result.root.scale, 'the same number on every axis, such as [1, 1, 1], because motion ik and footLock need a uniform asset root scale');
}
result.motion = agentMotion.normalizeAgentMotion(candidate.motion, motionRecipe(result));
if (candidate.physics !== undefined && candidate.physics !== null) {
@@ -530,7 +540,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
return {
nodes: [...sourceNodes.values()].filter(node => node.editable),
materials: [...baselines.values()], camera: candidate.camera,
- buildDrive, normalizeDrive: input => agentSceneModule('drive').normalizeDrive(input), ikHierarchy: [...sourceNodes.values()], clipLayerContext, morphTargets: [...morphTargetIndex.keys()],
+ buildDrive, normalizeDrive: (input, path) => agentSceneModule('drive').normalizeDrive(input, path), ikHierarchy: [...sourceNodes.values()], clipLayerContext, morphTargets: [...morphTargetIndex.keys()],
ikRootMatrix: Array.from(mat4.fromRotationTranslationScale(mat4.create(), root.rotation, root.translation, [root.scale[0], root.scale[0], root.scale[0]])),
};
}
@@ -813,7 +823,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
function expected(options) {
knownKeys(options, ['expectedRevision'], 'transaction options');
if (!Number.isSafeInteger(options.expectedRevision) || options.expectedRevision !== revision) {
- throw new RangeError('expectedRevision must match the current revision.');
+ throw invalidField('expectedRevision', options.expectedRevision, `the current revision, such as ${revision}`);
}
}
@@ -850,7 +860,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
provideMotionSources,
sampleMotion(time) {
if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
- throw new RangeError('Motion sample time must be null or within zero and 3600.');
+ throw invalidField('motionTime', time, 'null, or seconds from 0 to 3600, such as 0.5');
}
publish(recipe, false, false, time);
return motionTime;
@@ -860,7 +870,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
knownKeys(frame, ['animation', 'motionTime'], 'asset frame');
const time = frame.motionTime === undefined ? motionTime : frame.motionTime;
if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
- throw new RangeError('Motion sample time must be null or within zero and 3600.');
+ throw invalidField('motionTime', time, 'null, or seconds from 0 to 3600, such as 0.5');
}
publish(recipe, false, false, time, frame.animation);
return motionTime;
@@ -868,14 +878,15 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
apply(inputOperations, options = {}) {
expected(options);
if (!Array.isArray(inputOperations) || !inputOperations.length || inputOperations.length > MAX_OPERATIONS) {
- throw new RangeError('Asset operations must contain 1 to 256 commands.');
+ throw invalidField('operations', Array.isArray(inputOperations) ? `${inputOperations.length} commands` : inputOperations, `an array of 1 to ${MAX_OPERATIONS} commands, such as [{ "type": "set-root", "translation": [0, 1, 0] }]`);
}
const operations = copiedJson(inputOperations);
const candidate = structuredClone(recipe);
- for (const operation of operations) {
+ for (const [operationIndex, operation] of operations.entries()) {
+ const path = `operations[${operationIndex}]`;
const lookField = Object.hasOwn(LOOK_OPERATIONS, operation.type) ? LOOK_OPERATIONS[operation.type] : null;
if (lookField) {
- knownKeys(operation, ['type', lookField], 'operation');
+ knownKeys(operation, ['type', lookField], path);
const patch = operation[lookField];
knownKeys(patch, Object.keys(candidate[lookField]), lookField);
const nested = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;
@@ -886,39 +897,39 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
}
candidate[lookField] = merged;
} else if (operation.type === 'set-camera') {
- knownKeys(operation, ['type', ...Object.keys(candidate.camera)], 'operation');
+ knownKeys(operation, ['type', ...Object.keys(candidate.camera)], path);
for (const field of Object.keys(candidate.camera)) {
if (Object.hasOwn(operation, field)) {
candidate.camera[field] = operation[field];
}
}
} else if (operation.type === 'set-root') {
- knownKeys(operation, ['type', ...ROOT_FIELDS], 'operation');
+ knownKeys(operation, ['type', ...ROOT_FIELDS], path);
for (const field of ROOT_FIELDS) {
if (Object.hasOwn(operation, field)) {
candidate.root[field] = operation[field];
}
}
} else if (operation.type === 'set-motion') {
- knownKeys(operation, ['type', 'motion'], 'operation');
+ knownKeys(operation, ['type', 'motion'], path);
if (!Object.hasOwn(operation, 'motion')) {
- throw new TypeError('set-motion requires a motion record or explicit null.');
+ throw invalidField(`${path}.motion`, undefined, 'a motion record, or null to clear it, such as null', TypeError);
}
candidate.motion = operation.motion;
} else if (operation.type === 'set-physics') {
- knownKeys(operation, ['type', 'physics'], 'operation');
+ knownKeys(operation, ['type', 'physics'], path);
if (!Object.hasOwn(operation, 'physics')) {
- throw new TypeError('set-physics requires physics; use null to clear it.');
+ throw invalidField(`${path}.physics`, undefined, 'a physics record, or null to clear it, such as null', TypeError);
}
candidate.physics = operation.physics;
} else if (operation.type === 'set-asset-node') {
- knownKeys(operation, ['type', 'id', ...ROOT_FIELDS], 'operation');
+ knownKeys(operation, ['type', 'id', ...ROOT_FIELDS], path);
if (!sourceNodes.has(operation.id)) {
- throw new RangeError(`Unknown source-node ID: ${operation.id}.`);
+ throw invalidField(`${path}.id`, operation.id, 'the ID of a source node; call scene_inspect with kind hierarchy to list them');
}
const fields = ROOT_FIELDS.filter(field => Object.hasOwn(operation, field));
if (!fields.length) {
- throw new TypeError('set-asset-node needs a local transform component.');
+ throw invalidField(path, operation, 'an id plus at least one of translation, rotation or scale, such as { "type": "set-asset-node", "id": "node-1", "translation": [0, 1, 0] }', TypeError);
}
let override = candidate.nodeOverrides.find(value => value.id === operation.id);
if (!override) {
@@ -929,10 +940,10 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
override[field] = operation[field];
}
} else if (operation.type === 'set-animation') {
- knownKeys(operation, ['type', 'clip', 'time'], 'operation');
+ knownKeys(operation, ['type', 'clip', 'time'], path);
if (operation.clip === null) {
if (Object.hasOwn(operation, 'time')) {
- throw new TypeError('Returning to the initial pose requires clip:null with time omitted.');
+ throw invalidField(`${path}.time`, operation.time, 'no time when clip is null, which returns to the initial pose; drop time', TypeError);
}
candidate.animation = null;
} else {
@@ -942,9 +953,9 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
candidate.animation = { clip, time };
}
} else if (operation.type === 'set-material') {
- knownKeys(operation, ['type', 'id', ...MATERIAL_FIELDS], 'operation');
+ knownKeys(operation, ['type', 'id', ...MATERIAL_FIELDS], path);
if (!materialRecords.has(operation.id)) {
- throw new RangeError(`Unknown material ID: ${operation.id}.`);
+ throw invalidField(`${path}.id`, operation.id, `the ID of a decoded material, one of ${[...materialRecords.keys()].slice(0, 5).join(', ')}`);
}
let override = candidate.materialOverrides.find(value => value.id === operation.id);
if (!override) {
@@ -957,10 +968,10 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
}
}
} else if (operation.type === 'edit-mesh') {
- knownKeys(operation, ['type', 'geometry', 'edits', 'replace'], 'operation');
- candidate.meshEdits = meshEditEntriesAfter(candidate.meshEdits ?? [], operation, records);
+ knownKeys(operation, ['type', 'geometry', 'edits', 'replace'], path);
+ candidate.meshEdits = withFieldPrefix(path, () => meshEditEntriesAfter(candidate.meshEdits ?? [], operation, records));
} else {
- throw new TypeError('Unsupported asset operation. Imported parts take edit-mesh (mesh_edit with a mesh ID such as mesh-0); other geometry changes are unavailable.');
+ throw invalidField(`${path}.type`, operation.type, 'one of set-camera, set-root, set-motion, set-physics, set-asset-node, set-animation, set-material or edit-mesh, such as "set-root"; imported parts take edit-mesh with a mesh ID such as mesh-0', TypeError);
}
}
return publish(candidate);
@@ -971,23 +982,29 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
const limit = options.limit === undefined ? 64 : options.limit;
if (!Number.isInteger(limit) || limit < 1 || limit > 256 ||
(options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean')) {
- throw new RangeError('Inspection needs limit from 1 to 256 and boolean includeBounds.');
+ if (options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean') {
+ throw invalidField('includeBounds', options.includeBounds, 'true or false');
+ }
+ throw invalidField('limit', limit, 'a whole number from 1 to 256, such as 64');
}
const offset = options.offset === undefined ? 0 : options.offset;
if (!Number.isInteger(offset) || offset < 0 || offset > 4096 ||
(options.kind !== undefined && !['meshes', 'hierarchy'].includes(options.kind))) {
- throw new RangeError('Inspection kind must be meshes or hierarchy with an offset from zero to 4096.');
+ if (options.kind !== undefined && !['meshes', 'hierarchy'].includes(options.kind)) {
+ throw invalidField('kind', options.kind, 'one of meshes, hierarchy');
+ }
+ throw invalidField('offset', offset, 'a whole number from 0 to 4096, such as 0');
}
if (options.kind === 'hierarchy') {
if (options.includeBounds) {
- throw new TypeError('Hierarchy inspection has no deformed silhouette bounds. Drop includeBounds, or inspect without kind to get mesh bounds.');
+ throw invalidField('includeBounds', options.includeBounds, 'false for kind hierarchy, which has no deformed silhouette bounds; drop it, or inspect without kind to get mesh bounds', TypeError);
}
if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > sourceNodes.size)) {
- throw new RangeError('Hierarchy IDs must fit the source-node count.');
+ throw invalidField('ids', Array.isArray(options.ids) ? `${options.ids.length} IDs` : options.ids, `an array of at most ${sourceNodes.size} source-node IDs, such as []`);
}
const selected = options.ids === undefined ? [...sourceNodes.values()] : options.ids.map(id => {
if (!sourceNodes.has(id)) {
- throw new RangeError(`Unknown source-node ID: ${id}.`);
+ throw invalidField('ids', id, 'the ID of a source node; call scene_inspect with kind hierarchy to list them');
}
return sourceNodes.get(id);
});
@@ -998,12 +1015,12 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null };
}
if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > records.length)) {
- throw new RangeError('Inspection IDs must be an array within the decoded part count.');
+ throw invalidField('ids', Array.isArray(options.ids) ? `${options.ids.length} IDs` : options.ids, `an array of at most ${records.length} mesh IDs, such as ["mesh-0"]`);
}
const selected = options.ids === undefined ? records : options.ids.map(id => partRecordFor(id));
const visible = selected.slice(offset, offset + limit);
if (options.includeBounds && visible.reduce((total, record) => total + geometryOf(record).positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {
- throw new RangeError('Bounds inspection exceeds two million authored base vertices. Select fewer meshes.');
+ throw invalidField('ids', `${visible.length} meshes`, 'fewer meshes, under two million authored base vertices in all, such as ["mesh-0"]');
}
const nodes = visible.map(record => {
const index = Number(record.id.slice(5));
@@ -1049,12 +1066,12 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
knownKeys(options, ['geometries'], 'mesh inspection');
const requested = options.geometries ?? records.slice(0, MAX_MESH_REPORTS).map(record => record.id);
if (!Array.isArray(requested) || requested.length > MAX_MESH_REPORTS) {
- throw new RangeError(`Inspect at most ${MAX_MESH_REPORTS} mesh IDs per call.`);
+ throw invalidField('geometries', Array.isArray(requested) ? `${requested.length} IDs` : requested, `an array of at most ${MAX_MESH_REPORTS} mesh IDs, such as ["mesh-0"]`);
}
const meshes = requested.map(id => {
const index = records.findIndex(record => record.id === id);
if (index < 0) {
- throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; scene_inspect lists them.`);
+ throw invalidField('geometries', id, 'an imported mesh ID such as "mesh-0"; scene_inspect lists them');
}
const record = records[index];
const edited = editedParts.get(id);
@@ -1079,7 +1096,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
},
checkpoint() {
if (checkpoints.size >= MAX_CHECKPOINTS) {
- throw new RangeError('Asset checkpoint budget exhausted. Release a checkpoint.');
+ throw invalidField('checkpoints', `${checkpoints.size} saved`, `at most ${MAX_CHECKPOINTS} saved checkpoints; release one first, such as with scene_release_checkpoint`);
}
const handle = Object.freeze({});
checkpoints.set(handle, structuredClone(recipe));
@@ -1088,13 +1105,13 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
restore(handle, options = {}) {
expected(options);
if (!checkpoints.has(handle)) {
- throw new RangeError('Unknown or released asset checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
+ throw invalidField('checkpointId', 'unknown or released', 'a checkpointId that scene_checkpoint returned and you have not released, such as the last one returned');
}
return publish(checkpoints.get(handle));
},
releaseCheckpoint(handle) {
if (!checkpoints.delete(handle)) {
- throw new RangeError('Unknown or released asset checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
+ throw invalidField('checkpointId', 'unknown or released', 'a checkpointId that scene_checkpoint returned and you have not released, such as the last one returned');
}
},
});
diff --git a/src/agent-drive-schema.js b/src/agent-drive-schema.js
index 8610e463..65de4331 100644
--- a/src/agent-drive-schema.js
+++ b/src/agent-drive-schema.js
@@ -1,3 +1,5 @@
+import { invalidField } from './field-error.js';
+
// Shape checks for the `drive` entry of an asset recipe's motion and of a placed asset. Pure validation with no vehicle
// code, so the recipe normalizers and the MCP server can use it without loading the drive (agent-drive.js).
@@ -15,113 +17,127 @@ const HEADLIGHT_FIELDS = ['id', 'position', 'direction'];
const TAIL_LIGHT_FIELDS = ['id', 'material', 'signal', 'off', 'on'];
const CAMERA_PATH_FIELDS = ['duration', 'loop', 'eye'];
-function knownKeys(value, allowed, label) {
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} must be an object.`);
+function knownKeys(value, allowed, path) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalidField(path, value, 'an object, such as {}', TypeError);
for (const key of Object.keys(value)) {
- if (!allowed.includes(key)) throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${allowed.join(', ')}.`);
+ if (!allowed.includes(key)) throw invalidField(`${path}.${key}`, value[key], `no such field; use one of ${allowed.join(', ')}`, TypeError);
}
}
-function vector(value, label) {
+function vector(value, path) {
if (!Array.isArray(value) || value.length !== 3 || value.some(component => !Number.isFinite(component))) {
- throw new TypeError(`${label} must be three finite numbers.`);
+ throw invalidField(path, value, 'an array of 3 finite numbers, such as [0, 0, 1]', TypeError);
}
return [...value];
}
-function nodeReference(value, label) {
- if (typeof value !== 'string' || !value || value.length > 256) throw new TypeError(`${label} must be a node label or id of 1 to 256 characters.`);
+function nodeReference(value, path) {
+ if (typeof value !== 'string' || !value || value.length > 256) throw invalidField(path, value, 'a node label or id of 1 to 256 characters, such as "wheel-front-left"', TypeError);
return value;
}
function normalizePath(path, label) {
if (Array.isArray(path)) {
if (path.length < 2 || path.length > DRIVE_LIMITS.maxPathPoints) {
- throw new RangeError(`${label} needs 2 to ${DRIVE_LIMITS.maxPathPoints} points.`);
+ throw invalidField(label, `${path.length} points`, `2 to ${DRIVE_LIMITS.maxPathPoints} points, such as [[0, 0, 0], [0, 0, 10]]`);
}
- return path.map((point, index) => vector(point, `${label} point ${index}`));
+ return path.map((point, index) => vector(point, `${label}[${index}]`));
}
knownKeys(path, CAMERA_PATH_FIELDS, label);
if (!path.eye || !Array.isArray(path.eye.keyframes) || path.eye.keyframes.length > DRIVE_LIMITS.maxPathPoints) {
- throw new TypeError(`${label} is an array of [x, y, z] points or a camera path { duration, eye: { keyframes } }.`);
+ throw invalidField(label, path, 'an array of [x, y, z] points, such as [[0, 0, 0], [0, 0, 10]], or a camera path such as { "duration": 5, "eye": { "keyframes": [] } }', TypeError);
}
return structuredClone(path);
}
-function normalizeWheels(wheels) {
+function normalizeWheels(wheels, path) {
if (wheels === 'auto') return wheels;
if (!Array.isArray(wheels) || wheels.length < 2 || wheels.length > DRIVE_LIMITS.maxWheels) {
- throw new RangeError(`wheels is 'auto' or a list of 2 to ${DRIVE_LIMITS.maxWheels} wheels.`);
+ throw invalidField(path, Array.isArray(wheels) ? `${wheels.length} wheels` : wheels, `"auto", or a list of 2 to ${DRIVE_LIMITS.maxWheels} wheels, such as "auto"`);
}
return wheels.map((wheel, index) => {
- knownKeys(wheel, WHEEL_FIELDS, `wheel ${index}`);
+ const wheelPath = `${path}[${index}]`;
+ knownKeys(wheel, WHEEL_FIELDS, wheelPath);
const references = wheel.nodes ?? [wheel.node];
if (!Array.isArray(references) || !references.length || references.length > DRIVE_LIMITS.maxNodeReferences) {
- throw new TypeError(`wheel ${index} needs a node, or nodes listing tire, hub and bolts.`);
+ throw invalidField(`${wheelPath}.${wheel.nodes === undefined ? 'node' : 'nodes'}`, wheel.nodes ?? wheel.node, 'a node, or nodes listing tire, hub and bolts, such as "wheel-0"', TypeError);
}
- references.forEach(reference => nodeReference(reference, `wheel ${index} node`));
+ references.forEach((reference, referenceIndex) => nodeReference(reference, wheel.nodes === undefined ? `${wheelPath}.node` : `${wheelPath}.nodes[${referenceIndex}]`));
return structuredClone(wheel);
});
}
-function normalizeLights(lights) {
- knownKeys(lights, LIGHT_FIELDS, 'drive lights');
+function normalizeLights(lights, path) {
+ knownKeys(lights, LIGHT_FIELDS, path);
const result = {};
if (lights.headlights !== undefined) {
- if (!Array.isArray(lights.headlights) || lights.headlights.length > DRIVE_LIMITS.maxLights) throw new RangeError(`headlights lists at most ${DRIVE_LIMITS.maxLights} lamps.`);
+ if (!Array.isArray(lights.headlights) || lights.headlights.length > DRIVE_LIMITS.maxLights) {
+ throw invalidField(`${path}.headlights`, Array.isArray(lights.headlights) ? `${lights.headlights.length} lamps` : lights.headlights, `a list of at most ${DRIVE_LIMITS.maxLights} lamps, such as [{ "position": [0.5, 0.6, 2] }]`);
+ }
result.headlights = lights.headlights.map((light, index) => {
- knownKeys(light, HEADLIGHT_FIELDS, `headlight ${index}`);
- const lamp = { position: vector(light.position, `headlight ${index} position`) };
+ const lampPath = `${path}.headlights[${index}]`;
+ knownKeys(light, HEADLIGHT_FIELDS, lampPath);
+ const lamp = { position: vector(light.position, `${lampPath}.position`) };
if (light.id !== undefined) lamp.id = String(light.id);
- if (light.direction !== undefined) lamp.direction = vector(light.direction, `headlight ${index} direction`);
+ if (light.direction !== undefined) lamp.direction = vector(light.direction, `${lampPath}.direction`);
return lamp;
});
}
if (lights.tailLights !== undefined) {
- if (!Array.isArray(lights.tailLights) || lights.tailLights.length > DRIVE_LIMITS.maxLights) throw new RangeError(`tailLights lists at most ${DRIVE_LIMITS.maxLights} lamps.`);
+ if (!Array.isArray(lights.tailLights) || lights.tailLights.length > DRIVE_LIMITS.maxLights) {
+ throw invalidField(`${path}.tailLights`, Array.isArray(lights.tailLights) ? `${lights.tailLights.length} lamps` : lights.tailLights, `a list of at most ${DRIVE_LIMITS.maxLights} lamps, such as [{ "material": "tail", "signal": "brake" }]`);
+ }
result.tailLights = lights.tailLights.map((light, index) => {
- knownKeys(light, TAIL_LIGHT_FIELDS, `tail light ${index}`);
- if (typeof light.material !== 'string' || !light.material) throw new TypeError(`tail light ${index} needs the material id whose emission it drives.`);
- if (light.signal !== 'brake' && light.signal !== 'reverse') throw new RangeError(`tail light ${index} signal must be brake or reverse.`);
+ const lampPath = `${path}.tailLights[${index}]`;
+ knownKeys(light, TAIL_LIGHT_FIELDS, lampPath);
+ if (typeof light.material !== 'string' || !light.material) throw invalidField(`${lampPath}.material`, light.material, 'the id of the material whose emission the lamp drives, such as "tail"', TypeError);
+ if (light.signal !== 'brake' && light.signal !== 'reverse') throw invalidField(`${lampPath}.signal`, light.signal, 'one of brake, reverse');
return structuredClone(light);
});
}
return result;
}
-/** Validate the shape of a drive entry and return its canonical JSON. Numbers are checked when the drive is built. */
-export function normalizeDrive(input) {
- knownKeys(input, DRIVE_FIELDS, 'drive');
- if ((input.path === undefined) === (input.legs === undefined)) throw new TypeError('A drive needs exactly one of path or legs.');
+/** Validate the shape of a drive entry and return its canonical JSON. Numbers are checked when the drive is built. `path` is where the entry sits in the recipe. */
+export function normalizeDrive(input, path = 'drive') {
+ knownKeys(input, DRIVE_FIELDS, path);
+ if ((input.path === undefined) === (input.legs === undefined)) {
+ throw invalidField(`${path}.${input.path === undefined ? 'path' : 'legs'}`, input.path ?? input.legs, 'exactly one of path or legs, such as a path [[0, 0, 0], [0, 0, 10]]', TypeError);
+ }
const result = {};
- if (input.path !== undefined) result.path = normalizePath(input.path, 'drive path');
+ if (input.path !== undefined) result.path = normalizePath(input.path, `${path}.path`);
if (input.legs !== undefined) {
- if (!Array.isArray(input.legs) || !input.legs.length || input.legs.length > DRIVE_LIMITS.maxLegs) throw new RangeError(`legs lists 1 to ${DRIVE_LIMITS.maxLegs} legs.`);
+ if (!Array.isArray(input.legs) || !input.legs.length || input.legs.length > DRIVE_LIMITS.maxLegs) {
+ throw invalidField(`${path}.legs`, Array.isArray(input.legs) ? `${input.legs.length} legs` : input.legs, `1 to ${DRIVE_LIMITS.maxLegs} legs, such as [{ "path": [[0, 0, 0], [0, 0, 10]] }]`);
+ }
result.legs = input.legs.map((leg, index) => {
- knownKeys(leg, ['path', 'direction', 'pause'], `leg ${index}`);
- if (leg.direction !== undefined && leg.direction !== 'forward' && leg.direction !== 'reverse') throw new RangeError(`leg ${index} direction must be forward or reverse.`);
- return { ...structuredClone(leg), path: normalizePath(leg.path, `leg ${index} path`) };
+ const legPath = `${path}.legs[${index}]`;
+ knownKeys(leg, ['path', 'direction', 'pause'], legPath);
+ if (leg.direction !== undefined && leg.direction !== 'forward' && leg.direction !== 'reverse') throw invalidField(`${legPath}.direction`, leg.direction, 'one of forward, reverse');
+ return { ...structuredClone(leg), path: normalizePath(leg.path, `${legPath}.path`) };
});
}
for (const field of NUMBER_OPTIONS) {
if (input[field] !== undefined) {
- if (!Number.isFinite(input[field])) throw new TypeError(`drive ${field} must be a finite number.`);
+ if (!Number.isFinite(input[field])) throw invalidField(`${path}.${field}`, input[field], 'a finite number, such as 5', TypeError);
result[field] = input[field];
}
}
if (input.steering !== undefined) {
- if (input.steering !== 'ackermann' && input.steering !== 'shared') throw new RangeError("drive steering must be 'ackermann' or 'shared'.");
+ if (input.steering !== 'ackermann' && input.steering !== 'shared') throw invalidField(`${path}.steering`, input.steering, 'one of ackermann, shared');
result.steering = input.steering;
}
if (input.forwardAxis !== undefined) {
- if (!['+x', '-x', '+z', '-z'].includes(input.forwardAxis)) throw new RangeError('drive forwardAxis must be +x, -x, +z or -z.');
+ if (!['+x', '-x', '+z', '-z'].includes(input.forwardAxis)) throw invalidField(`${path}.forwardAxis`, input.forwardAxis, 'one of +x, -x, +z, -z');
result.forwardAxis = input.forwardAxis;
}
- if (input.wheels !== undefined) result.wheels = normalizeWheels(input.wheels);
+ if (input.wheels !== undefined) result.wheels = normalizeWheels(input.wheels, `${path}.wheels`);
if (input.body !== undefined) {
- if (!Array.isArray(input.body) || !input.body.length || input.body.length > DRIVE_LIMITS.maxNodeReferences) throw new RangeError(`drive body lists 1 to ${DRIVE_LIMITS.maxNodeReferences} nodes.`);
- result.body = input.body.map(reference => nodeReference(reference, 'drive body node'));
+ if (!Array.isArray(input.body) || !input.body.length || input.body.length > DRIVE_LIMITS.maxNodeReferences) {
+ throw invalidField(`${path}.body`, Array.isArray(input.body) ? `${input.body.length} nodes` : input.body, `a list of 1 to ${DRIVE_LIMITS.maxNodeReferences} nodes, such as ["body"]`);
+ }
+ result.body = input.body.map((reference, index) => nodeReference(reference, `${path}.body[${index}]`));
}
- if (input.lights !== undefined) result.lights = normalizeLights(input.lights);
+ if (input.lights !== undefined) result.lights = normalizeLights(input.lights, `${path}.lights`);
return result;
}
diff --git a/src/agent-drive.js b/src/agent-drive.js
index ab4981ed..748a9d0d 100644
--- a/src/agent-drive.js
+++ b/src/agent-drive.js
@@ -1,4 +1,5 @@
import { createCameraPath } from './camera-path.js';
+import { invalidField, withFieldPrefix } from './field-error.js';
import { createVehicleRig, driveAlongLegs, createVehicleNodeOverrides } from './vehicle.js';
// The `drive` entry of an asset recipe's motion and of a placed asset: a car driven along a path by the vehicle kit.
@@ -18,15 +19,21 @@ function rounded(value) {
* Builds the rig and the drive for a decoded asset. `materialIds` are the ids a tail light may drive.
* `sample(time)` returns the pose, the node overrides that put the asset in it, and the tail-light emission per material.
*/
-export function createAssetDrive(asset, drive, { materialIds = null } = {}) {
+export function createAssetDrive(asset, drive, { materialIds = null, fieldPath = 'motion.drive' } = {}) {
+ return withFieldPrefix(fieldPath, () => buildAssetDrive(asset, drive, materialIds));
+}
+
+function buildAssetDrive(asset, drive, materialIds) {
const { path, legs, wheels, body, forwardAxis, wheelbase, lights = {}, ...driveOptions } = drive;
const rig = createVehicleRig({
asset, wheels, body, forwardAxis, wheelbase,
maxSteerAngle: driveOptions.maxSteerAngle,
lights: { headlights: lights.headlights },
});
- for (const tail of lights.tailLights ?? []) {
- if (materialIds && !materialIds.has(tail.material)) throw new RangeError(`Tail light material was not found: ${tail.material}.`);
+ for (const [index, tail] of (lights.tailLights ?? []).entries()) {
+ if (materialIds && !materialIds.has(tail.material)) {
+ throw invalidField(`lights.tailLights[${index}].material`, tail.material, `the id of a material in the asset, one of ${[...materialIds].slice(0, 5).join(', ')}`);
+ }
}
const vehicle = driveAlongLegs(rig, (legs ?? [{ path }]).map(leg => ({ ...leg, path: resolvePath(leg.path) })), driveOptions);
const tailLights = lights.tailLights ?? [];
diff --git a/src/agent-motion.js b/src/agent-motion.js
index 285e7fc2..2b727a55 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -346,7 +346,7 @@ function normalizedDrive(input, recipe) {
if (!recipe.normalizeDrive) {
throw new RangeError('motion.drive moves an imported asset recipe. For an asset placed in a scene, give the placement a drive: { asset: { id, drive } }.');
}
- const canonical = recipe.normalizeDrive(input);
+ const canonical = recipe.normalizeDrive(input, 'motion.drive');
return { canonical, built: recipe.buildDrive(canonical) };
}
diff --git a/src/agent-physics.js b/src/agent-physics.js
index 72df7c79..bb0ca952 100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@ -1,4 +1,5 @@
import { mat4, vec3 } from 'gl-matrix';
+import { invalidField } from './field-error.js';
import { restWorldMatrix, boneTails, boneNodeId } from './rig.js';
import { createRagdoll, ragdollPatches, ragdollReport } from './ragdoll.js';
import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from './physics.js';
@@ -24,134 +25,139 @@ const JOINT_FIELDS = ['type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'l
const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'ragdoll'];
const RAGDOLL_FIELDS = ['armature', 'density', 'friction', 'restitution', 'layer'];
-function knownKeys(value, fields, label) {
+function knownKeys(value, fields, path) {
if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
- throw new TypeError(`${label} must be a plain object.`);
+ throw invalidField(path, value, 'a plain object, such as {}', TypeError);
}
for (const key of Object.keys(value)) {
if (!fields.includes(key)) {
- throw new TypeError(`Unknown or unsupported ${label} field: ${key}. Allowed fields: ${fields.join(", ")}.`);
+ throw invalidField(`${path}.${key}`, value[key], `no such field; use one of ${fields.join(', ')}`, TypeError);
}
}
}
-function finiteNumber(value, label, minimum = -Infinity, maximum = Infinity) {
+function finiteNumber(value, path, minimum = -Infinity, maximum = Infinity) {
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < minimum || value > maximum) {
- throw new RangeError(`${label} must be a finite number within ${minimum} and ${maximum}.`);
+ const bounded = Number.isFinite(minimum) && Number.isFinite(maximum);
+ const range = bounded ? `from ${minimum} to ${maximum}` : 'that fits Float32';
+ const example = bounded ? Math.min(Math.max(1, minimum), maximum) : 1;
+ throw invalidField(path, value, `a number ${range}, such as ${example}`);
}
return value;
}
-function numberList(value, size, label) {
+function numberList(value, size, path) {
if (!Array.isArray(value) || value.length !== size) {
- throw new TypeError(`${label} needs ${size} numbers.`);
+ throw invalidField(path, value, `an array of ${size} numbers, such as [${Array(size).fill(0).join(', ')}]`, TypeError);
}
- return value.map(component => finiteNumber(component, label));
+ return value.map((component, index) => finiteNumber(component, `${path}[${index}]`));
}
-function nodeIdentifier(value, label) {
+function nodeIdentifier(value, path) {
if (typeof value !== 'string' || !value.trim() || value.length > 128) {
- throw new TypeError(`${label} needs a node ID of 1 to 128 characters.`);
+ throw invalidField(path, value, 'a node ID of 1 to 128 characters, such as "crate"', TypeError);
}
return value;
}
-function boundedArray(value, maximum, label) {
+function boundedArray(value, maximum, path) {
if (!Array.isArray(value) || value.length > maximum) {
- throw new TypeError(`${label} must be an array of at most ${maximum} entries.`);
+ throw invalidField(path, Array.isArray(value) ? `${value.length} entries` : value, `an array of at most ${maximum} entries, such as []`, TypeError);
}
return value;
}
-function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes) {
- knownKeys(input, BODY_FIELDS, 'physics body');
- const nodeId = nodeIdentifier(input.node, 'Physics body node');
+function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes, path) {
+ knownKeys(input, BODY_FIELDS, path);
+ const nodeId = nodeIdentifier(input.node, `${path}.node`);
const node = recipeNodes.get(nodeId);
if (!node) {
- throw new RangeError(`Physics body node was not found: ${nodeId}.`);
+ throw invalidField(`${path}.node`, nodeId, `the ID of a recipe node, one of ${[...recipeNodes.keys()].slice(0, 5).join(', ') || 'none yet'}`);
}
if (node.geometry === undefined) {
- throw new RangeError(`Physics body node ${nodeId} has no geometry to fit a collider to.`);
+ throw invalidField(`${path}.node`, nodeId, 'a node with a geometry to fit a collider to; set geometry on it or pick another node');
}
if (node.parent !== null) {
- throw new RangeError(`Physics body node ${nodeId} must be a root node; reparent it or move its parent into the body.`);
+ throw invalidField(`${path}.node`, nodeId, 'a root node, with no parent; reparent it or move its parent into the body');
}
if (claimedNodes.has(nodeId)) {
- throw new RangeError(`Node ${nodeId} has more than one physics body.`);
+ throw invalidField(`${path}.node`, nodeId, 'a node with one physics body only; this one already has another');
}
if (motionNodeIds.has(nodeId)) {
- throw new RangeError(`Node ${nodeId} has a motion translation or rotation track and a physics body. Pick one.`);
+ throw invalidField(`${path}.node`, nodeId, 'a node without a motion translation or rotation track; pick the track or the body, not both');
}
claimedNodes.add(nodeId);
const type = input.type ?? 'dynamic';
if (!BODY_TYPES.includes(type)) {
- throw new RangeError(`Physics body type must be one of ${BODY_TYPES.join(', ')}.`);
+ throw invalidField(`${path}.type`, type, `one of ${BODY_TYPES.join(', ')}`);
}
if (input.sensor !== undefined && typeof input.sensor !== 'boolean') {
- throw new TypeError('Physics body sensor must be boolean.');
+ throw invalidField(`${path}.sensor`, input.sensor, 'true or false', TypeError);
}
const sensor = input.sensor ?? false;
const shape = input.shape ?? (sensor ? 'box' : type === 'dynamic' ? 'box' : 'trimesh');
if (!SHAPES.includes(shape)) {
- throw new RangeError(`Physics shape must be one of ${SHAPES.join(', ')}.`);
+ throw invalidField(`${path}.shape`, shape, `one of ${SHAPES.join(', ')}`);
}
if (shape === 'trimesh' && type === 'dynamic') {
- throw new RangeError(`Body ${nodeId} is dynamic: use shape convex, box, ball or capsule. Trimesh is for fixed or kinematic bodies.`);
+ throw invalidField(`${path}.shape`, shape, 'one of convex, box, ball or capsule for a dynamic body; trimesh is for fixed or kinematic bodies');
}
if (type !== 'dynamic' && (input.velocity !== undefined || input.angularVelocity !== undefined)) {
- throw new TypeError(`Body ${nodeId} is ${type}: only dynamic bodies take velocity.`);
+ const field = input.velocity !== undefined ? 'velocity' : 'angularVelocity';
+ throw invalidField(`${path}.${field}`, input[field], `no velocity since the body is ${type}; only dynamic bodies take one, such as type "dynamic"`, TypeError);
}
if (input.mass !== undefined && input.density !== undefined) {
- throw new TypeError('A physics body takes mass or density, not both.');
+ throw invalidField(`${path}.density`, input.density, 'mass or density, not both; drop one, such as density 1', TypeError);
}
const body = { node: nodeId, type, shape };
if (sensor) body.sensor = true;
- if (input.mass !== undefined) body.mass = finiteNumber(input.mass, 'Physics mass', 1e-6, 1e9);
- if (input.density !== undefined) body.density = finiteNumber(input.density, 'Physics density', 1e-6, 1e9);
- if (input.friction !== undefined) body.friction = finiteNumber(input.friction, 'Physics friction', 0, 100);
- if (input.restitution !== undefined) body.restitution = finiteNumber(input.restitution, 'Physics restitution', 0, 1);
- if (input.velocity !== undefined) body.velocity = numberList(input.velocity, 3, 'Physics velocity');
- if (input.angularVelocity !== undefined) body.angularVelocity = numberList(input.angularVelocity, 3, 'Physics angularVelocity');
- if (input.layer !== undefined) body.layer = Math.trunc(finiteNumber(input.layer, 'Physics layer', 0, MAX_LAYER));
+ if (input.mass !== undefined) body.mass = finiteNumber(input.mass, `${path}.mass`, 1e-6, 1e9);
+ if (input.density !== undefined) body.density = finiteNumber(input.density, `${path}.density`, 1e-6, 1e9);
+ if (input.friction !== undefined) body.friction = finiteNumber(input.friction, `${path}.friction`, 0, 100);
+ if (input.restitution !== undefined) body.restitution = finiteNumber(input.restitution, `${path}.restitution`, 0, 1);
+ if (input.velocity !== undefined) body.velocity = numberList(input.velocity, 3, `${path}.velocity`);
+ if (input.angularVelocity !== undefined) body.angularVelocity = numberList(input.angularVelocity, 3, `${path}.angularVelocity`);
+ if (input.layer !== undefined) body.layer = Math.trunc(finiteNumber(input.layer, `${path}.layer`, 0, MAX_LAYER));
if (input.collidesWith !== undefined) {
- const layers = boundedArray(input.collidesWith, MAX_LAYER + 1, 'Physics collidesWith');
- body.collidesWith = [...new Set(layers.map(layer => Math.trunc(finiteNumber(layer, 'Physics collidesWith layer', 0, MAX_LAYER))))].sort((first, second) => first - second);
+ const layers = boundedArray(input.collidesWith, MAX_LAYER + 1, `${path}.collidesWith`);
+ body.collidesWith = [...new Set(layers.map((layer, index) => Math.trunc(finiteNumber(layer, `${path}.collidesWith[${index}]`, 0, MAX_LAYER))))].sort((first, second) => first - second);
}
return body;
}
-function normalizeJoint(input, bodyNodeIds) {
- knownKeys(input, JOINT_FIELDS, 'physics joint');
+function normalizeJoint(input, bodyNodeIds, path) {
+ knownKeys(input, JOINT_FIELDS, path);
if (!JOINT_TYPES.includes(input.type)) {
- throw new RangeError(`Physics joint type must be one of ${JOINT_TYPES.join(', ')}.`);
+ throw invalidField(`${path}.type`, input.type, `one of ${JOINT_TYPES.join(', ')}`);
}
for (const field of ['bodyA', 'bodyB']) {
if (!bodyNodeIds.has(input[field])) {
- throw new RangeError(`Physics joint ${field} must be the node of a physics body: ${input[field]}.`);
+ throw invalidField(`${path}.${field}`, input[field], `the node of a physics body, one of ${[...bodyNodeIds].slice(0, 5).join(', ') || 'none yet'}`);
}
}
const joint = { type: input.type, bodyA: input.bodyA, bodyB: input.bodyB };
for (const field of ['anchorA', 'anchorB', 'axis']) {
- if (input[field] !== undefined) joint[field] = numberList(input[field], 3, `Physics joint ${field}`);
+ if (input[field] !== undefined) joint[field] = numberList(input[field], 3, `${path}.${field}`);
}
- if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, 'Physics joint limits');
+ if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, `${path}.limits`);
return joint;
}
function normalizeRagdoll(input, recipe, motionNodeIds) {
- knownKeys(input, RAGDOLL_FIELDS, 'physics ragdoll');
+ knownKeys(input, RAGDOLL_FIELDS, 'physics.ragdoll');
const armature = (recipe.armatures ?? []).find(candidate => candidate.id === input.armature);
if (!armature) {
- throw new RangeError(`Physics ragdoll armature was not found: ${JSON.stringify(String(input.armature).slice(0, 48))}. Add it to the recipe armatures.`);
+ const known = (recipe.armatures ?? []).slice(0, 5).map(candidate => candidate.id).join(', ') || 'none yet; add one to the recipe armatures';
+ throw invalidField('physics.ragdoll.armature', input.armature, `the ID of a recipe armature, one of ${known}`);
}
const ragdoll = { armature: armature.id };
- if (input.density !== undefined) ragdoll.density = finiteNumber(input.density, 'Ragdoll density', 1e-6, 1e9);
- if (input.friction !== undefined) ragdoll.friction = finiteNumber(input.friction, 'Ragdoll friction', 0, 100);
- if (input.restitution !== undefined) ragdoll.restitution = finiteNumber(input.restitution, 'Ragdoll restitution', 0, 1);
- if (input.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.layer, 'Ragdoll layer', 0, MAX_LAYER));
+ if (input.density !== undefined) ragdoll.density = finiteNumber(input.density, 'physics.ragdoll.density', 1e-6, 1e9);
+ if (input.friction !== undefined) ragdoll.friction = finiteNumber(input.friction, 'physics.ragdoll.friction', 0, 100);
+ if (input.restitution !== undefined) ragdoll.restitution = finiteNumber(input.restitution, 'physics.ragdoll.restitution', 0, 1);
+ if (input.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.layer, 'physics.ragdoll.layer', 0, MAX_LAYER));
for (const bone of armature.bones) {
if (motionNodeIds.has(boneNodeId(armature, bone.name))) {
- throw new RangeError(`Bone ${bone.name} has a motion translation or rotation track and a ragdoll. Pick one.`);
+ throw invalidField('physics.ragdoll.armature', armature.id, `an armature whose bones have no motion translation or rotation track, but ${bone.name} has one; pick the track or the ragdoll`);
}
}
ragdollForRecipe(ragdoll, recipe);
@@ -182,21 +188,21 @@ export function normalizeAgentPhysics(input, recipe) {
return null;
}
knownKeys(input, PHYSICS_FIELDS, 'physics');
- const duration = finiteNumber(input.duration, 'Physics duration', 0.1, MAX_DURATION_SECONDS);
+ const duration = finiteNumber(input.duration, 'physics.duration', 0.1, MAX_DURATION_SECONDS);
const recipeNodes = new Map(recipe.nodes.map(node => [node.id, node]));
const motionNodeIds = new Set((recipe.motion?.tracks ?? [])
.filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))
.map(track => track.id));
const claimedNodes = new Set();
- const bodies = boundedArray(input.bodies ?? [], MAX_BODIES, 'Physics bodies').map(body => normalizeBody(body, recipeNodes, motionNodeIds, claimedNodes));
+ const bodies = boundedArray(input.bodies ?? [], MAX_BODIES, 'physics.bodies').map((body, index) => normalizeBody(body, recipeNodes, motionNodeIds, claimedNodes, `physics.bodies[${index}]`));
if (!bodies.length && input.ragdoll === undefined) {
- throw new RangeError('Physics needs at least one body. Use null to clear it.');
+ throw invalidField('physics.bodies', [], 'at least one body, such as [{ "node": "crate" }]; use physics null to clear it');
}
const result = { duration, bodies };
if (input.ragdoll !== undefined) result.ragdoll = normalizeRagdoll(input.ragdoll, recipe, motionNodeIds);
- if (input.gravity !== undefined) result.gravity = numberList(input.gravity, 3, 'Physics gravity');
+ if (input.gravity !== undefined) result.gravity = numberList(input.gravity, 3, 'physics.gravity');
if (input.joints !== undefined) {
- result.joints = boundedArray(input.joints, MAX_JOINTS, 'Physics joints').map(joint => normalizeJoint(joint, claimedNodes));
+ result.joints = boundedArray(input.joints, MAX_JOINTS, 'physics.joints').map((joint, index) => normalizeJoint(joint, claimedNodes, `physics.joints[${index}]`));
}
return result;
}
@@ -218,14 +224,14 @@ function scaledBounds(positions, scale) {
function convexPoints(positions, scale, nodeId) {
if (positions.length / 3 > MAX_SOURCE_VERTICES) {
- throw new RangeError(`Geometry of ${nodeId} has ${positions.length / 3} vertices; a convex collider reads at most ${MAX_SOURCE_VERTICES}. Use shape box or a coarser geometry.`);
+ throw invalidField(`nodes[${nodeId}].geometry`, `${positions.length / 3} vertices`, `at most ${MAX_SOURCE_VERTICES} vertices for a convex collider; use shape box or a coarser geometry, such as shape "box"`);
}
const distinct = new Map();
for (let index = 0; index < positions.length; index += 3) {
const point = [positions[index] * scale[0], positions[index + 1] * scale[1], positions[index + 2] * scale[2]];
distinct.set(point.map(component => component.toFixed(5)).join(','), point);
if (distinct.size > MAX_HULL_POINTS) {
- throw new RangeError(`Geometry of ${nodeId} has more than ${MAX_HULL_POINTS} distinct vertices for a convex collider. Use shape box or a coarser geometry.`);
+ throw invalidField(`nodes[${nodeId}].geometry`, `more than ${MAX_HULL_POINTS} distinct vertices`, `at most ${MAX_HULL_POINTS} distinct vertices for a convex collider; use shape box or a coarser geometry, such as shape "box"`);
}
}
return [...distinct.values()].flat();
@@ -234,7 +240,7 @@ function convexPoints(positions, scale, nodeId) {
function trimeshArrays(geometry, scale, nodeId) {
const triangleCount = geometry.indices.length / 3;
if (triangleCount > MAX_TRIMESH_TRIANGLES) {
- throw new RangeError(`Geometry of ${nodeId} has ${triangleCount} triangles; a trimesh collider holds at most ${MAX_TRIMESH_TRIANGLES}. Use a coarser geometry or shape box.`);
+ throw invalidField(`nodes[${nodeId}].geometry`, `${triangleCount} triangles`, `at most ${MAX_TRIMESH_TRIANGLES} triangles for a trimesh collider; use a coarser geometry or shape box, such as shape "box"`);
}
const vertices = [];
for (let index = 0; index < geometry.positions.length; index += 3) {
@@ -401,19 +407,19 @@ const FLOOR_HALF_THICKNESS = 0.5;
/** Validate the physics of an imported asset: a ragdoll of its joints falling onto a floor at a world height. */
export function normalizeAssetPhysics(input) {
- knownKeys(input, ASSET_PHYSICS_FIELDS, 'asset physics');
- const physics = { duration: finiteNumber(input.duration, 'Physics duration', 0.1, MAX_DURATION_SECONDS) };
- if (input.gravity !== undefined) physics.gravity = numberList(input.gravity, 3, 'Physics gravity');
- if (input.floor !== undefined) physics.floor = finiteNumber(input.floor, 'Physics floor', -1e6, 1e6);
+ knownKeys(input, ASSET_PHYSICS_FIELDS, 'physics');
+ const physics = { duration: finiteNumber(input.duration, 'physics.duration', 0.1, MAX_DURATION_SECONDS) };
+ if (input.gravity !== undefined) physics.gravity = numberList(input.gravity, 3, 'physics.gravity');
+ if (input.floor !== undefined) physics.floor = finiteNumber(input.floor, 'physics.floor', -1e6, 1e6);
if (input.ragdoll === undefined) {
- throw new TypeError('Asset physics needs a ragdoll section: it is what moves the asset joints.');
+ throw invalidField('physics.ragdoll', input.ragdoll, 'a ragdoll section, such as {}; it is what moves the asset joints', TypeError);
}
- knownKeys(input.ragdoll, RAGDOLL_FIELDS.filter(field => field !== 'armature'), 'physics ragdoll');
+ knownKeys(input.ragdoll, RAGDOLL_FIELDS.filter(field => field !== 'armature'), 'physics.ragdoll');
const ragdoll = {};
for (const [field, minimum, maximum] of [['density', 1e-6, 1e9], ['friction', 0, 100], ['restitution', 0, 1]]) {
- if (input.ragdoll[field] !== undefined) ragdoll[field] = finiteNumber(input.ragdoll[field], `Ragdoll ${field}`, minimum, maximum);
+ if (input.ragdoll[field] !== undefined) ragdoll[field] = finiteNumber(input.ragdoll[field], `physics.ragdoll.${field}`, minimum, maximum);
}
- if (input.ragdoll.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.ragdoll.layer, 'Ragdoll layer', 0, MAX_LAYER));
+ if (input.ragdoll.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.ragdoll.layer, 'physics.ragdoll.layer', 0, MAX_LAYER));
return { ...physics, ragdoll };
}
@@ -438,7 +444,7 @@ function assetRagdollBones(nodes, nodePoses, rootMatrix) {
const joints = nodes.filter(node => node.joint);
const lockedJoint = joints.find(node => !node.editable);
if (lockedJoint) {
- throw new RangeError(`Joint ${lockedJoint.id} cannot be edited (mirrored or sheared), so a ragdoll cannot drive it.`);
+ throw invalidField('physics.ragdoll', lockedJoint.id, 'an asset whose joints can all be edited, but this one is mirrored or sheared so a ragdoll cannot drive it; remove the ragdoll or use another asset');
}
const depthOf = node => (node.parent === null ? 0 : 1 + depthOf(nodesById.get(node.parent)));
const ordered = joints.map(node => ({ node, depth: depthOf(node) })).sort((first, second) => first.depth - second.depth).map(entry => entry.node);
diff --git a/src/agent-scene-assets.js b/src/agent-scene-assets.js
index d27b48c0..87c5fa65 100644
--- a/src/agent-scene-assets.js
+++ b/src/agent-scene-assets.js
@@ -1,3 +1,4 @@
+import { invalidField } from './field-error.js';
import { mat4 } from 'gl-matrix';
import { normalizeDrive } from './agent-drive-schema.js';
@@ -35,46 +36,47 @@ const OVERRIDE_TAGS = ['surface', 'foliage', 'grass'];
function knownKeys(value, allowed, label) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throw new TypeError(`${label} must be an object.`);
+ throw invalidField(label, value, 'an object, such as {}', TypeError);
}
for (const key of Object.keys(value)) {
if (!allowed.includes(key)) {
- throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${allowed.join(', ')}.`);
+ throw invalidField(`${label}.${key}`, value[key], `no such field; use one of ${allowed.join(', ')}`, TypeError);
}
}
}
function colorVector(value, label) {
if (!Array.isArray(value) || value.length !== 3 || value.some(component => !Number.isFinite(component) || component < 0)) {
- throw new RangeError(`${label} must be three finite non-negative linear RGB numbers.`);
+ throw invalidField(label, value, 'an array of 3 linear RGB numbers of 0 or more, such as [0.5, 0.2, 0.1]');
}
return [...value];
}
-function normalizeMaterialOverride(override) {
- knownKeys(override, OVERRIDE_FIELDS, 'asset material override');
+function normalizeMaterialOverride(override, index) {
+ const path = `asset.materials[${index}]`;
+ knownKeys(override, OVERRIDE_FIELDS, path);
if (typeof override.name !== 'string' || !override.name || override.name.length > 256) {
- throw new TypeError('An asset material override needs the source material name. scene_inspect lists the names under assets.');
+ throw invalidField(`${path}.name`, override.name, 'the name of a source material, such as "paint"; scene_inspect lists the names under assets', TypeError);
}
const result = { name: override.name };
if (override.tag !== undefined) {
- if (!OVERRIDE_TAGS.includes(override.tag)) throw new RangeError(`asset material override tag must be one of ${OVERRIDE_TAGS.join(', ')}.`);
+ if (!OVERRIDE_TAGS.includes(override.tag)) throw invalidField(`${path}.tag`, override.tag, `one of ${OVERRIDE_TAGS.join(', ')}`);
result.tag = override.tag;
}
for (const field of COLOR_FIELDS) {
- if (override[field] !== undefined) result[field] = colorVector(override[field], field);
+ if (override[field] !== undefined) result[field] = colorVector(override[field], `${path}.${field}`);
}
for (const field of UNIT_FIELDS) {
if (override[field] !== undefined) {
if (!Number.isFinite(override[field]) || override[field] < 0 || override[field] > 1) {
- throw new RangeError(`${field} must be a number from 0 to 1.`);
+ throw invalidField(`${path}.${field}`, override[field], 'a number from 0 to 1, such as 0.5');
}
result[field] = override[field];
}
}
if (override.emission !== undefined) {
if (!Number.isFinite(override.emission) || override.emission < 0) {
- throw new RangeError('emission must be a finite non-negative number.');
+ throw invalidField(`${path}.emission`, override.emission, 'a number of 0 or more, such as 1');
}
result.emission = override.emission;
}
@@ -83,39 +85,39 @@ function normalizeMaterialOverride(override) {
/** Validate the `asset` field of a node. Returns the canonical form kept in the recipe. */
export function normalizeAssetPlacement(value) {
- knownKeys(value, PLACEMENT_FIELDS, 'asset placement');
+ knownKeys(value, PLACEMENT_FIELDS, 'asset');
if (typeof value.id !== 'string' || !ASSET_ID.test(value.id.toLowerCase())) {
- throw new TypeError('asset id must be the 64 hexadecimal characters of a catalog asset id; asset_catalog lists them.');
+ throw invalidField('asset.id', value.id, '64 hexadecimal characters, such as "ab12..." (a catalog asset id that asset_catalog lists)', TypeError);
}
const result = { id: value.id.toLowerCase() };
if (value.materials !== undefined) {
if (!Array.isArray(value.materials) || value.materials.length > ASSET_PLACEMENT_LIMITS.maxOverrides) {
- throw new RangeError(`asset materials must list at most ${ASSET_PLACEMENT_LIMITS.maxOverrides} overrides.`);
+ throw invalidField('asset.materials', Array.isArray(value.materials) ? `${value.materials.length} overrides` : value.materials, `a list of at most ${ASSET_PLACEMENT_LIMITS.maxOverrides} overrides, such as [{ "name": "paint", "color": [1, 0, 0] }]`);
}
- const overrides = value.materials.map(normalizeMaterialOverride);
+ const overrides = value.materials.map((override, index) => normalizeMaterialOverride(override, index));
if (new Set(overrides.map(override => override.name)).size !== overrides.length) {
- throw new RangeError('asset material overrides must name distinct source materials.');
+ throw invalidField('asset.materials', `${overrides.length} overrides`, 'overrides that each name a different source material, such as one override per name');
}
result.materials = overrides;
}
if (value.clip !== undefined) {
- knownKeys(value.clip, CLIP_FIELDS, 'asset clip');
+ knownKeys(value.clip, CLIP_FIELDS, 'asset.clip');
const { index, start = 0, speed = 1, loop = true } = value.clip;
- if (!Number.isInteger(index) || index < 0) throw new RangeError('asset clip index must be a non-negative integer.');
- if (!Number.isFinite(start) || start < 0 || start > 3600) throw new RangeError('asset clip start must be seconds from 0 to 3600.');
- if (!Number.isFinite(speed) || speed <= 0 || speed > 16) throw new RangeError('asset clip speed must be above 0 and at most 16.');
- if (typeof loop !== 'boolean') throw new TypeError('asset clip loop must be boolean.');
+ if (!Number.isInteger(index) || index < 0) throw invalidField('asset.clip.index', index, 'a whole number of 0 or more, such as 0');
+ if (!Number.isFinite(start) || start < 0 || start > 3600) throw invalidField('asset.clip.start', start, 'seconds from 0 to 3600, such as 0');
+ if (!Number.isFinite(speed) || speed <= 0 || speed > 16) throw invalidField('asset.clip.speed', speed, 'a number above 0 and at most 16, such as 1');
+ if (typeof loop !== 'boolean') throw invalidField('asset.clip.loop', loop, 'true or false', TypeError);
result.clip = { index, start, speed, loop };
}
if (value.crowd !== undefined) {
- if (value.clip !== undefined || value.drive !== undefined) throw new TypeError('An asset placement plays a clip, drives along a path or fills a crowd, only one of them.');
+ if (value.clip !== undefined || value.drive !== undefined) throw invalidField('asset.crowd', value.crowd, 'only one of clip, drive or crowd; drop the others, such as keeping just the crowd', TypeError);
result.crowd = crowdCode().normalizeCrowd(value.crowd);
}
if (value.drive !== undefined) {
- if (value.clip !== undefined) throw new TypeError('An asset placement plays a clip or drives along a path, not both.');
- result.drive = normalizeDrive(value.drive);
+ if (value.clip !== undefined) throw invalidField('asset.drive', value.drive, 'a drive or a clip, not both; drop one, such as keeping just the drive', TypeError);
+ result.drive = normalizeDrive(value.drive, 'asset.drive');
if (result.drive.lights?.tailLights) {
- throw new RangeError('Placed assets share their materials, so tail lights glow only in an asset recipe (motion.drive). Headlight and brake signals are still reported by scene_inspect.');
+ throw invalidField('asset.drive.lights.tailLights', value.drive.lights.tailLights, 'no tail lights on a placed asset, since placed assets share their materials; tail lights glow only in an asset recipe (motion.drive), such as motion.drive.lights.tailLights');
}
}
return result;
@@ -222,7 +224,7 @@ export function expandAssetPlacements(recipe, assets, limits, outputCache = new
throw new Error(`Asset ${assetId.slice(0, 12)} copy ${copy} is not loaded. The host loads it before createAgentScene or apply.`);
}
if (clip && !asset.animations[clip.index]) {
- throw new RangeError(`Node ${node.id}: asset ${assetId.slice(0, 12)} has ${asset.animations.length} clips, so clip index ${clip.index} does not exist. scene_inspect lists them under assets.`);
+ throw invalidField(`nodes[${recipe.nodes.indexOf(node)}].asset.clip.index`, clip.index, `a clip index from 0 to ${asset.animations.length - 1}, since asset ${assetId.slice(0, 12)} has ${asset.animations.length} clips; scene_inspect lists them under assets`);
}
if (crowd) {
const expanded = crowdCode().expandCrowd(recipe, node, asset, copy, outputCache, runtime, limits);
@@ -234,7 +236,7 @@ export function expandAssetPlacements(recipe, assets, limits, outputCache = new
const materialNames = new Set(asset.parts.map(part => part.material.name).filter(Boolean));
for (const override of overrides) {
if (!materialNames.has(override.name)) {
- throw new RangeError(`Node ${node.id}: asset has no material named ${JSON.stringify(override.name)}. Names: ${[...materialNames].slice(0, 16).map(name => JSON.stringify(name)).join(', ') || 'none, the asset materials are unnamed'}.`);
+ throw invalidField(`nodes[${recipe.nodes.indexOf(node)}].asset.materials[${overrides.indexOf(override)}].name`, override.name, `one of ${[...materialNames].slice(0, 16).map(name => JSON.stringify(name)).join(', ') || 'none, since the asset materials are unnamed'}`);
}
}
const overrideByName = new Map(overrides.map(override => [override.name, override]));
@@ -271,7 +273,7 @@ export function expandAssetPlacements(recipe, assets, limits, outputCache = new
...(part.castShadow !== undefined ? { castShadow: part.castShadow } : {}),
});
});
- const record = { node: node.id, assetId, copy, asset, partNodeIds, clip: clip ?? null, drive: drive ? createDrive(node.id, createAssetDrive, asset, drive) : null, drivePose: null };
+ const record = { node: node.id, assetId, copy, asset, partNodeIds, clip: clip ?? null, drive: drive ? createDrive(node.id, `nodes[${recipe.nodes.indexOf(node)}].asset.drive`, createAssetDrive, asset, drive) : null, drivePose: null };
runtime.placements.push(record);
if (clip || drive) runtime.animators.push(record);
}
@@ -282,12 +284,12 @@ export function expandAssetPlacements(recipe, assets, limits, outputCache = new
return runtime;
}
-function createDrive(nodeId, createAssetDrive, asset, drive) {
+function createDrive(nodeId, fieldPath, createAssetDrive, asset, drive) {
if (!createAssetDrive) throw new Error('This recipe drives a placed asset, which needs the drive code: await loadAgentSceneModules(recipe) before createAgentScene or apply.');
try {
- return createAssetDrive(asset, drive);
+ return createAssetDrive(asset, drive, { fieldPath });
} catch (error) {
- error.message = `Node ${nodeId} drive: ${error.message}`;
+ if (typeof error?.fieldPath !== 'string') error.message = `Node ${nodeId} drive: ${error.message}`;
throw error;
}
}
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index 6117ca33..6d49c3e8 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -42,6 +42,17 @@ 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) {
+ if (typeof error?.fieldPath === 'string' && error.message.startsWith(error.fieldPath)) {
+ error.message = `edits[${index}].${error.message}`;
+ error.fieldPath = `edits[${index}].${error.fieldPath}`;
+ return error;
+ }
+ return new error.constructor(`Mesh edit ${index} (${label}): ${error.message}`);
+}
+
function editError(index, message) {
return new TypeError(`Mesh edit ${index} (${message})`);
}
@@ -320,7 +331,7 @@ function checkArrayBudget(mesh, edit, limits, index) {
try {
checkSculptBudget(mesh, edit.strokes.length);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (sculpt): ${error.message}`);
+ throw editFailure(error, index, `sculpt`);
}
return;
}
@@ -332,7 +343,7 @@ function checkArrayBudget(mesh, edit, limits, index) {
try {
remeshGridSize(mesh, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (remesh): ${error.message}`);
+ throw editFailure(error, index, `remesh`);
}
return;
}
@@ -395,7 +406,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = runModifierEdit(current, edit, limits);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ throw editFailure(error, index, `${edit.op}`);
}
Object.assign(result, outcome.result);
return { mesh: outcome.mesh, result };
@@ -406,14 +417,14 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
cutter = transformMesh(resolveCutter(edit.cutter), edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (boolean cutter): ${error.message}`);
+ throw editFailure(error, index, `boolean cutter`);
}
const cutTag = `${edit.name}.cut`;
let outcome;
try {
outcome = meshBoolean(current, cutter, edit.operation, { cutTag });
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (boolean ${edit.operation}): ${error.message}`);
+ throw editFailure(error, index, `boolean ${edit.operation}`);
}
result.operation = edit.operation;
result.tags = { [cutTag]: outcome.cutterFaces };
@@ -430,7 +441,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = loopCut(current, edit.edges, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (loop_cut): ${error.message}`);
+ throw editFailure(error, index, `loop_cut`);
}
result.rings = outcome.rings;
result.closedRings = outcome.closedRings;
@@ -443,7 +454,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = bevelEdges(current, edit.edges, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (bevel): ${error.message}`);
+ throw editFailure(error, index, `bevel`);
}
result.edges = outcome.bevelEdges;
result.width = outcome.width;
@@ -456,7 +467,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = runCutEdit(current, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ throw editFailure(error, index, `${edit.op}`);
}
Object.assign(result, outcome.result);
const tags = tagSummary(outcome.mesh, edit.name);
@@ -468,7 +479,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = edit.op === 'set_position' ? setPosition(current, edit, loadSurface) : displaceMesh(current, edit, loadSurface);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ throw editFailure(error, index, `${edit.op}`);
}
result.movedVertices = outcome.movedVertices;
return { mesh: outcome.mesh, result };
@@ -478,7 +489,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = edit.op === 'vertex_group' ? setVertexGroup(current, edit, loadSurface) : setVertexColor(current, edit, loadSurface);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ throw editFailure(error, index, `${edit.op}`);
}
if (edit.op === 'vertex_group') {
result.group = edit.name;
@@ -493,7 +504,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = edit.op === 'sculpt' ? sculptMesh(current, edit) : runShrinkwrap(current, edit, resolveCutter);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ throw editFailure(error, index, `${edit.op}`);
}
result.movedVertices = outcome.movedVertices;
if (outcome.missedVertices) result.missedVertices = outcome.missedVertices;
@@ -504,7 +515,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
subdivided = subdivideMesh(current, { levels: edit.levels, crease: edit.crease, sharpness: edit.sharpness });
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (subdivide): ${error.message}`);
+ throw editFailure(error, index, `subdivide`);
}
result.levels = edit.levels;
return { mesh: subdivided, result };
@@ -514,7 +525,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = decimateMesh(current, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (decimate): ${error.message}`);
+ throw editFailure(error, index, `decimate`);
}
result.triangles = outcome.triangles;
if (!outcome.reachedTarget) result.stoppedEarly = true;
@@ -525,7 +536,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
outcome = remeshMesh(current, edit);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (remesh): ${error.message}`);
+ throw editFailure(error, index, `remesh`);
}
result.voxelSize = Number(outcome.voxelSize.toPrecision(5));
return { mesh: outcome.mesh, result };
@@ -539,7 +550,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
if (error instanceof KernelDeferred) {
throw error;
}
- throw new error.constructor(`Mesh edit ${index} (uv_unwrap): ${error.message}`);
+ throw editFailure(error, index, `uv_unwrap`);
}
result.islands = outcome.islands;
result.seamEdges = outcome.seamEdges;
@@ -559,7 +570,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
try {
mask = selectFaces(current, edit.select);
} catch (error) {
- throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ 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.`);
diff --git a/src/mesh-shrinkwrap.js b/src/mesh-shrinkwrap.js
index 4cc43be4..d18796a2 100644
--- a/src/mesh-shrinkwrap.js
+++ b/src/mesh-shrinkwrap.js
@@ -1,3 +1,4 @@
+import { invalidField } from './field-error.js';
import { createMeshQueryIndex } from './mesh-query.js';
import { triangulatedSurface } from './mesh-surface-distance.js';
import { selectedVertices, withPositions } from './mesh-field-edits.js';
@@ -37,13 +38,13 @@ export function shrinkwrapMesh(mesh, target, edit) {
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
if (!flags[vertex]) continue;
const remainingTests = MAX_SHRINKWRAP_TRIANGLE_TESTS - triangleTests;
- if (remainingTests <= 0) throw new RangeError('Shrinkwrap searched too many triangles. Select fewer faces or use a simpler target.');
+ if (remainingTests <= 0) throw invalidField('select', 'a selection that needs too many triangle tests', 'fewer faces or a simpler target, such as a smaller select');
const origin = Array.from(mesh.positions.subarray(vertex * 3, vertex * 3 + 3));
const found = findSurface(index, origin, edit, remainingTests);
triangleTests += found.triangleTests;
if (!found.hit) {
missedVertices++;
- if (onMiss === 'error') throw new RangeError(`Shrinkwrap found no surface for vertex ${vertex}. Raise maxDistance, change the direction, or set onMiss to keep.`);
+ if (onMiss === 'error') throw invalidField('onMiss', onMiss, `"keep", such as onMiss "keep", to leave vertices that find no surface in place (vertex ${vertex} found none); or raise maxDistance, or change the direction`);
continue;
}
const side = standOffSide(found.hit.normal, edit);
diff --git a/src/vehicle.js b/src/vehicle.js
index 92d75ad8..5aacef14 100644
--- a/src/vehicle.js
+++ b/src/vehicle.js
@@ -1,4 +1,5 @@
import { mat4, vec3 } from 'gl-matrix';
+import { invalidField } from './field-error.js';
// Local vehicle frame: x is left, y is up, z is forward, origin on the ground under the wheel centroid.
const FORWARD_AXES = Object.freeze({
@@ -37,8 +38,8 @@ function createMatrix() {
return mat4.identity(new Float64Array(16));
}
-function assertFinitePositive(value, message) {
- if (!Number.isFinite(value) || value <= 0) throw new RangeError(message);
+function assertFinitePositive(value, path, example = '1') {
+ if (!Number.isFinite(value) || value <= 0) throw invalidField(path, value, `a finite number above 0, such as ${example}`);
}
function clamp(value, minimum, maximum) {
@@ -186,15 +187,15 @@ function createSource({ parts, graph, asset }) {
return createAssetSource(asset);
}
-function resolveEntry(source, reference) {
+function resolveEntry(source, reference, path = 'target') {
if (source.byKey.has(reference)) return source.byKey.get(reference);
if (Number.isInteger(reference) && source.kind === 'parts' && source.entries[reference]) return source.entries[reference];
if (typeof reference === 'string') {
const matches = source.entries.filter(entry => entry.label === reference);
if (matches.length === 1) return matches[0];
- if (matches.length > 1) throw new RangeError(`Vehicle ${source.kind} name is ambiguous: ${reference}`);
+ if (matches.length > 1) throw invalidField(path, reference, `a ${source.kind} name that is used once; this name matches ${matches.length}, such as an id from scene_inspect`);
}
- throw new RangeError(`Vehicle ${source.kind} was not found: ${String(reference?.name ?? reference)}`);
+ throw invalidField(path, reference?.name ?? reference, `the name of a ${source.kind === 'parts' ? 'part' : 'node'} in the asset, such as one scene_inspect lists`);
}
function collectMeshes(source, entry, meshes = []) {
@@ -280,20 +281,21 @@ function detectWheelGroups(source, forward) {
}
function normalizeWheelSpec(source, spec, index) {
+ const path = `wheels[${index}]`;
const references = spec.targets ?? spec.parts ?? spec.nodes ?? [spec.target ?? spec.part ?? spec.node];
if (!Array.isArray(references) || references.length === 0 || references.includes(undefined)) {
- throw new TypeError(`Wheel ${index} needs a part, node or targets list.`);
+ throw invalidField(`${path}.node`, spec.node, 'a node, part or targets list, such as "wheel-0"', TypeError);
}
- const entries = references.map(reference => resolveEntry(source, reference));
- return { id: spec.id ?? entries[0].label, entries, axle: spec.axle, side: spec.side, spec };
+ const entries = references.map(reference => resolveEntry(source, reference, `${path}.node`));
+ return { id: spec.id ?? entries[0].label, index, entries, axle: spec.axle, side: spec.side, spec };
}
function describeWheels(source, wheelOption, forward) {
if (wheelOption === undefined || wheelOption === 'auto') {
const { groups, rejected } = detectWheelGroups(source, forward);
- return { described: groups.map(group => ({ id: group.id, entries: group.entries, axle: group.axle, side: group.side, spec: {} })), rejected };
+ return { described: groups.map((group, index) => ({ id: group.id, index, entries: group.entries, axle: group.axle, side: group.side, spec: {} })), rejected };
}
- if (!Array.isArray(wheelOption)) throw new TypeError("wheels must be an array of wheel descriptions or 'auto'.");
+ if (!Array.isArray(wheelOption)) throw invalidField('wheels', wheelOption, `"auto", or an array of wheel descriptions, such as "auto"`, TypeError);
return { described: wheelOption.map((spec, index) => normalizeWheelSpec(source, spec, index)), rejected: [] };
}
@@ -303,12 +305,12 @@ function measureDescribedWheel(source, described, forward) {
const center = described.spec.center ?? measured?.center;
const radius = described.spec.radius ?? measured?.radius;
if (!center || radius === undefined) {
- throw new RangeError(`Wheel ${described.id} needs a radius and center, or geometry to measure them from.`);
+ throw invalidField(`wheels[${described.index}].radius`, radius, 'a radius with a center, or geometry to measure them from, such as 0.35');
}
if (center.length !== 3 || !Array.from(center).every(Number.isFinite)) {
- throw new RangeError(`Wheel ${described.id} center must be three finite numbers.`);
+ throw invalidField(`wheels[${described.index}].center`, center, 'an array of 3 finite numbers, such as [0.8, 0.35, 1.2]');
}
- assertFinitePositive(radius, `Wheel ${described.id} radius must be positive and finite.`);
+ assertFinitePositive(radius, `wheels[${described.index}].radius`, '0.35');
return { ...described, center: Array.from(center), radius };
}
@@ -332,10 +334,10 @@ function resolveWheelLayout(measuredWheels, forward) {
const centerLocal = vec3.transformMat4(vec3.create(), wheel.center, inverseRestFrame);
const side = wheel.side ?? (Math.abs(centerLocal[0]) < 1e-4 ? 'center' : centerLocal[0] > 0 ? 'left' : 'right');
const axle = wheel.axle ?? (centerLocal[2] >= 0 ? 'front' : 'rear');
- if (!['left', 'right', 'center'].includes(side)) throw new RangeError(`Wheel ${wheel.id} side must be left, right or center.`);
- if (!['front', 'rear'].includes(axle)) throw new RangeError(`Wheel ${wheel.id} axle must be front or rear.`);
+ if (!['left', 'right', 'center'].includes(side)) throw invalidField(`wheels[${wheel.index}].side`, side, 'one of left, right, center');
+ if (!['front', 'rear'].includes(axle)) throw invalidField(`wheels[${wheel.index}].axle`, axle, 'one of front, rear');
const spinSign = wheel.spec.spinSign ?? 1;
- if (spinSign !== 1 && spinSign !== -1) throw new RangeError(`Wheel ${wheel.id} spinSign must be 1 or -1.`);
+ if (spinSign !== 1 && spinSign !== -1) throw invalidField(`wheels[${wheel.index}].spinSign`, spinSign, 'one of 1, -1');
return {
id: wheel.id || `wheel-${index}`,
entries: wheel.entries,
@@ -352,7 +354,7 @@ function resolveWheelLayout(measuredWheels, forward) {
function resolveWheelbase(wheels, wheelbaseOption) {
if (wheelbaseOption !== undefined) {
- assertFinitePositive(wheelbaseOption, 'wheelbase must be positive and finite.');
+ assertFinitePositive(wheelbaseOption, 'wheelbase', '2.7');
return wheelbaseOption;
}
const front = wheels.filter(wheel => wheel.axle === 'front');
@@ -362,27 +364,27 @@ function resolveWheelbase(wheels, wheelbaseOption) {
if (distance > 1e-6) return distance;
}
if (wheels.some(wheel => wheel.steerable)) {
- throw new RangeError('Cannot measure the wheelbase from the wheels. Pass wheelbase in metres or mark axles front and rear.');
+ throw invalidField('wheelbase', undefined, 'a wheelbase in metres, such as 2.7, or wheels marked with axle front and rear so it can be measured');
}
return 0;
}
function resolveBodyEntries(source, bodyOption, wheels) {
if (bodyOption !== undefined) {
- if (!Array.isArray(bodyOption) || bodyOption.length === 0) throw new TypeError('body must be a non-empty array of parts or nodes.');
- return bodyOption.map(reference => resolveEntry(source, reference));
+ if (!Array.isArray(bodyOption) || bodyOption.length === 0) throw invalidField('body', bodyOption, 'a non-empty array of parts or nodes, such as ["body"]', TypeError);
+ return bodyOption.map((reference, index) => resolveEntry(source, reference, `body[${index}]`));
}
const wheelKeys = new Set(wheels.flatMap(wheel => wheel.entries.map(entry => entry.key)));
const bodyEntries = source.entries.filter(entry => !wheelKeys.has(entry.key) && !isDescendantOfAny(source, entry, wheelKeys) &&
(source.kind === 'parts' || entry.parentKey === null));
- if (bodyEntries.length === 0) throw new RangeError('No body parts remain after removing the wheels. Pass body explicitly.');
+ if (bodyEntries.length === 0) throw invalidField('body', undefined, 'a list of the body nodes, such as ["body"], since no body parts remain after removing the wheels');
return bodyEntries;
}
function assertNoPivot(entries) {
for (const entry of entries) {
if (entry.pivot && entry.pivot.some(component => component !== 0)) {
- throw new RangeError(`Vehicle node ${entry.label} has a nonzero pivot, which vehicle poses do not support.`);
+ throw invalidField('body', entry.label, 'nodes with a zero pivot, since vehicle poses do not support a nonzero one; pick another node');
}
}
}
@@ -393,8 +395,8 @@ function transformDirection(matrix, origin, direction) {
return vec3.normalize(tip, vec3.subtract(tip, tip, base));
}
-function assertVector3(value, message) {
- if (!value || value.length !== 3 || !Array.from(value).every(Number.isFinite)) throw new TypeError(message);
+function assertVector3(value, path) {
+ if (!value || value.length !== 3 || !Array.from(value).every(Number.isFinite)) throw invalidField(path, value, 'an array of 3 finite numbers, such as [0.5, 0.6, 2]', TypeError);
}
/**
@@ -403,9 +405,9 @@ function assertVector3(value, message) {
*/
function resolveLights(source, lights = {}, inverseRestFrame, forward) {
const headlights = (lights.headlights ?? []).map((light, index) => {
- assertVector3(light.position, `Headlight ${index} needs a position of three finite numbers.`);
+ assertVector3(light.position, `lights.headlights[${index}].position`);
const direction = light.direction ?? forward;
- assertVector3(direction, `Headlight ${index} direction must be three finite numbers.`);
+ assertVector3(direction, `lights.headlights[${index}].direction`);
const position = vec3.transformMat4(vec3.create(), light.position, inverseRestFrame);
return {
id: light.id ?? `headlight-${index}`,
@@ -414,14 +416,14 @@ function resolveLights(source, lights = {}, inverseRestFrame, forward) {
};
});
const tailLights = (lights.tailLights ?? []).map((light, index) => {
- if (light.signal !== 'brake' && light.signal !== 'reverse') throw new RangeError(`Tail light ${index} signal must be brake or reverse.`);
+ if (light.signal !== 'brake' && light.signal !== 'reverse') throw invalidField(`lights.tailLights[${index}].signal`, light.signal, 'one of brake, reverse');
const references = light.targets ?? light.parts ?? light.nodes ?? [light.target ?? light.part ?? light.node];
if (!Array.isArray(references) || references.length === 0 || references.includes(undefined)) {
- throw new TypeError(`Tail light ${index} needs a part, node or targets list.`);
+ throw invalidField(`lights.tailLights[${index}].node`, light.node, 'a node, part or targets list, such as "tail"', TypeError);
}
const { off = 0, on = 4 } = light;
- if (!Number.isFinite(off) || !Number.isFinite(on) || off < 0 || on < 0) throw new RangeError(`Tail light ${index} off and on must be zero or positive.`);
- const entries = references.map(reference => resolveEntry(source, reference));
+ if (!Number.isFinite(off) || !Number.isFinite(on) || off < 0 || on < 0) throw invalidField(`lights.tailLights[${index}].${Number.isFinite(off) && off >= 0 ? 'on' : 'off'}`, Number.isFinite(off) && off >= 0 ? on : off, 'a number of 0 or more, such as 4');
+ const entries = references.map(reference => resolveEntry(source, reference, `lights.tailLights[${index}].node`));
return { id: light.id ?? entries[0].label, signal: light.signal, entries, off, on };
});
return { headlights: Object.freeze(headlights), tailLights: Object.freeze(tailLights) };
@@ -434,12 +436,12 @@ function resolveLights(source, lights = {}, inverseRestFrame, forward) {
*/
export function createVehicleRig({ parts, graph, asset, body, wheels = 'auto', forwardAxis = '+z', wheelbase, maxSteerAngle = DEFAULT_MAX_STEER_ANGLE, lights } = {}) {
const forward = FORWARD_AXES[forwardAxis];
- if (!forward) throw new RangeError('forwardAxis must be one of +x, -x, +z or -z.');
- assertFinitePositive(maxSteerAngle, 'maxSteerAngle must be positive radians.');
+ if (!forward) throw invalidField('forwardAxis', forwardAxis, 'one of +x, -x, +z, -z');
+ assertFinitePositive(maxSteerAngle, 'maxSteerAngle', '0.6');
const source = createSource({ parts, graph, asset });
const { described, rejected } = describeWheels(source, wheels, forward);
if (described.length < 2) {
- throw new RangeError(`A vehicle rig needs at least two wheels, found ${described.length}. Pass wheels explicitly or check findWheelCandidates.`);
+ throw invalidField('wheels', described.length, 'at least 2 wheels, such as "auto" on a car with 4 wheel nodes, or a list of wheel nodes');
}
const measuredWheels = described.map(item => measureDescribedWheel(source, item, forward));
const layout = resolveWheelLayout(measuredWheels, forward);
@@ -467,7 +469,7 @@ export function createVehicleRig({ parts, graph, asset, body, wheels = 'auto', f
function validatePoint(point, index) {
if ((!Array.isArray(point) && !ArrayBuffer.isView(point)) || point.length !== 3 || !Array.from(point).every(Number.isFinite)) {
- throw new TypeError(`Path point ${index} must be three finite numbers.`);
+ throw invalidField(`path[${index}]`, point, 'an array of 3 finite numbers, such as [0, 0, 10]', TypeError);
}
}
@@ -480,7 +482,7 @@ function pointsFromPath(path, pathSamples) {
}
return points;
}
- throw new TypeError('Path must be an array of [x, y, z] points or a camera path with duration and sample(time).');
+ throw invalidField('path', path, 'an array of [x, y, z] points, such as [[0, 0, 0], [0, 0, 10]], or a camera path with duration and sample(time)', TypeError);
}
function removeRepeatedPoints(points) {
@@ -525,7 +527,7 @@ function resampleUniformly(polyline) {
lengths.push(lengths[index - 1] + vec3.distance(polyline[index - 1], polyline[index]));
}
const total = lengths.at(-1);
- if (!(total > 1e-6)) throw new RangeError('Path has zero length.');
+ if (!(total > 1e-6)) throw invalidField('path', 'a path of zero length', 'points that are not all the same, such as [[0, 0, 0], [0, 0, 10]]');
const intervals = Math.max(2, Math.ceil(total / Math.max(PATH_SPACING_METRES, total / MAX_PATH_SAMPLES)));
const spacing = total / intervals;
const positions = [];
@@ -552,9 +554,9 @@ function smoothed(values, radius) {
function buildPathTable(path, pathSamples) {
const points = pointsFromPath(path, pathSamples);
- points.forEach(validatePoint);
+ points.forEach((point, index) => validatePoint(point, index));
const distinct = removeRepeatedPoints(points);
- if (distinct.length < 2) throw new RangeError('Path needs at least two distinct points.');
+ if (distinct.length < 2) throw invalidField('path', `${distinct.length} distinct point`, 'at least 2 distinct points, such as [[0, 0, 0], [0, 0, 10]]');
const { positions, spacing, length } = resampleUniformly(splinePolyline(distinct));
const headings = [];
const slopes = [];
@@ -595,7 +597,7 @@ function createSpeedProfile(table, options) {
const times = new Float64Array(count);
for (let index = 1; index < count; index++) {
const meanSpeed = (speeds[index - 1] + speeds[index]) / 2;
- if (meanSpeed < 1e-9) throw new RangeError('The speed profile never leaves rest. Raise acceleration or startSpeed.');
+ if (meanSpeed < 1e-9) throw invalidField('acceleration', 'a speed profile that never leaves rest', 'a higher acceleration or startSpeed, such as acceleration 3');
times[index] = times[index - 1] + table.spacing / meanSpeed;
}
return { speeds, times, duration: times[count - 1] };
@@ -767,8 +769,8 @@ function buildLegs(legDescriptions, settings) {
const legs = [];
legDescriptions.forEach((description, index) => {
const { path, direction = 'forward', pause = 0 } = description ?? {};
- if (direction !== 'forward' && direction !== 'reverse') throw new RangeError(`Leg ${index} direction must be forward or reverse.`);
- if (!Number.isFinite(pause) || pause < 0) throw new RangeError(`Leg ${index} pause must be zero or positive seconds.`);
+ if (direction !== 'forward' && direction !== 'reverse') throw invalidField(`legs[${index}].direction`, direction, 'one of forward, reverse');
+ if (!Number.isFinite(pause) || pause < 0) throw invalidField(`legs[${index}].pause`, pause, 'seconds of 0 or more, such as 2');
const previous = legs.at(-1);
const sign = direction === 'reverse' ? -1 : 1;
const startTime = previous ? previous.endTime + pause : settings.startTime;
@@ -807,7 +809,7 @@ function buildLegs(legDescriptions, settings) {
*/
export function driveAlongLegs(rig, legDescriptions, options = {}) {
if (!rig || !rig.wheels || !rig.restFrame) throw new TypeError('driveAlongPath needs a rig from createVehicleRig.');
- if (!Array.isArray(legDescriptions) || legDescriptions.length === 0) throw new TypeError('legs must be a non-empty array of { path, direction, pause }.');
+ if (!Array.isArray(legDescriptions) || legDescriptions.length === 0) throw invalidField('legs', legDescriptions, 'a non-empty array of { path, direction, pause }, such as [{ "path": [[0, 0, 0], [0, 0, 10]] }]', TypeError);
const settings = resolveDriveOptions(rig, options);
const legs = buildLegs(legDescriptions, settings);
const duration = legs.at(-1).endTime;
@@ -891,27 +893,28 @@ function resolveDriveOptions(rig, options) {
bounceFrequency = 1.6, dampingRatio = 0.45, suspensionTravel = 0.2, pathSamples = 400,
steering = 'ackermann', fullBrakeDeceleration = braking,
} = options;
- if (steering !== 'ackermann' && steering !== 'shared') throw new RangeError("steering must be 'ackermann' or 'shared'.");
- assertFinitePositive(fullBrakeDeceleration, 'fullBrakeDeceleration must be positive and finite.');
+ if (steering !== 'ackermann' && steering !== 'shared') throw invalidField('steering', steering, 'one of ackermann, shared');
+ assertFinitePositive(fullBrakeDeceleration, 'fullBrakeDeceleration', '4');
if ((speed === undefined) === (cruiseSpeed === undefined)) {
- throw new TypeError('Give exactly one of speed (constant) or cruiseSpeed (with acceleration and braking).');
+ throw invalidField(speed === undefined ? 'speed' : 'cruiseSpeed', speed ?? cruiseSpeed, 'exactly one of speed (constant) or cruiseSpeed (with acceleration and braking), such as speed 8', TypeError);
}
- if (speed !== undefined) assertFinitePositive(speed, 'speed must be positive and finite.');
+ if (speed !== undefined) assertFinitePositive(speed, 'speed', '8');
if (cruiseSpeed !== undefined) {
- assertFinitePositive(cruiseSpeed, 'cruiseSpeed must be positive and finite.');
- assertFinitePositive(acceleration, 'acceleration must be positive and finite.');
- assertFinitePositive(braking, 'braking must be positive and finite.');
+ assertFinitePositive(cruiseSpeed, 'cruiseSpeed', '8');
+ assertFinitePositive(acceleration, 'acceleration', '3');
+ assertFinitePositive(braking, 'braking', '4');
}
- if (!Number.isFinite(startTime) || startTime < 0) throw new RangeError('startTime must be zero or positive.');
+ if (!Number.isFinite(startTime) || startTime < 0) throw invalidField('startTime', startTime, 'seconds of 0 or more, such as 0');
if (groundHeight !== undefined && typeof groundHeight !== 'function') throw new TypeError('groundHeight must be a function (x, z) => height.');
- assertFinitePositive(maxSteerAngle, 'maxSteerAngle must be positive radians.');
- assertFinitePositive(bounceFrequency, 'bounceFrequency must be positive.');
- assertFinitePositive(dampingRatio, 'dampingRatio must be positive.');
+ assertFinitePositive(maxSteerAngle, 'maxSteerAngle', '0.6');
+ assertFinitePositive(bounceFrequency, 'bounceFrequency', '1.6');
+ assertFinitePositive(dampingRatio, 'dampingRatio', '0.45');
if (!Number.isFinite(startSpeed) || startSpeed < 0 || !Number.isFinite(endSpeed) || endSpeed < 0) {
- throw new RangeError('startSpeed and endSpeed must be zero or positive.');
+ const badSpeedField = !Number.isFinite(startSpeed) || startSpeed < 0 ? 'startSpeed' : 'endSpeed';
+ throw invalidField(badSpeedField, badSpeedField === 'startSpeed' ? startSpeed : endSpeed, 'a speed of 0 or more, such as 0');
}
- if (!(maxLateralAcceleration > 0)) throw new RangeError('maxLateralAcceleration must be positive.');
- if (!Number.isInteger(pathSamples) || pathSamples < 8) throw new RangeError('pathSamples must be an integer of at least 8.');
+ if (!(maxLateralAcceleration > 0)) throw invalidField('maxLateralAcceleration', maxLateralAcceleration, 'a number above 0, such as 6');
+ if (!Number.isInteger(pathSamples) || pathSamples < 8) throw invalidField('pathSamples', pathSamples, 'a whole number of 8 or more, such as 400');
return {
speed, cruiseSpeed, acceleration, braking, startSpeed, endSpeed, maxLateralAcceleration, startTime, groundHeight,
maxSteerAngle, rollGain, pitchGain, bounceFrequency, dampingRatio, suspensionTravel, pathSamples, steering, fullBrakeDeceleration,
diff --git a/tests/actionable-errors.test.js b/tests/actionable-errors.test.js
index 96d412ee..f357ec41 100644
--- a/tests/actionable-errors.test.js
+++ b/tests/actionable-errors.test.js
@@ -1,6 +1,11 @@
+import './support/load-agent-scene-modules.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
import { createAgentScene } from '../src/agent-scene.js';
+import { createAgentAssetScene } from '../src/agent-asset.js';
+import { parseGltf } from '../src/gltf.js';
+import { carAsset } from './fixtures/car-glb.js';
import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
import { describeReceived, invalidField, withFieldPrefix } from '../src/field-error.js';
@@ -23,6 +28,35 @@ function badRecipe(change) {
};
}
+const ASSET_ID = 'ca'.repeat(32);
+const DRIVE_PATH = [[0, 0, 0], [0, 0, 12], [6, 0, 22]];
+
+// Builds the decoded car asset, hands it to the check and releases it afterwards.
+async function withCar(check) {
+ const asset = await parseGltf(carAsset());
+ try {
+ return await check(asset);
+ } finally {
+ asset.dispose();
+ }
+}
+
+function badAsset(change) {
+ return () => withCar(asset => {
+ const recipe = { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID };
+ change(recipe);
+ return createAgentAssetScene(asset, recipe);
+ });
+}
+
+function badAssetApply(operation) {
+ return () => withCar(asset => createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID }).apply([operation], { expectedRevision: 0 }));
+}
+
+function badAssetInspect(options) {
+ return () => withCar(asset => createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID }).inspect(options));
+}
+
function badApply(operation) {
return async () => {
const recipe = baseRecipe();
@@ -70,12 +104,36 @@ const CASES = [
['motion duration too long', badRecipe(recipe => { recipe.motion.duration = 100; }), 'motion.duration', '100'],
['motion loop as text', badRecipe(recipe => { recipe.motion.loop = 'yes'; }), 'motion.loop', '"yes"'],
['motion interpolation unknown', badRecipe(recipe => { recipe.motion.tracks[0].interpolation = 'BOUNCE'; }), 'motion.tracks[0].interpolation', '"BOUNCE"'],
+ ['physics body mass below range', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 1, bodies: [{ node: 'body', mass: -1 }] }; }), 'physics.bodies[0].mass', '-1'],
+ ['physics body type unknown', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 1, bodies: [{ node: 'body', type: 'liquid' }] }; }), 'physics.bodies[0].type', '"liquid"'],
+ ['physics velocity on a fixed body', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 1, bodies: [{ node: 'body', type: 'fixed', velocity: [1, 0, 0] }] }; }), 'physics.bodies[0].velocity', '[1,0,0]'],
+ ['physics joint to a node without a body', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 1, bodies: [{ node: 'body' }], joints: [{ type: 'fixed', bodyA: 'body', bodyB: 'ghost' }] }; }), 'physics.joints[0].bodyB', '"ghost"'],
+ ['physics gravity with two numbers', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 1, gravity: [0, -9], bodies: [{ node: 'body' }] }; }), 'physics.gravity', '[0,-9]'],
+ ['physics duration too long', badRecipe(recipe => { delete recipe.motion; recipe.physics = { duration: 99, bodies: [{ node: 'body' }] }; }), 'physics.duration', '99'],
+ ['drive wheel node missing', badAsset(recipe => { recipe.motion = { drive: { path: DRIVE_PATH, speed: 3, wheels: [{ node: 'Wheel_FL' }, { node: 'Nope' }] } }; }), 'motion.drive.wheels[1].node', '"Nope"'],
+ ['drive speed below zero', badAsset(recipe => { recipe.motion = { drive: { path: DRIVE_PATH, speed: -3 } }; }), 'motion.drive.speed', '-3'],
+ ['drive steering unknown', badAsset(recipe => { recipe.motion = { drive: { path: DRIVE_PATH, speed: 3, steering: 'both' } }; }), 'motion.drive.steering', '"both"'],
+ ['drive path with one point', badAsset(recipe => { recipe.motion = { drive: { path: [[0, 0, 0]], speed: 3 } }; }), 'motion.drive.path', '"1 points"'],
+ ['drive tail light signal unknown', badAsset(recipe => { recipe.motion = { drive: { path: DRIVE_PATH, speed: 3, lights: { tailLights: [{ material: 'material-1', signal: 'fog' }] } } }; }), 'motion.drive.lights.tailLights[0].signal', '"fog"'],
+ ['asset root scale zero', badAsset(recipe => { recipe.root = { scale: [0, 1, 1] }; }), 'root.scale', '[0,1,1]'],
+ ['asset id not hexadecimal', badAsset(recipe => { recipe.assetId = 'zz'; }), 'assetId', '"zz"'],
+ ['asset material override unknown id', badAsset(recipe => { recipe.materialOverrides = [{ id: 'material-99' }]; }), 'materialOverrides[0].id', '"material-99"'],
+ ['asset operation unknown type', badAssetApply({ type: 'add-node' }), 'operations[0].type', '"add-node"'],
+ ['asset set-material unknown id', badAssetApply({ type: 'set-material', id: 'material-99' }), 'operations[0].id', '"material-99"'],
+ ['asset inspect limit too high', badAssetInspect({ limit: 1000 }), 'limit', '1000'],
+ ['placed asset id not hexadecimal', badRecipe(recipe => { recipe.nodes[1].asset = { id: 'nothex' }; }), 'nodes[1].asset.id', '"nothex"'],
+ ['placed asset clip index below zero', badRecipe(recipe => { recipe.nodes[1].asset = { id: ASSET_ID, clip: { index: -1 } }; }), 'nodes[1].asset.clip.index', '-1'],
+ ['placed asset material tag unknown', badRecipe(recipe => { recipe.nodes[1].asset = { id: ASSET_ID, materials: [{ name: 'Paint', tag: 'water' }] }; }), 'nodes[1].asset.materials[0].tag', '"water"'],
+ ['placed asset drive forwardAxis unknown', badRecipe(recipe => { recipe.nodes[1].asset = { id: ASSET_ID, drive: { path: DRIVE_PATH, speed: 3, forwardAxis: '+y' } }; }), 'nodes[1].asset.drive.forwardAxis', '"+y"'],
+ ['shrinkwrap finds no surface', badApply({ type: 'edit-mesh', geometry: 'block', edits: [{ op: 'shrinkwrap', target: { type: 'sphere', segments: 8 }, translation: [20, 0, 0], maxDistance: 1, onMiss: 'error' }] }), 'edits[0].onMiss', '"error"'],
+ ['shrinkwrap mode unknown', badApply({ type: 'edit-mesh', geometry: 'block', edits: [{ op: 'shrinkwrap', target: { type: 'sphere', segments: 8 }, mode: 'wrap' }] }), 'edits[0].mode', '"wrap"'],
+ ['shrinkwrap maxDistance below zero', badApply({ type: 'edit-mesh', geometry: 'block', edits: [{ op: 'shrinkwrap', target: { type: 'sphere', segments: 8 }, maxDistance: -1 }] }), 'edits[0].maxDistance', '-1'],
];
// 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|\bor more\b/;
-assert.ok(CASES.length >= 20, 'the walk covers at least 20 bad inputs');
+assert.ok(CASES.length >= 50, 'the walk covers at least 50 bad inputs');
for (const [label, trigger, path, received] of CASES) {
test(`error for ${label} names the field, the value and what is accepted`, async () => {
@@ -126,3 +184,78 @@ test('a schema error through the MCP layer names the field path and the value re
await client.close();
}
});
+
+// The guard: these files hold the validators an agent reaches through recipes and operations (physics, drive, asset,
+// placed asset, imported mesh edits, shrinkwrap). A throw in them reports through invalidField, which names the path,
+// the value and what is accepted. The throws listed here stay raw on purpose: whole-input size limits, host wiring and
+// engine invariants no recipe field can fix. A new raw throw fails this test until it uses invalidField or is listed.
+const RAW_THROWS_LEFT = {
+ 'src/agent-physics.js': [
+],
+ 'src/agent-drive-schema.js': [
+],
+ 'src/agent-drive.js': [
+],
+ 'src/agent-asset.js': [
+ "'Asset recipe JSON exceeds 1 MiB. Reduce",
+ "'Asset recipe JSON nesting exceeds 64 le",
+ "'Asset recipe JSON exceeds 1 MiB.');",
+ "'Asset recipe requires finite, acyclic J",
+ "'Asset recipe arrays must be ordinary bo",
+ "'Asset recipe objects must be plain JSON",
+ "'Invalid asset recipe JSON key.');",
+ "'Asset recipe accessors and hidden field",
+ "'Asset recipe arrays must be dense witho",
+ "'Asset recipe arrays cannot contain trai",
+ "'Asset recipe JSON exceeds 1 MiB.');",
+ "'Asset world/skin matrix products exceed",
+ "'Asset world geometry bounds exceed Floa",
+ "'createAgentAssetScene requires a decode",
+ "'This file has no meshes, so there is no",
+ "'Asset budgets allow 4096 parts, 4096 ma",
+ "'The asset has no authored motion or phy",
+ "'Decoded part membership must remain fix",
+ "'Decoded resources and retained adapter ",
+ "'Asset root/world matrices must remain f",
+ ],
+ 'src/agent-asset-mesh.js': [
+ "failureMessage(record, error));",
+ "`${entry.id}: ${error.message}`);",
+ ],
+ 'src/agent-scene-assets.js': [
+ "'This recipe places a crowd, which loads",
+ "'This recipe places catalog assets, whic",
+ "`A scene places at most ${ASSET_PLACEMEN",
+ "`Asset ${assetId.slice(0, 12)} copy ${co",
+ "`Placed assets expand to ${generatedNode",
+ "'This recipe drives a placed asset, whic",
+ ],
+ 'src/vehicle.js': [
+ "'findWheelCandidates needs an array of n",
+ "'parts must be a non-empty array of part",
+ "`Part ${index} needs a 16-value matrix.`",
+ "'graph must be a scene graph with nodes.",
+ "'asset must be a loadGltf result with no",
+ "'createVehicleRig needs exactly one of p",
+ "'groundHeight must return a finite numbe",
+ "'driveAlongPath needs a rig from createV",
+ "'Sample time must be finite.');",
+ "'groundHeight must be a function (x, z) ",
+ "'pose must come from drive.sample for th",
+ "`Tail light ${id} part needs a material ",
+ "'pose must come from drive.sample for th",
+ "`This rig was built from ${rig.kind}, no",
+ "`Imported node ${entry.label} has an aut",
+ ],
+ 'src/mesh-shrinkwrap.js': [
+],
+};
+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 invalidField(path, value, expected) from src/field-error.js; list a throw here only when no input field can cause it`);
+ });
+}
diff --git a/tests/agent-asset-mesh.test.js b/tests/agent-asset-mesh.test.js
index c58b5c8f..f59a08f8 100644
--- a/tests/agent-asset-mesh.test.js
+++ b/tests/agent-asset-mesh.test.js
@@ -182,9 +182,9 @@ test('hostile mesh edits are rejected without changing the scene', async () => {
const scene = createScene(asset);
const revision = scene.revision;
const hostile = [
- ['unknown mesh', () => applyEdits(scene, 'mesh-99', [{ op: 'delete', select: { tag: 'top' } }]), /Unknown mesh ID/],
- ['prototype key', () => applyEdits(scene, '__proto__', [{ op: 'delete', select: { tag: 'top' } }]), /Unknown mesh ID/],
- ['edits not an array', () => scene.apply([{ type: 'edit-mesh', geometry: TORSO, edits: 'delete' }], { expectedRevision: revision }), /edits array/],
+ ['unknown mesh', () => applyEdits(scene, 'mesh-99', [{ op: 'delete', select: { tag: 'top' } }]), /^RangeError: operations\[0\]\.geometry: got "mesh-99"; expected an imported mesh ID such as mesh-0/],
+ ['prototype key', () => applyEdits(scene, '__proto__', [{ op: 'delete', select: { tag: 'top' } }]), /^RangeError: operations\[0\]\.geometry: got "__proto__"; expected an imported mesh ID such as mesh-0/],
+ ['edits not an array', () => scene.apply([{ type: 'edit-mesh', geometry: TORSO, edits: 'delete' }], { expectedRevision: revision }), /^TypeError: operations\[0\]\.edits: got "delete"; expected an array of edits, such as/],
['unknown operation', () => applyEdits(scene, TORSO, [{ op: 'explode' }]), /explode|op/],
['not a number', () => applyEdits(scene, TORSO, [{ op: 'extrude_face_region', select: { tag: 'top' }, offset: Number.NaN }]), /offset|finite/],
['selects nothing', () => applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'no-such-tag' } }]), /select|tag|no faces/i],
@@ -201,7 +201,7 @@ test('hostile mesh edits are rejected without changing the scene', async () => {
assert.equal(scene.topologyRevision, 0, `${label} left the topology alone`);
}
assert.throws(() => createScene(asset, { meshEdits: [{ id: TORSO, edits: [{ op: 'delete', select: { tag: 'top' } }], extra: 1 }] }), /meshEdits/);
- assert.throws(() => createScene(asset, { meshEdits: [{ id: TORSO, edits: [] }, { id: TORSO, edits: [] }] }), /repeated/);
+ assert.throws(() => createScene(asset, { meshEdits: [{ id: TORSO, edits: [] }, { id: TORSO, edits: [] }] }), /^RangeError: meshEdits.1.[.]id: got "[^"]+"; expected an imported mesh ID used once, such as /);
asset.dispose();
});
@@ -252,7 +252,7 @@ test('inspect accepts a source-node ID that holds one part and names the parts o
assert.ok(single && several && empty, 'the robot has leaf, group and mesh-less nodes');
const byNode = scene.inspect({ ids: [single.id] }).nodes;
assert.deepEqual(byNode.map(node => node.id), single.meshIds);
- assert.throws(() => scene.inspect({ ids: [several.id] }), error => error.message.includes(several.meshIds[0]) && /holds \d+ parts/.test(error.message));
- assert.throws(() => scene.inspect({ ids: [empty.id] }), /no mesh/);
- assert.throws(() => scene.inspect({ ids: ['nothing-here'] }), /Unknown mesh ID/);
+ assert.throws(() => scene.inspect({ ids: [several.id] }), error => error.message.includes(several.meshIds[0]) && /^geometry: got .*; expected one part ID, such as .*holds \d+ parts/.test(error.message));
+ assert.throws(() => scene.inspect({ ids: [empty.id] }), /^RangeError: geometry: got .*; expected a source node with a mesh of its own, or a mesh ID such as "mesh-0"/);
+ assert.throws(() => scene.inspect({ ids: ['nothing-here'] }), /^RangeError: geometry: got "nothing-here"; expected an imported mesh ID such as "mesh-0"/);
});
diff --git a/tests/agent-asset.test.js b/tests/agent-asset.test.js
index b9392fd5..c6cde7b9 100644
--- a/tests/agent-asset.test.js
+++ b/tests/agent-asset.test.js
@@ -82,7 +82,7 @@ test('failed commands and Float32 root staging leave pose, recipe, materials, an
assert.deepEqual(pose(asset), checkpointPose);
assert.deepEqual(Array.from(scene.parts[0].matrix), matrix);
assert.equal(scene.revision, 0);
- assert.throws(() => scene.apply([{ type: 'set-root', translation: [2, 0, 0] }, { type: 'add-node', node: {} }], { expectedRevision: 0 }), /Unsupported/);
+ assert.throws(() => scene.apply([{ type: 'set-root', translation: [2, 0, 0] }, { type: 'add-node', node: {} }], { expectedRevision: 0 }), /^TypeError: operations\[1\]\.type: got "add-node"; expected one of set-camera, set-root/);
assert.deepEqual(scene.exportRecipe(), checkpointRecipe);
scene.apply([{ type: 'set-animation', time: 0.25 }], { expectedRevision: 0 });
assert.equal(scene.revision, 1);
@@ -120,8 +120,8 @@ test('checkpoint handles are private, bounded, revision checked, and restore ide
const asset = await fixture();
const scene = createAgentAssetScene(asset, recipe());
const handles = Array.from({ length: 8 }, () => scene.checkpoint());
- assert.throws(() => scene.checkpoint(), /budget/);
- assert.throws(() => scene.restore({}, { expectedRevision: 0 }), /Unknown/);
+ assert.throws(() => scene.checkpoint(), /^RangeError: checkpoints: got .*; expected at most 8 saved checkpoints; release one first, such as/);
+ assert.throws(() => scene.restore({}, { expectedRevision: 0 }), /^RangeError: checkpointId: got .*; expected a checkpointId that scene_checkpoint returned and you have not released, such as/);
const parts = scene.parts;
scene.apply([{ type: 'set-root', scale: [2, 2, 2] }], { expectedRevision: 0 });
assert.throws(() => scene.restore(handles[0], { expectedRevision: 0 }), /expectedRevision/);
@@ -130,8 +130,8 @@ test('checkpoint handles are private, bounded, revision checked, and restore ide
assert.equal(scene.revision, 2);
assert.deepEqual(scene.exportRecipe().root.scale, [1, 1, 1]);
scene.releaseCheckpoint(handles[0]);
- assert.throws(() => scene.releaseCheckpoint(handles[0]), /Unknown/);
- assert.throws(() => scene.restore(handles[0], { expectedRevision: 2 }), /Unknown/);
+ assert.throws(() => scene.releaseCheckpoint(handles[0]), /^RangeError: checkpointId: got .*; expected a checkpointId that scene_checkpoint returned and you have not released, such as/);
+ assert.throws(() => scene.restore(handles[0], { expectedRevision: 2 }), /^RangeError: checkpointId: got .*; expected a checkpointId that scene_checkpoint returned and you have not released, such as/);
scene.checkpoint();
asset.dispose();
});
@@ -157,8 +157,8 @@ test('ordinary JSON, strict schemas, numeric domains, budgets, and stale revisio
assert.throws(() => createAgentAssetScene(asset, { ...recipe(), extra: 'x'.repeat(1024 * 1024) }), /1 MiB/);
const scene = createAgentAssetScene(asset, recipe());
assert.throws(() => scene.apply([{ type: 'set-root', scale: [2, 2, 2] }]), /expectedRevision/);
- assert.throws(() => scene.apply([{ type: 'set-animation', clip: null, time: 0 }], { expectedRevision: 0 }), /omitted/);
- assert.throws(() => scene.inspect({ ids: ['mesh-9'] }), /Unknown/);
+ assert.throws(() => scene.apply([{ type: 'set-animation', clip: null, time: 0 }], { expectedRevision: 0 }), /^TypeError: operations\[0\]\.time: got 0; expected no time when clip is null/);
+ assert.throws(() => scene.inspect({ ids: ['mesh-9'] }), /^RangeError: geometry: got "mesh-9"; expected an imported mesh ID such as "mesh-0"/);
assert.throws(() => createAgentAssetScene({ ...asset, animations: Array(257).fill(asset.animations[0]) }, recipe()), /budgets/);
assert.throws(() => createAgentAssetScene({ ...asset, parts: Array(4097).fill(asset.parts[0]) }, recipe()), /budgets/);
asset.dispose();
@@ -182,7 +182,7 @@ test('detached matrices and replaced pose buffers fail before publishing canonic
test('nonanimated assets support root edits and detached exports while clips reject', async () => {
const asset = await fixture(document => { document.animations = []; });
const scene = createAgentAssetScene(asset, recipe());
- assert.throws(() => scene.apply([{ type: 'set-animation', clip: 0 }], { expectedRevision: 0 }), /existing clip/);
+ assert.throws(() => scene.apply([{ type: 'set-animation', clip: 0 }], { expectedRevision: 0 }), /^RangeError: animation\.clip: got 0; expected no animation, since this asset has no clips; drop it, such as null/);
const exported = scene.exportRecipe();
exported.root.translation[0] = 100;
const camera = scene.camera;
diff --git a/tests/agent-drive.test.js b/tests/agent-drive.test.js
index 68108ed7..e12a924a 100644
--- a/tests/agent-drive.test.js
+++ b/tests/agent-drive.test.js
@@ -149,10 +149,10 @@ test('the brake signal is on only while the car slows, and the tail lamp glows w
test('a bad drive names the problem', async () => {
await withCar(asset => {
assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE })), /exactly one of speed/);
- assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, banana: 1 })), /Unknown drive field: banana/);
- assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, wheels: [{ node: 'Wheel_FL' }, { node: 'Nope' }] })), /was not found: Nope/);
- assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, lights: { tailLights: [{ material: 'material-99', signal: 'brake' }] } })), /Tail light material was not found/);
- assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3 })).apply([{ type: 'set-motion', motion: { duration: 5, drive: { legs: [{ path: CURVE, direction: 'sideways' }], speed: 3 } } }], { expectedRevision: 0 }), /direction must be forward or reverse/);
+ assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, banana: 1 })), /^TypeError: motion\.drive\.banana: got 1; expected no such field; use one of path, legs, speed/);
+ assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, wheels: [{ node: 'Wheel_FL' }, { node: 'Nope' }] })), /^RangeError: motion\.drive\.wheels\[1\]\.node: got "Nope"; expected the name of a node in the asset, such as/);
+ assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3, lights: { tailLights: [{ material: 'material-99', signal: 'brake' }] } })), /^RangeError: motion\.drive\.lights\.tailLights\[0\]\.material: got "material-99"; expected the id of a material in the asset, one of /);
+ assert.throws(() => createAgentAssetScene(asset, assetRecipe({ path: CURVE, speed: 3 })).apply([{ type: 'set-motion', motion: { duration: 5, drive: { legs: [{ path: CURVE, direction: 'sideways' }], speed: 3 } } }], { expectedRevision: 0 }), /^RangeError: motion[.]drive[.]legs.0.[.]direction: got "sideways"; expected one of forward, reverse/);
});
});
diff --git a/tests/agent-physics.test.js b/tests/agent-physics.test.js
index 783aaf66..e1179ab4 100644
--- a/tests/agent-physics.test.js
+++ b/tests/agent-physics.test.js
@@ -84,12 +84,12 @@ test('masks and layers decide what a body falls through', () => {
test('bad physics sections fail with a message that names the fix', () => {
const cases = [
- [{ duration: 3, bodies: [{ node: 'missing' }] }, /not found/],
+ [{ duration: 3, bodies: [{ node: 'missing' }] }, /^RangeError: physics\.bodies\[0\]\.node: got "missing"; expected the ID of a recipe node, one of /],
[{ duration: 0, bodies: [{ node: 'ball' }] }, /duration/],
[{ duration: 3, bodies: [] }, /at least one body/],
[{ duration: 3, bodies: [{ node: 'ball', shape: 'trimesh' }] }, /dynamic/],
- [{ duration: 3, bodies: [{ node: 'ball' }, { node: 'ball' }] }, /more than one/],
- [{ duration: 3, bodies: [{ node: 'ball', color: 1 }] }, /Unknown/],
+ [{ duration: 3, bodies: [{ node: 'ball' }, { node: 'ball' }] }, /^RangeError: physics\.bodies\[1\]\.node: got "ball"; expected a node with one physics body only/],
+ [{ duration: 3, bodies: [{ node: 'ball', color: 1 }] }, /^TypeError: physics\.bodies\[0\]\.color: got 1; expected no such field; use one of node, type, shape/],
[{ duration: 3, bodies: [{ node: 'ball' }], joints: [{ type: 'fixed', bodyA: 'ball', bodyB: 'floor' }] }, /physics body/],
[{ duration: 3, bodies: [{ node: 'ball', layer: 16 }] }, /layer/],
];
@@ -101,7 +101,7 @@ test('bad physics sections fail with a message that names the fix', () => {
test('a node cannot have both a physics body and a motion track on its pose', () => {
const input = recipe({ duration: 3, bodies: [{ node: 'ball' }] });
input.motion = { duration: 1, tracks: [{ kind: 'node', id: 'ball', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [1, 0, 0] }] }] };
- assert.throws(() => createAgentScene(input), /Pick one/);
+ assert.throws(() => createAgentScene(input), /^RangeError: physics\.bodies\[0\]\.node: got "[^"]+"; expected a node without a motion translation or rotation track; pick the track or the body, not both/);
});
test('a trimesh over the triangle limit is refused before it is copied', () => {
diff --git a/tests/agent-scene-assets.test.js b/tests/agent-scene-assets.test.js
index 50c8fe7f..d58fe258 100644
--- a/tests/agent-scene-assets.test.js
+++ b/tests/agent-scene-assets.test.js
@@ -70,7 +70,7 @@ test('material overrides name the source material and stay shared between placem
assert.equal(material('red-a'), material('red-b'));
assert.notEqual(material('red-a'), material('plain'));
assert.throws(() => createAgentScene(recipe([{ id: 'bad', asset: { id: ASSET_ID, materials: [{ name: 'Nope', color: [1, 0, 0] }] } }]), {}, { assets: new Map([[assetCopyKey(ASSET_ID, 0), null]]) }), /not loaded/);
- await assert.rejects(async () => createAgentScene(recipe([{ id: 'bad', asset: { id: ASSET_ID, materials: [{ name: 'Nope', color: [1, 0, 0] }] } }]), {}, { assets: await loadedAssets() }), /no material named "Nope"/);
+ await assert.rejects(async () => createAgentScene(recipe([{ id: 'bad', asset: { id: ASSET_ID, materials: [{ name: 'Nope', color: [1, 0, 0] }] } }]), {}, { assets: await loadedAssets() }), /^RangeError: nodes\[1\]\.asset\.materials\[0\]\.name: got "Nope"; expected one of "Skin"/);
});
test('a placed clip plays on its own time offset and a seek gives the same frame', async () => {
diff --git a/tests/agent-scene-vegetation.test.js b/tests/agent-scene-vegetation.test.js
index 07ab9b68..528a29cc 100644
--- a/tests/agent-scene-vegetation.test.js
+++ b/tests/agent-scene-vegetation.test.js
@@ -162,5 +162,5 @@ test('an imported tree with a foliage override gets the swaying tag and shares i
assert.equal(material('a').tag, 'foliage');
assert.equal(material('a'), material('b'));
assert.notEqual(material('plain').tag, 'foliage');
- assert.throws(() => createAgentScene({ ...recipe, nodes: [{ id: 'a', asset: { id, materials: [{ name: 'Leaves', tag: 'water' }] } }] }, {}, { assets }), /tag must be one of/);
+ assert.throws(() => createAgentScene({ ...recipe, nodes: [{ id: 'a', asset: { id, materials: [{ name: 'Leaves', tag: 'water' }] } }] }, {}, { assets }), /^RangeError: nodes\[0\]\.asset\.materials\[0\]\.tag: got "water"; expected one of surface, foliage, grass/);
});
diff --git a/tests/mesh-sculpt-shrinkwrap.test.js b/tests/mesh-sculpt-shrinkwrap.test.js
index c66cc366..36f15f4e 100644
--- a/tests/mesh-sculpt-shrinkwrap.test.js
+++ b/tests/mesh-sculpt-shrinkwrap.test.js
@@ -166,7 +166,7 @@ test('shrinkwrap project follows a direction and honours placement and select',
test('shrinkwrap misses are an error or kept in place, and maxDistance bounds the search', () => {
const far = sheet(4, 0.4, 5);
- assert.throws(() => run(far, [{ op: 'shrinkwrap', target: SPHERE_TARGET, maxDistance: 1 }]), /Mesh edit 0 \(shrinkwrap\).*no surface/);
+ assert.throws(() => run(far, [{ op: 'shrinkwrap', target: SPHERE_TARGET, maxDistance: 1 }]), /^RangeError: edits\[0\]\.onMiss: got "error"; expected "keep", such as onMiss "keep", to leave vertices that find no surface in place/);
const kept = run(far, [{ op: 'shrinkwrap', target: SPHERE_TARGET, maxDistance: 1, onMiss: 'keep' }]);
assert.equal(kept.results[0].missedVertices, 25);
assert.equal(kept.results[0].movedVertices, 0);
diff --git a/tests/ragdoll.test.js b/tests/ragdoll.test.js
index 5b401d8b..95df16cb 100644
--- a/tests/ragdoll.test.js
+++ b/tests/ragdoll.test.js
@@ -75,9 +75,9 @@ test('a scene without physics never loads the ragdoll code path', () => {
test('bad ragdoll sections fail with a message that names the fix', () => {
const cases = [
- [{ ragdoll: { armature: 'missing' } }, /armature was not found/],
- [{ ragdoll: {} }, /armature was not found/],
- [{ ragdoll: { armature: 'rig', color: 1 } }, /Unknown/],
+ [{ ragdoll: { armature: 'missing' } }, /^RangeError: physics\.ragdoll\.armature: got "missing"; expected the ID of a recipe armature, one of rig/],
+ [{ ragdoll: {} }, /^RangeError: physics\.ragdoll\.armature: got undefined; expected the ID of a recipe armature, one of rig/],
+ [{ ragdoll: { armature: 'rig', color: 1 } }, /^TypeError: physics\.ragdoll\.color: got 1; expected no such field; use one of armature, density/],
[{ ragdoll: { armature: 'rig', density: 0 } }, /density/],
[{ ragdoll: { armature: 'rig', layer: 16 } }, /layer/],
[{ ragdoll: { armature: 'rig', friction: -1 } }, /friction/],
@@ -93,7 +93,7 @@ test('bad ragdoll sections fail with a message that names the fix', () => {
test('a bone cannot have both a ragdoll and a pose track', () => {
const recipe = ragdollWalker();
recipe.motion = { duration: 1, tracks: [{ kind: 'node', id: 'leftUpperLeg', property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: 1, value: [0, 0, 0, 1] }] }] };
- assert.throws(() => createAgentScene(recipe), /Pick one/);
+ assert.throws(() => createAgentScene(recipe), /^RangeError: physics\.ragdoll\.armature: got "rig"; expected an armature whose bones have no motion translation or rotation track, but leftUpperLeg has one; pick the track or the ragdoll/);
});
test('an armature larger than the bone limit is refused before the solver runs', () => {
diff --git a/tests/vehicle-steering-lights.test.js b/tests/vehicle-steering-lights.test.js
index ec95f540..eef6af71 100644
--- a/tests/vehicle-steering-lights.test.js
+++ b/tests/vehicle-steering-lights.test.js
@@ -212,8 +212,8 @@ test('legs and lights sample the same pose whatever order they are read in', ()
test('bad steering, light and leg input produces specific errors', () => {
const { rig } = createLitRig();
- assert.throws(() => driveAlongPath(rig, [[0, 0, 0], [0, 0, 5]], { speed: 1, steering: 'both' }), /steering must be/);
+ assert.throws(() => driveAlongPath(rig, [[0, 0, 0], [0, 0, 5]], { speed: 1, steering: 'both' }), /^RangeError: steering: got "both"; expected one of ackermann, shared/);
assert.throws(() => driveAlongLegs(rig, [], { speed: 1 }), /non-empty array of/);
- assert.throws(() => driveAlongLegs(rig, [{ path: REVERSING_LEGS[0].path, direction: 'sideways' }], { speed: 1 }), /direction must be/);
- assert.throws(() => createVehicleRig({ parts: [{ name: 'Wheel_FL', matrix: mat4.create() }], lights: { tailLights: [{ part: 0, signal: 'fog' }] } }), /at least two wheels|signal/);
+ assert.throws(() => driveAlongLegs(rig, [{ path: REVERSING_LEGS[0].path, direction: 'sideways' }], { speed: 1 }), /^RangeError: legs\[0\]\.direction: got "sideways"; expected one of forward, reverse/);
+ assert.throws(() => createVehicleRig({ parts: [{ name: 'Wheel_FL', matrix: mat4.create() }], lights: { tailLights: [{ part: 0, signal: 'fog' }] } }), /wheels: got 1; expected at least 2 wheels|signal/);
});
diff --git a/tests/vehicle.test.js b/tests/vehicle.test.js
index 45cecddc..da3c7832 100644
--- a/tests/vehicle.test.js
+++ b/tests/vehicle.test.js
@@ -332,20 +332,20 @@ test('bad input produces specific errors', () => {
const { body, wheels, parts } = createTestVehicleParts();
const wheelSpecs = wheels.map(part => ({ part }));
assert.throws(() => createVehicleRig({}), /exactly one of parts, graph or asset/);
- assert.throws(() => createVehicleRig({ parts, wheels: [wheelSpecs[0]] }), /at least two wheels/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [wheelSpecs[0]] }), /^RangeError: wheels: got 1; expected at least 2 wheels, such as/);
assert.throws(() => createVehicleRig({ parts, wheels: wheelSpecs, forwardAxis: '+y' }), /forwardAxis/);
- assert.throws(() => createVehicleRig({ parts, wheels: [{ part: 'Nothing' }, wheelSpecs[0]] }), /was not found: Nothing/);
- assert.throws(() => createVehicleRig({ parts, wheels: [{ part: wheels[0], radius: -1, center: [0, 0, 0] }, wheelSpecs[1]] }), /radius must be positive/);
- assert.throws(() => createVehicleRig({ parts: [body, { name: 'W1', matrix: mat4.create() }, { name: 'W2', matrix: mat4.create() }], wheels: [{ part: 'W1' }, { part: 'W2' }] }), /needs a radius and center/);
- assert.throws(() => createVehicleRig({ parts, wheels: wheelSpecs, body: [] }), /body must be a non-empty array/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [{ part: 'Nothing' }, wheelSpecs[0]] }), /^RangeError: wheels\[0\]\.node: got "Nothing"; expected the name of a part in the asset, such as/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [{ part: wheels[0], radius: -1, center: [0, 0, 0] }, wheelSpecs[1]] }), /^RangeError: wheels\[0\]\.radius: got -1; expected a finite number above 0, such as 0\.35/);
+ assert.throws(() => createVehicleRig({ parts: [body, { name: 'W1', matrix: mat4.create() }, { name: 'W2', matrix: mat4.create() }], wheels: [{ part: 'W1' }, { part: 'W2' }] }), /^RangeError: wheels.0.[.]radius: got undefined; expected a radius with a center, or geometry to measure them from, such as 0.35/);
+ assert.throws(() => createVehicleRig({ parts, wheels: wheelSpecs, body: [] }), /^TypeError: body: got \[\]; expected a non-empty array of parts or nodes, such as/);
const { rig } = createTestRig();
assert.throws(() => driveAlongPath({}, STRAIGHT_PATH, { speed: 3 }), /needs a rig/);
- assert.throws(() => driveAlongPath(rig, [[0, 0, 0]], { speed: 3 }), /at least two distinct points/);
- assert.throws(() => driveAlongPath(rig, [[0, 0, 0], [0, 0, NaN]], { speed: 3 }), /Path point 1/);
- assert.throws(() => driveAlongPath(rig, 'road', { speed: 3 }), /Path must be/);
+ assert.throws(() => driveAlongPath(rig, [[0, 0, 0]], { speed: 3 }), /^RangeError: path: got "1 distinct point"; expected at least 2 distinct points, such as/);
+ assert.throws(() => driveAlongPath(rig, [[0, 0, 0], [0, 0, NaN]], { speed: 3 }), /^TypeError: path\[1\]: got \[0,0,null\]; expected an array of 3 finite numbers, such as/);
+ assert.throws(() => driveAlongPath(rig, 'road', { speed: 3 }), /^TypeError: path: got "road"; expected an array of \[x, y, z\] points, such as/);
assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, {}), /exactly one of speed/);
assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, cruiseSpeed: 4 }), /exactly one of speed/);
- assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: -3 }), /speed must be positive/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: -3 }), /^RangeError: speed: got -3; expected a finite number above 0, such as 8/);
assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, groundHeight: 4 }), /groundHeight must be a function/);
const drive = driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, groundHeight: () => NaN });
assert.throws(() => drive.sample(1), /groundHeight must return a finite number/);