Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add seven motion constraints: copy_transforms, limit_distance, limit_scale, stretch_to, locked_track, transformation, action (#595)

Nguyen Xuan An4c07336f25ec
diff --git a/changes/595-more-constraints.md b/changes/595-more-constraints.md
new file mode 100644
index 00000000..26d10eef
--- /dev/null
+++ b/changes/595-more-constraints.md
@@ -0,0 +1 @@
+- motion.constraints: adds copy_transforms, limit_distance, limit_scale, stretch_to, locked_track, transformation and action, each one scene_motion call (#595)
diff --git a/changes/595-more-constraints.size.md b/changes/595-more-constraints.size.md
new file mode 100644
index 00000000..8756a8df
--- /dev/null
+++ b/changes/595-more-constraints.size.md
@@ -0,0 +1,2 @@
+- scene:agent-scene+lazy: seven constraint operators and their validation load only with motion, each a few hundred bytes of the 1.6 KB (#595)
+- tool:scene_motion: one constraint entry names the seven new types and their optional fields, so strict-mode clients see them (#595)
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index f7db7666..9f5136fe 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -277,8 +277,15 @@ own transform under its parent.
| `child_of` | `target`, `inverse` (`rest` or `none`) | The node follows the target: its world matrix becomes target * inverse * its own. `rest` uses the inverse of the target's rest matrix, so the node stays put until the target moves; Blender's default is `none` |
| `floor` | `target`, `axis` (default `+y`), `offset` | Keep the node on the positive side of the plane through the target, along `axis`, plus `offset` |
-Not covered yet: `use_*` switches on `child_of`, `limit_scale`, `copy_transforms`, `damped_track`, `locked_track`,
-`stretch_to`, bone sub-targets and `head_tail`.
+| `copy_transforms` | `target` | The node's world matrix becomes the target's |
+| `limit_distance` | `target`, `distance`, `mode` (`inside` default, `outside`, `surface`) | Keep the node's world position inside, outside or on the sphere of that radius around the target |
+| `limit_scale` | `x`, `y`, `z` as `[min, max]` above 0, `space` | Clamp the scale per axis |
+| `stretch_to` | `target`, `restLength` (default: the rest distance), `volume` (`xz` default, `x`, `z`, `none`), `bulge` (0 to 4, default 1), `worldUp` | Aim +y at the target, scale y by distance over `restLength` and x and z by that ratio to the power of minus `bulge` (its square root for `xz`). Z leans toward `worldUp` |
+| `locked_track` | `target`, `trackAxis` (default `+y`), `lockAxis` (default `z`) | Turn only about the node's own lock axis so the track axis points toward the target |
+| `transformation` | `target`, `source`, `destination` (`translation`, `rotation` or `scale`), `map` (the source axis for each destination x, y, z), `fromMin`, `fromMax` (per source axis), `toMin`, `toMax` (per destination axis), `space` | The target's channel, clamped to its range, sets the node's channel over its range. Rotation is Euler degrees |
+| `action` | `target`, `source`, `axis`, `min`, `max`, `destination`, `keys` (2 to 16 of `{ at, value }`, `at` 0 to 1 rising), `space` | Read the curve where the target's channel sits between `min` and `max`; its value sets the node's channel |
+
+Not covered yet: `use_*` switches on `child_of`, `damped_track`, bone sub-targets and `head_tail`.
## Drivers
diff --git a/docs/parity.md b/docs/parity.md
index 9f677156..a65ef51a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -144,22 +144,22 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Constraints > Transform > Copy Location Constraint | partial | `copy_location` in `motion.constraints`: axes, invert, offset, world or local space, influence. Matches Blender where tested. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js), [src/expression.js](../src/expression.js) | #58, #98 |
| Animation & Rigging > Constraints > Transform > Copy Rotation Constraint | partial | `copy_rotation`: Euler axes, invert, replace or add, world or local. World matrices match Blender 5.2 in 2 cases. | [blender-constraints](../tests/blender-constraints.test.js) | #58 |
| Animation & Rigging > Constraints > Transform > Copy Scale Constraint | partial | `copy_scale`: axes and offset, world or local. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |
-| Animation & Rigging > Constraints > Transform > Copy Transforms Constraint | missing | No constraint. | | #58 |
-| Animation & Rigging > Constraints > Transform > Limit Distance Constraint | missing | No constraint. | | #58 |
+| Animation & Rigging > Constraints > Transform > Copy Transforms Constraint | partial | `copy_transforms`: the node takes the target world matrix; influence blends it. No mix modes. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
+| Animation & Rigging > Constraints > Transform > Limit Distance Constraint | partial | `limit_distance`: `distance` and `mode` inside, outside or surface, from the target origin. The distance is required, not set from the first frame. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Transform > Limit Location Constraint | partial | `limit_location`: per-axis clamp, world or local. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |
| Animation & Rigging > Constraints > Transform > Limit Rotation Constraint | partial | `limit_rotation` constraint and per-axis `limits` on two-bone IK joints, reported in `motionIk`. Matches Blender 5.2. | [blender-constraints](../tests/blender-constraints.test.js), [skeleton-pose-limits](../tests/skeleton-pose-limits.test.js) | #58 |
-| Animation & Rigging > Constraints > Transform > Limit Scale Constraint | missing | No constraint. | | #58 |
+| Animation & Rigging > Constraints > Transform > Limit Scale Constraint | partial | `limit_scale`: per-axis clamp, world or local; the minimum must be above 0. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Transform > Maintain Volume Constraint | missing | No constraint. | | |
-| Animation & Rigging > Constraints > Transform > Transformation Constraint | missing | No constraint. | | |
+| Animation & Rigging > Constraints > Transform > Transformation Constraint | partial | `transformation`: maps a target translation, rotation or scale range onto the node, per axis, clamped. Replace only, no add or multiply. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Transform > Transform Cache Constraint | missing | No constraint. | | |
| Animation & Rigging > Constraints > Tracking > Clamp To Constraint | missing | No constraint. | | |
| Animation & Rigging > Constraints > Tracking > Damped Track Constraint | partial | Aim IK turns one joint toward a target. It is not a general constraint. | [agent-motion-ik](../tests/agent-motion-ik.test.js) | #58 |
| Animation & Rigging > Constraints > Tracking > Inverse Kinematics Constraint | partial | Two-bone and aim IK, in code and in `motion.ik`, with joint limits and sanity warnings on two-bone. There are no longer chains. | [agent-motion-ik](../tests/agent-motion-ik.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58 |
-| Animation & Rigging > Constraints > Tracking > Locked Track Constraint | missing | No constraint. | | |
+| Animation & Rigging > Constraints > Tracking > Locked Track Constraint | partial | `locked_track`: turns only about the node's own lock axis so the track axis aims at the target as near as it can. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Tracking > Spline IK Constraint | missing | No constraint. | | |
-| Animation & Rigging > Constraints > Tracking > Stretch To Constraint | missing | No constraint. | | |
+| Animation & Rigging > Constraints > Tracking > Stretch To Constraint | partial | `stretch_to`: aims +y and stretches it to the distance over `restLength`; `volume` and `bulge` keep volume on x and z. The up axis is fixed to z leaning toward `worldUp`. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Tracking > Track To Constraint | partial | `track_to` on nodes: track and up axes, `worldUp`. Matches Blender 5.2 in 2 cases. Cameras still use camera paths. | [blender-constraints](../tests/blender-constraints.test.js), [camera-path](../tests/camera-path.test.js) | #58 |
-| Animation & Rigging > Constraints > Relationship > Action Constraint | missing | No constraint. | | |
+| Animation & Rigging > Constraints > Relationship > Action Constraint | partial | `action`: a keyed curve of up to 16 keys, read where a target channel sits between `min` and `max`, sets the node translation, rotation or scale. No stored actions or frame ranges. | [agent-motion-constraints-more](../tests/agent-motion-constraints-more.test.js) | #595 |
| Animation & Rigging > Constraints > Relationship > Armature Constraint | missing | No constraint. | | |
| Animation & Rigging > Constraints > Relationship > Child Of Constraint | partial | `child_of` in `motion.constraints`: follows a moving target from its rest inverse (or none), with an influence that can be animated by an expression. Matches Blender 5.2 in 2 cases. No per-channel switches. | [blender-constraints](../tests/blender-constraints.test.js), [scene-graph](../tests/scene-graph.test.js) | #58 |
| Animation & Rigging > Constraints > Relationship > Floor Constraint | partial | `floor`: keeps a node on one side of a plane through the target, axis and offset. Matches Blender 5.2 for the Z floor with an offset; no `use_rotation`. | [blender-constraints](../tests/blender-constraints.test.js) | #58 |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 7eb3f03d..fb77c03b 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -477,6 +477,8 @@ const axisName = z.enum(['x', 'y', 'z']);
const axisNames = z.array(axisName).min(1).max(3);
const signedAxis = z.enum(['+x', '-x', '+y', '-y', '+z', '-z']);
const constraintSpace = z.enum(['world', 'local']).optional();
+const constraintChannel = z.enum(['translation', 'rotation', 'scale']).optional();
+const number1e6 = z.number().min(-1e6).max(1e6);
const limitRange = z.tuple([z.number().min(-1e6).max(1e6), z.number().min(-1e6).max(1e6)]).optional();
// A bounded expression: data only, never code. See docs/agent-motion.md for the operators.
const expression = z.lazy(() => z.union([
@@ -495,6 +497,16 @@ const constraint = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('track_to'), node: identifier, target: identifier, trackAxis: signedAxis.optional(), upAxis: axisName.optional(), worldUp: vector3.optional(), influence }),
z.strictObject({ type: z.literal('child_of'), node: identifier, target: identifier, inverse: z.enum(['rest', 'none']).optional(), influence }),
z.strictObject({ type: z.literal('floor'), node: identifier, target: identifier, axis: signedAxis.optional(), offset: z.number().min(-1e6).max(1e6).optional(), influence }),
+ // One entry for the seven newer types; the motion validator checks which fields each one needs.
+ z.strictObject({
+ type: z.enum(['copy_transforms', 'limit_distance', 'limit_scale', 'stretch_to', 'locked_track', 'transformation', 'action']), node: identifier, target: identifier.optional(), influence,
+ distance: number1e6.optional(), mode: z.enum(['inside', 'outside', 'surface']).optional(), x: limitRange, y: limitRange, z: limitRange, space: constraintSpace,
+ restLength: number1e6.optional(), volume: z.enum(['xz', 'x', 'z', 'none']).optional(), bulge: z.number().min(0).max(4).optional(), worldUp: vector3.optional(),
+ trackAxis: signedAxis.optional(), lockAxis: axisName.optional(), axis: axisName.optional(),
+ source: constraintChannel, destination: constraintChannel, map: z.array(axisName).length(3).optional(),
+ fromMin: vector3.optional(), fromMax: vector3.optional(), toMin: vector3.optional(), toMax: vector3.optional(),
+ min: number1e6.optional(), max: number1e6.optional(), keys: z.array(z.strictObject({ at: unit, value: vector3 })).min(2).max(16).optional(),
+ }),
]);
const driver = z.strictObject({
target: z.union([
@@ -528,7 +540,7 @@ const ikSolver = z.discriminatedUnion('type', [
const motion = z.strictObject({
duration: z.number().min(0.1).max(30),
ik: z.array(ikSolver).max(16).optional().describe('Inverse kinematics run after the tracks and any selected clip, in order, on recipes and imported assets. IDs are recipe node IDs or an asset\'s node-N IDs; find them with scene_inspect kind hierarchy. scene_inspect reports motionIk: whether each solver reaches its target across the clip.'),
- constraints: z.array(constraint).max(32).optional().describe('Blender-style node constraints, run in order after the tracks, drivers and IK, each on the pose the one before left: copy_location, copy_rotation, copy_scale, limit_location, limit_rotation, track_to, child_of, floor. Euler angles are XYZ in degrees; space defaults to world. Same result at any time, so seeking equals playing.'),
+ constraints: z.array(constraint).max(32).optional().describe('Blender-style node constraints, run in order after the tracks, drivers and IK, each on the pose the one before left: copy_location, copy_rotation, copy_scale, limit_location, limit_rotation, track_to, child_of, floor, and more (scene_capabilities). Euler angles are XYZ in degrees; space defaults to world. Same result at any time, so seeking equals playing.'),
drivers: z.array(driver).max(32).optional().describe('Drive one node component or material property from a bounded expression over time and other nodes\' values. A driven property cannot also have a track.'),
loop: z.boolean().optional(),
tracks: z.array(z.union([
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 707d8f66..c1de8614 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -259,10 +259,10 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
align: 'to, axis, at (min, center, max), offset: anchor on one axis',
centered: 'to, axes (default x, y, z): centre on those axes',
}),
- notes: 'Optional region (a mesh tag) uses only those faces of the target. One relation per axis, no loops, mesh nodes only. A relation replaces translation on its axes. set-node with relations [] removes them.',
+ notes: 'Region (mesh tag): target faces only. One relation per axis, no loops, mesh nodes only. A relation sets translation on its axes. set-node with relations [] removes them.',
}),
rigging: Object.freeze({ presets: Object.freeze(['humanoid', 'quadruped']), maxArmatures: 16, maxBones: 128, maxInfluences: 4, weights: 'bone-distance' }),
- motionConstraints: Object.freeze(['copy_location', 'copy_rotation', 'copy_scale', 'limit_location', 'limit_rotation', 'track_to', 'child_of', 'floor']),
+ motionConstraints: Object.freeze(['copy_location', 'copy_rotation', 'copy_scale', 'limit_location', 'limit_rotation', 'track_to', 'child_of', 'floor', 'copy_transforms', 'limit_distance', 'limit_scale', 'stretch_to', 'locked_track', 'transformation', 'action']),
motionDrivers: Object.freeze({ maxDrivers: 32, maxConstraints: 32, maxExpressionParts: 64, maxExpressionDepth: 8 }),
// Recipe physics: Rapier (an optional peer) bakes bodies on nodes offline; playback is a seek into the bake.
physics: Object.freeze({
@@ -277,7 +277,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
cloth: Object.freeze({
sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',
defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),
- notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes with no motion track or physics body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude } (a capsule per bone). Sheet pinGroup names a vertex group of the sheet mesh whose vertices (weight 0.5 or more) are held, with or without pin. Sheet pinTo { node, weight } rides the pinned edges on a node. No self collision.',
+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup names a sheet vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. No self collision.',
limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxMovingColliders: 64, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),
}),
// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.
@@ -285,7 +285,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
emitter: 'System node keeps its geometry as the particle shape (keep it low-poly); node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y where particles land and rest).',
hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Triangular tapering tubes, no UVs.',
sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction)',
- notes: 'A particle is a pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision, combing or clumping. Report: maxAlive and endsAt per system.',
+ notes: 'A particle is a pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision, combing or clumping. Report: maxAlive, endsAt.',
limits: Object.freeze({ maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: 100000, maxLifetime: 60 }),
}),
// Recipe bake: bounced light written into lightmaps at build time (src/light-bake.js, loaded on demand).
diff --git a/src/node-constraints.js b/src/node-constraints.js
index 1c8d55a1..a8cb701a 100644
--- a/src/node-constraints.js
+++ b/src/node-constraints.js
@@ -1,4 +1,4 @@
-import { mat4, quat, vec3 } from 'gl-matrix';
+import { mat3, mat4, quat, vec3 } from 'gl-matrix';
import { compileMotionExpression } from './motion-expression.js';
import { bounded, denseArray, knownKeys, valueFrom } from './motion-validation.js';
import { eulerFromQuaternion, quaternionFromEuler } from './rotation-euler.js';
@@ -32,7 +32,16 @@ const CONSTRAINT_FIELDS = {
track_to: ['target', 'trackAxis', 'upAxis', 'worldUp'],
child_of: ['target', 'inverse'],
floor: ['target', 'axis', 'offset'],
+ copy_transforms: ['target'],
+ limit_distance: ['target', 'distance', 'mode'],
+ limit_scale: ['x', 'y', 'z', 'space'],
+ stretch_to: ['target', 'restLength', 'volume', 'bulge', 'worldUp'],
+ locked_track: ['target', 'trackAxis', 'lockAxis'],
+ transformation: ['target', 'source', 'destination', 'map', 'fromMin', 'fromMax', 'toMin', 'toMax', 'space'],
+ action: ['target', 'source', 'axis', 'min', 'max', 'destination', 'keys', 'space'],
};
+const PROPERTIES = ['translation', 'rotation', 'scale'];
+const MAX_ACTION_KEYS = 16;
export const CONSTRAINT_TYPES = Object.freeze(Object.keys(CONSTRAINT_FIELDS));
// ---------------------------------------------------------------------------------------------------------------
@@ -120,13 +129,73 @@ function normalizeConstraint(input, position, movableIds, visibleIds) {
case 'child_of':
result.inverse = oneOf(input.inverse, ['rest', 'none'], 'rest', `${label} inverse`);
break;
- default:
+ case 'floor':
result.axis = oneOf(input.axis, SIGNED_AXES, '+y', `${label} axis`);
result.offset = input.offset === undefined ? 0 : bounded(input.offset, -MAX_COORDINATE, MAX_COORDINATE, `${label} offset`);
+ break;
+ default:
+ normalizeExtraConstraint(input, result, label);
}
return result;
}
+function normalizeExtraConstraint(input, result, label) {
+ switch (input.type) {
+ case 'copy_transforms':
+ break;
+ case 'limit_distance':
+ result.distance = bounded(input.distance, 0, MAX_COORDINATE, `${label} distance`);
+ result.mode = oneOf(input.mode, ['inside', 'outside', 'surface'], 'inside', `${label} mode`);
+ break;
+ case 'limit_scale':
+ Object.assign(result, axisRanges(input, MAX_COORDINATE, label));
+ for (const axis of AXES) {
+ if (result[axis] && !(result[axis][0] > 0)) throw new RangeError(`${label} ${axis} minimum must be above 0.`);
+ }
+ break;
+ case 'stretch_to':
+ result.restLength = input.restLength === undefined ? 0 : bounded(input.restLength, 0, MAX_COORDINATE, `${label} restLength`);
+ result.volume = oneOf(input.volume, ['xz', 'x', 'z', 'none'], 'xz', `${label} volume`);
+ result.bulge = input.bulge === undefined ? 1 : bounded(input.bulge, 0, 4, `${label} bulge`);
+ result.worldUp = input.worldUp === undefined ? [0, 1, 0] : valueFrom(input.worldUp, 3, `${label} worldUp`);
+ if (vec3.length(result.worldUp) < NEAR_ZERO) throw new RangeError(`${label} worldUp cannot be zero.`);
+ break;
+ case 'locked_track':
+ result.trackAxis = oneOf(input.trackAxis, SIGNED_AXES, '+y', `${label} trackAxis`);
+ result.lockAxis = oneOf(input.lockAxis, AXES, 'z', `${label} lockAxis`);
+ if (result.trackAxis.slice(1) === result.lockAxis) throw new RangeError(`${label} trackAxis and lockAxis must be different axes.`);
+ break;
+ case 'transformation':
+ result.source = oneOf(input.source, PROPERTIES, 'translation', `${label} source`);
+ result.destination = oneOf(input.destination, PROPERTIES, 'translation', `${label} destination`);
+ result.map = input.map === undefined ? [...AXES] : denseArray(input.map, 3, `${label} map`);
+ if (result.map.length !== 3 || result.map.some(axis => !AXES.includes(axis))) throw new RangeError(`${label} map needs three axes from x, y and z, one per destination axis.`);
+ for (const [field, fallback] of [['fromMin', 0], ['fromMax', 1], ['toMin', 0], ['toMax', 1]]) {
+ result[field] = input[field] === undefined ? [fallback, fallback, fallback] : valueFrom(input[field], 3, `${label} ${field}`);
+ }
+ if (result.fromMin.some((value, index) => value === result.fromMax[index])) throw new RangeError(`${label} fromMax must differ from fromMin on every axis.`);
+ break;
+ default:
+ normalizeActionConstraint(input, result, label);
+ }
+}
+
+function normalizeActionConstraint(input, result, label) {
+ result.source = oneOf(input.source, PROPERTIES, 'translation', `${label} source`);
+ result.destination = oneOf(input.destination, PROPERTIES, 'translation', `${label} destination`);
+ result.axis = oneOf(input.axis, AXES, 'x', `${label} axis`);
+ result.min = bounded(input.min, -MAX_COORDINATE, MAX_COORDINATE, `${label} min`);
+ result.max = bounded(input.max, -MAX_COORDINATE, MAX_COORDINATE, `${label} max`);
+ if (!(result.min < result.max)) throw new RangeError(`${label} min must be below max.`);
+ denseArray(input.keys, MAX_ACTION_KEYS, `${label} keys`);
+ if (input.keys.length < 2) throw new RangeError(`${label} keys needs at least 2 keys.`);
+ result.keys = input.keys.map((key, index) => {
+ knownKeys(key, ['at', 'value'], `${label} key ${index}`);
+ return { at: bounded(key.at, 0, 1, `${label} key ${index} at`), value: valueFrom(key.value, 3, `${label} key ${index} value`) };
+ });
+ if (result.keys.some((key, index) => index && key.at <= result.keys[index - 1].at)) throw new RangeError(`${label} keys must have rising at values.`);
+}
+
/** Validate a constraint list against the node IDs a motion may move and the ones it may read. Returns plain data. */
export function normalizeConstraints(input, movableIds, visibleIds) {
denseArray(input, MAX_CONSTRAINTS, 'Motion constraints');
@@ -256,9 +325,56 @@ function limitRotation(owner, target, constraint) {
quaternionFromEuler(owner.rotation, angles[0], angles[1], angles[2]);
}
+function limitScale(owner, target, constraint) {
+ for (const axis of AXES) {
+ if (!constraint[axis]) continue;
+ const index = axisIndex(axis);
+ owner.scale[index] = Math.min(constraint[axis][1], Math.max(constraint[axis][0], owner.scale[index]));
+ }
+}
+
+/** A frame's translation, scale or Euler rotation (degrees) as three numbers. */
+function channelOf(frame, property) {
+ return property === 'rotation' ? eulerFromQuaternion(frame.rotation).map(radians => radians / TO_RADIANS) : Array.from(frame[property]);
+}
+
+function writeChannel(frame, property, values) {
+ if (property === 'rotation') {
+ const [x, y, z] = values.map(degrees => degrees * TO_RADIANS);
+ quaternionFromEuler(frame.rotation, x, y, z);
+ } else {
+ frame[property].set(values);
+ }
+}
+
+function transformation(owner, target, constraint) {
+ const source = channelOf(target, constraint.source);
+ const result = channelOf(owner, constraint.destination);
+ constraint.map.forEach((sourceAxis, index) => {
+ const from = axisIndex(sourceAxis);
+ const fraction = (source[from] - constraint.fromMin[from]) / (constraint.fromMax[from] - constraint.fromMin[from]);
+ const clamped = Math.min(1, Math.max(0, fraction));
+ result[index] = constraint.toMin[index] + clamped * (constraint.toMax[index] - constraint.toMin[index]);
+ });
+ writeChannel(owner, constraint.destination, result);
+}
+
+/** The owner's channel follows a keyed curve, read where the target's channel sits between min and max. */
+function action(owner, target, constraint) {
+ const value = channelOf(target, constraint.source)[axisIndex(constraint.axis)];
+ const at = Math.min(1, Math.max(0, (value - constraint.min) / (constraint.max - constraint.min)));
+ const { keys } = constraint;
+ const found = keys.findIndex(key => key.at >= at);
+ const next = found < 0 ? keys.length - 1 : Math.max(1, found);
+ const previous = keys[next - 1];
+ const following = keys[next];
+ const fraction = Math.min(1, Math.max(0, (at - previous.at) / (following.at - previous.at)));
+ writeChannel(owner, constraint.destination, previous.value.map((from, index) => from + fraction * (following.value[index] - from)));
+}
+
const FRAME_CONSTRAINTS = {
copy_location: copyLocation, copy_rotation: copyRotation, copy_scale: copyScale,
- limit_location: limitLocation, limit_rotation: limitRotation,
+ limit_location: limitLocation, limit_rotation: limitRotation, limit_scale: limitScale, transformation, action,
};
function perpendicularTo(direction) {
@@ -287,6 +403,51 @@ function trackTo(ownerWorld, targetWorld, constraint) {
return compose(frame);
}
+function limitDistance(ownerWorld, targetWorld, constraint) {
+ const center = mat4.getTranslation(new Float64Array(3), targetWorld);
+ const offset = vec3.subtract(new Float64Array(3), mat4.getTranslation(new Float64Array(3), ownerWorld), center);
+ const distance = vec3.length(offset);
+ const outside = constraint.mode === 'outside';
+ const inside = constraint.mode === 'inside';
+ if (distance < NEAR_ZERO || (inside && distance <= constraint.distance) || (outside && distance >= constraint.distance)) return ownerWorld;
+ const moved = mat4.clone(ownerWorld);
+ vec3.scaleAndAdd(offset, center, offset, constraint.distance / distance);
+ moved.set(offset, 12);
+ return moved;
+}
+
+/** Aim the track axis at the target as far as turning about the owner's own lock axis allows. */
+function lockedTrack(ownerWorld, targetWorld, constraint) {
+ const frame = decompose(ownerWorld);
+ const rotation = mat3.fromQuat(new Float64Array(9), frame.rotation);
+ const columnOf = axis => Array.from(rotation.slice(axisIndex(axis) * 3, axisIndex(axis) * 3 + 3));
+ const lock = columnOf(constraint.lockAxis);
+ const track = columnOf(constraint.trackAxis).map(component => component * signOf(constraint.trackAxis));
+ const wanted = vec3.subtract(new Float64Array(3), mat4.getTranslation(new Float64Array(3), targetWorld), frame.translation);
+ vec3.scaleAndAdd(wanted, wanted, lock, -vec3.dot(wanted, lock));
+ if (vec3.length(wanted) < NEAR_ZERO) return ownerWorld;
+ vec3.normalize(wanted, wanted);
+ const angle = Math.atan2(vec3.dot(lock, vec3.cross(new Float64Array(3), track, wanted)), vec3.dot(track, wanted));
+ const turn = quat.setAxisAngle(new Float64Array(4), lock, angle);
+ frame.rotation = quat.normalize(new Float64Array(4), quat.multiply(new Float64Array(4), turn, frame.rotation));
+ return compose(frame);
+}
+
+/** Aim +y at the target and stretch it to the distance; x and z swell or thin to keep volume as `volume` says. */
+function stretchTo(ownerWorld, targetWorld, constraint, restLength) {
+ const aimed = trackTo(ownerWorld, targetWorld, { trackAxis: '+y', upAxis: 'z', worldUp: constraint.worldUp });
+ const distance = vec3.distance(mat4.getTranslation(new Float64Array(3), ownerWorld), mat4.getTranslation(new Float64Array(3), targetWorld));
+ if (aimed === ownerWorld || !(restLength > 0)) return aimed;
+ const frame = decompose(aimed);
+ const ratio = distance / restLength;
+ const swell = ratio ** -constraint.bulge;
+ const side = constraint.volume === 'xz' ? Math.sqrt(swell) : swell;
+ frame.scale[1] *= ratio;
+ if (constraint.volume !== 'none' && constraint.volume !== 'z') frame.scale[0] *= side;
+ if (constraint.volume !== 'none' && constraint.volume !== 'x') frame.scale[2] *= side;
+ return compose(frame);
+}
+
function floorConstraint(ownerWorld, targetWorld, constraint) {
const normal = new Float64Array(3);
normal[axisIndex(constraint.axis)] = signOf(constraint.axis);
@@ -413,6 +574,15 @@ export function createNodeConstraintEvaluator({ hierarchy, rootMatrix, constrain
result = trackTo(ownerWorld, worlds[targetIndex], constraint);
} else if (constraint.type === 'floor') {
result = floorConstraint(ownerWorld, worlds[targetIndex], constraint);
+ } else if (constraint.type === 'copy_transforms') {
+ result = worlds[targetIndex];
+ } else if (constraint.type === 'limit_distance') {
+ result = limitDistance(ownerWorld, worlds[targetIndex], constraint);
+ } else if (constraint.type === 'locked_track') {
+ result = lockedTrack(ownerWorld, worlds[targetIndex], constraint);
+ } else if (constraint.type === 'stretch_to') {
+ const restLength = constraint.restLength || vec3.distance(mat4.getTranslation(new Float64Array(3), restWorlds[ownerIndex]), mat4.getTranslation(new Float64Array(3), restWorlds[targetIndex]));
+ result = stretchTo(ownerWorld, worlds[targetIndex], constraint, restLength);
} else {
const inverse = constraint.inverse === 'rest' ? mat4.invert(new Float64Array(16), restWorlds[targetIndex]) : mat4.create();
const parent = mat4.multiply(new Float64Array(16), worlds[targetIndex], inverse);
diff --git a/tests/agent-motion-constraints-more.test.js b/tests/agent-motion-constraints-more.test.js
new file mode 100644
index 00000000..fb60aff6
--- /dev/null
+++ b/tests/agent-motion-constraints-more.test.js
@@ -0,0 +1,119 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat4 } from 'gl-matrix';
+import { createAgentScene } from '../src/agent-scene.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+import { CONSTRAINT_TYPES } from '../src/node-constraints.js';
+import { eulerFromQuaternion, quaternionFromEuler } from '../src/rotation-euler.js';
+
+// Each case builds an owner and a target, then compares the owner's world matrix with a pose worked out by hand.
+
+const DEGREES = Math.PI / 180;
+
+function sampled(nodes, constraint) {
+ const scene = createAgentScene({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.6, 0.6, 0.6] }],
+ nodes: nodes.map(node => ({ geometry: 'box', material: 'paint', ...node })),
+ motion: { duration: 1, tracks: [], constraints: [{ node: 'owner', ...constraint }] },
+ });
+ scene.sampleMotion(0);
+ return scene.parts.find(part => part.name === 'owner').matrix;
+}
+
+function assertClose(actual, expected, label, tolerance = 1e-4) {
+ expected.forEach((value, index) => {
+ assert.ok(Math.abs(actual[index] - value) <= tolerance, `${label}: ${JSON.stringify(Array.from(actual))} vs ${JSON.stringify(expected)}`);
+ });
+}
+
+const translationOf = matrix => Array.from(mat4.getTranslation(new Float64Array(3), matrix));
+const column = (matrix, index) => Array.from(matrix.slice(index * 4, index * 4 + 3));
+const eulerDegrees = matrix => eulerFromQuaternion(mat4.getRotation(new Float64Array(4), matrix)).map(radians => radians / DEGREES);
+const owner = { id: 'owner' };
+const targetAt = translation => ({ id: 'target', translation });
+
+test('copy_transforms gives the owner the target world matrix', () => {
+ const rotation = Array.from(quaternionFromEuler(new Float64Array(4), 20 * DEGREES, 30 * DEGREES, 40 * DEGREES));
+ const target = { id: 'target', translation: [1, 2, 3], rotation, scale: [2, 3, 4] };
+ const matrix = sampled([owner, target], { type: 'copy_transforms', target: 'target' });
+ const expected = mat4.fromRotationTranslationScale(new Float64Array(16), rotation, [1, 2, 3], [2, 3, 4]);
+ assertClose(matrix, Array.from(expected), 'copy_transforms');
+});
+
+test('limit_distance pulls a far owner onto the sphere, keeping its direction', () => {
+ const matrix = sampled([{ ...owner, translation: [6, 8, 0] }, targetAt([0, 0, 0])], { type: 'limit_distance', target: 'target', distance: 5 });
+ assertClose(translationOf(matrix), [3, 4, 0], 'inside, far owner');
+});
+
+test('limit_distance inside leaves a near owner, outside pushes it out and surface does both', () => {
+ const near = [{ ...owner, translation: [0.6, 0.8, 0] }, targetAt([0, 0, 0])];
+ assertClose(translationOf(sampled(near, { type: 'limit_distance', target: 'target', distance: 5 })), [0.6, 0.8, 0], 'inside, near owner');
+ assertClose(translationOf(sampled(near, { type: 'limit_distance', target: 'target', distance: 5, mode: 'outside' })), [3, 4, 0], 'outside');
+ assertClose(translationOf(sampled(near, { type: 'limit_distance', target: 'target', distance: 5, mode: 'surface' })), [3, 4, 0], 'surface');
+});
+
+test('limit_scale clamps each ranged axis and leaves the others', () => {
+ const matrix = sampled([{ ...owner, scale: [5, 0.1, 2] }], { type: 'limit_scale', x: [1, 3], y: [0.5, 2] });
+ assertClose([column(matrix, 0)[0], column(matrix, 1)[1], column(matrix, 2)[2]], [3, 0.5, 2], 'scale');
+});
+
+test('stretch_to aims +y at the target and keeps volume with x and z', () => {
+ const matrix = sampled([owner, targetAt([0, 0, 4])], { type: 'stretch_to', target: 'target', restLength: 2 });
+ const thin = Math.sqrt(0.5);
+ assertClose(column(matrix, 0), [-thin, 0, 0], 'x column');
+ assertClose(column(matrix, 1), [0, 0, 2], 'y column stretched to 4 over rest 2');
+ assertClose(column(matrix, 2), [0, thin, 0], 'z column');
+});
+
+test('stretch_to takes its rest length from the rest pose, and volume none leaves x and z alone', () => {
+ const matrix = sampled([owner, targetAt([0, 0, 2])], { type: 'stretch_to', target: 'target', volume: 'none' });
+ assertClose(column(matrix, 1), [0, 0, 1], 'unstretched at rest');
+ assertClose(column(matrix, 0), [-1, 0, 0], 'x column');
+});
+
+test('locked_track turns only about the lock axis', () => {
+ const matrix = sampled([owner, targetAt([3, 0, 5])], { type: 'locked_track', target: 'target' });
+ assertClose(column(matrix, 1), [1, 0, 0], 'track axis y points along x, the target seen from the lock plane');
+ assertClose(column(matrix, 2), [0, 0, 1], 'lock axis z does not move');
+ assertClose(eulerDegrees(matrix), [0, 0, -90], 'euler');
+});
+
+test('transformation maps a clamped target channel range onto the owner', () => {
+ const asRotation = sampled([owner, targetAt([5, 0, 0])], {
+ type: 'transformation', target: 'target', destination: 'rotation', map: ['x', 'y', 'x'], fromMax: [10, 10, 10], toMax: [90, 90, 180],
+ });
+ assertClose(eulerDegrees(asRotation), [45, 0, 90], 'half way along x');
+ const clamped = sampled([owner, targetAt([20, 0, 0])], {
+ type: 'transformation', target: 'target', fromMax: [10, 10, 10], toMax: [1, 2, 3], map: ['x', 'y', 'x'],
+ });
+ assertClose(translationOf(clamped), [1, 0, 3], 'clamped to the top of the range');
+});
+
+test('action reads a keyed curve at the target channel position', () => {
+ const action = { type: 'action', target: 'target', max: 10, min: 0, keys: [{ at: 0, value: [0, 0, 0] }, { at: 0.5, value: [0, 2, 0] }, { at: 1, value: [0, 2, 10] }] };
+ assertClose(translationOf(sampled([owner, targetAt([2.5, 0, 0])], action)), [0, 1, 0], 'first segment');
+ assertClose(translationOf(sampled([owner, targetAt([7.5, 0, 0])], action)), [0, 2, 5], 'second segment');
+ assertClose(translationOf(sampled([owner, targetAt([99, 0, 0])], action)), [0, 2, 10], 'past the end');
+});
+
+test('the new constraints refuse bad fields', () => {
+ const pair = [owner, targetAt([1, 0, 0])];
+ const refuses = (constraint, pattern) => assert.throws(() => sampled(pair, constraint), pattern);
+ refuses({ type: 'limit_scale', x: [0, 2] }, /minimum must be above 0/);
+ refuses({ type: 'limit_distance', target: 'target', distance: -1 }, /distance/);
+ refuses({ type: 'locked_track', target: 'target', trackAxis: '+z', lockAxis: 'z' }, /different axes/);
+ refuses({ type: 'stretch_to', target: 'target', volume: 'all' }, /volume/);
+ refuses({ type: 'transformation', target: 'target', fromMax: [0, 1, 1] }, /fromMax must differ/);
+ refuses({ type: 'transformation', target: 'target', map: ['x', 'y'] }, /map/);
+ refuses({ type: 'action', target: 'target', min: 1, max: 1, keys: [] }, /min must be below max/);
+ refuses({ type: 'action', target: 'target', min: 0, max: 1, keys: [{ at: 0, value: [0, 0, 0] }] }, /at least 2/);
+ refuses({ type: 'action', target: 'target', min: 0, max: 1, keys: [{ at: 0.5, value: [0, 0, 0] }, { at: 0.5, value: [1, 0, 0] }] }, /rising/);
+ refuses({ type: 'copy_transforms' }, /target/);
+});
+
+test('scene_capabilities lists every constraint type', () => {
+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionConstraints].sort(), [...CONSTRAINT_TYPES].sort());
+});