Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add multi-bone chain IK and Spline IK to skeleton-pose and motion.ik (#689) (#739)

Nguyen Xuan An80db017809ce
diff --git a/changes/689.md b/changes/689.md
new file mode 100644
index 00000000..916edd3c
--- /dev/null
+++ b/changes/689.md
@@ -0,0 +1 @@
+- Add multi-bone `chain` IK (with `pole`, `poleAngle`, `stretch`, `iterations` and per-joint `limits`) and `spline` IK along Catmull-Rom curves to `addons/skeleton-pose` and recipe `motion.ik` (#689).
diff --git a/changes/689.size.md b/changes/689.size.md
new file mode 100644
index 00000000..ccb0e002
--- /dev/null
+++ b/changes/689.size.md
@@ -0,0 +1,5 @@
+- entry:skeleton-pose: multi-bone CCD `chain` IK solver (with pole plane, poleAngle, bone stretch and joint limits) and Catmull-Rom `spline` IK solver (#689).
+- scene:agent-scene: `motionIk` capability names (`chain`, `spline`) in `agent-scene-capabilities.js` (#689).
+- scene:agent-scene+lazy: recipe `motion.ik` validation, staged stretch translation bindings and curve node evaluation for `chain` and `spline` solvers (#689).
+- entry:agent-asset: multi-bone chain IK and Spline IK solvers in imported asset motion (#689).
+- goal:agent-scene: 10 B gzip for `motionIk` capability names (`chain`, `spline`) in `agent-scene-capabilities.js` (#689).
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index 0bb6d093..283b91ed 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -112,6 +112,10 @@ A `two-bone` solver takes `root`, `middle` and `end` node IDs, each a descendant
point the middle node bends toward; give one, because a straight limb has no bend direction of its own. `keepEndRotation`
defaults to `true`, so a gripper or foot keeps its world rotation.
+A `chain` solver (alias `ik`) takes `chain` (2 to 16 node IDs from base to end) or `root` and `end`, `target`, optional `pole`, `poleAngle` (-180 to 180 degrees), `stretch` (boolean or 0 to 1), `iterations` (1 to 64, default 16), `limits` (joint node ID to `{ x, y, z }` degree ranges), `keepEndRotation` and `weight`.
+
+A `spline` solver (alias `spline_ik`) takes `chain` (or `root` and `end`), `curve` (2 to 64 `[x, y, z]` points or `{ "nodes": [ids] }` whose world positions define the Catmull-Rom spline), optional `stretch` (boolean or 0 to 1, default `true`) and `weight`.
+
An `aim` solver takes `joint`, or `joints` from the base of a chain to the aiming node, which then share the turn.
`worldForward` is the world direction the character faces at rest, which is the one to use on imported rigs because their
bone axes vary. Otherwise `forward` is the aiming node's local axis (default `[0, 0, 1]`). `maxAngle` limits the whole
diff --git a/docs/parity.md b/docs/parity.md
index 5ed10b01..83a646b6 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -155,9 +155,9 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| 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 > Inverse Kinematics Constraint | partial | Two-bone, multi-bone `chain` (CCD with `pole`, `poleAngle`, `stretch` and joint `limits`) and `aim` IK, in code and in `motion.ik`. | [agent-motion-ik](../tests/agent-motion-ik.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js), [skeleton-pose](../tests/skeleton-pose.test.js) | #58, #689 |
| 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 > Spline IK Constraint | partial | `spline` in `addons/skeleton-pose` and `motion.ik`: fits a bone chain along a Catmull-Rom curve (points or control nodes) with optional arc-length `stretch`. | [skeleton-pose](../tests/skeleton-pose.test.js), [agent-motion-ik](../tests/agent-motion-ik.test.js) | #689 |
| 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 | 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 |
diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.md
index f2ed562e..afddbdc5 100644
--- a/docs/skeleton-pose.md
+++ b/docs/skeleton-pose.md
@@ -107,6 +107,12 @@ perfectly straight limb has no defined bend for the next frame.
The turn is the shortest rotation, so `aim` does not hold an up direction and can add a little roll.
+## Multi-bone Chain IK and Spline IK
+
+`{ type: 'chain', chain: ['b0', 'b1', 'b2', 'end'], target, pole, poleAngle, stretch, iterations, limits, keepEndRotation, weight }` (or `{ type: 'chain', root: 'b0', end: 'end', ... }`, alias `'ik'`) solves chains of two or more bones with cyclic coordinate descent (1 to 64 iterations, default 16). `pole` sets the bend plane and `poleAngle` (-180 to 180 degrees) turns that plane around the root-to-target line. `stretch` (boolean or 0 to 1, default 0) scales bone translations when the target is beyond the chain length, and `limits` clamps per-joint Euler XYZ ranges in degrees.
+
+`{ type: 'spline', chain: ['b0', 'b1', 'b2', 'end'], curve, stretch, weight }` (or `root` and `end`, alias `'spline_ik'`) fits the bone chain along a Catmull-Rom curve of 2 to 64 world points `[x, y, z]` (or a function `time => points`). `stretch` defaults to `true` (1), scaling each bone segment to its arc-length span along the curve; `false` (0) keeps rest bone lengths.
+
## Reading the result
`pose.jointWorld(name)` returns `{ position, rotation }` after the last `apply`, in world space, for attaching props or
diff --git a/src/agent-motion.js b/src/agent-motion.js
index 2a28dfc9..f67c3fe6 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -211,8 +211,19 @@ function ikWeight(input, duration, label) {
}
/** { root: { x: [min, max], y, z }, middle: {...} } in degrees, the turn away from the rest rotation in the joint's own axes. */
-function jointLimits(input, label) {
- knownKeys(input, ['root', 'middle'], label);
+function jointLimits(input, label, allowedJoints = null) {
+ if (allowedJoints) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw invalidField(label, input, 'an object mapping joint node IDs to { x, y, z } degree ranges', TypeError);
+ }
+ for (const joint of Object.keys(input)) {
+ if (!allowedJoints.has(joint)) {
+ throw invalidField(`${label}.${joint}`, joint, 'a node ID in the chain');
+ }
+ }
+ } else {
+ knownKeys(input, ['root', 'middle'], label);
+ }
const limits = {};
for (const joint of Object.keys(input)) {
knownKeys(input[joint], ['x', 'y', 'z'], `${label}.${joint}`);
@@ -228,6 +239,50 @@ function jointLimits(input, label) {
return limits;
}
+function normalizeIkChainSpec(input, nodes, label) {
+ if (input.chain !== undefined && (input.root !== undefined || input.end !== undefined)) {
+ throw invalidField(`${label}.chain`, input.chain, 'chain, or root and end, not both', TypeError);
+ }
+ if (input.chain !== undefined) {
+ const names = denseArray(input.chain, 16, `${label}.chain`);
+ if (names.length < 2) {
+ throw invalidField(`${label}.chain`, input.chain, '2 to 16 node IDs from base to end, such as ["b0", "b1", "b2", "tip"]');
+ }
+ return { chain: names.map((name, slot) => nodeIdFrom(name, nodes, `${label}.chain[${slot}]`)) };
+ }
+ if (input.root !== undefined && input.end !== undefined) {
+ return {
+ root: nodeIdFrom(input.root, nodes, `${label}.root`),
+ end: nodeIdFrom(input.end, nodes, `${label}.end`),
+ };
+ }
+ throw invalidField(`${label}.chain`, input.chain, 'chain: [nodeIds], or root and end node IDs', TypeError);
+}
+
+function normalizeIkStretch(value, label) {
+ if (typeof value === 'boolean') return value;
+ return bounded(value, 0, 1, label);
+}
+
+function normalizeIkCurve(input, visibleNodes, label) {
+ if (Array.isArray(input)) {
+ denseArray(input, 64, label);
+ if (input.length < 2) {
+ throw invalidField(label, input, '2 to 64 [x, y, z] points');
+ }
+ return input.map((point, index) => valueFrom(point, 3, `${label}[${index}]`));
+ }
+ if (input && typeof input === 'object' && Object.hasOwn(input, 'nodes')) {
+ knownKeys(input, ['nodes'], label);
+ const ids = denseArray(input.nodes, 64, `${label}.nodes`);
+ if (ids.length < 2) {
+ throw invalidField(`${label}.nodes`, input.nodes, '2 to 64 node IDs');
+ }
+ return { nodes: ids.map((id, index) => nodeIdFrom(id, visibleNodes, `${label}.nodes[${index}]`)) };
+ }
+ throw invalidField(label, input, '2 to 64 [x, y, z] points or { "nodes": [ids] }', TypeError);
+}
+
function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {
const label = `motion.ik[${position}]`;
if (input?.type === 'two-bone') {
@@ -285,15 +340,68 @@ function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {
}
return solver;
}
- throw invalidField(`${label}.type`, input?.type, 'one of two-bone or aim');
+ if (input?.type === 'chain' || input?.type === 'ik') {
+ knownKeys(input, ['type', 'chain', 'root', 'end', 'target', 'pole', 'poleAngle', 'stretch', 'iterations', 'limits', 'keepEndRotation', 'weight'], label);
+ const spec = normalizeIkChainSpec(input, nodes, label);
+ const solver = {
+ type: 'chain',
+ ...spec,
+ target: ikPoint(input.target, visibleNodes, duration, `${label}.target`),
+ weight: ikWeight(input.weight, duration, `${label}.weight`),
+ };
+ if (input.pole !== undefined) {
+ solver.pole = ikPoint(input.pole, visibleNodes, duration, `${label}.pole`);
+ }
+ if (input.poleAngle !== undefined) {
+ solver.poleAngle = bounded(input.poleAngle, -180, 180, `${label}.poleAngle`);
+ }
+ if (input.stretch !== undefined) {
+ solver.stretch = normalizeIkStretch(input.stretch, `${label}.stretch`);
+ }
+ if (input.iterations !== undefined) {
+ if (!Number.isInteger(input.iterations)) {
+ throw invalidField(`${label}.iterations`, input.iterations, 'a whole number of iterations from 1 to 64, such as 16', TypeError);
+ }
+ solver.iterations = bounded(input.iterations, 1, 64, `${label}.iterations`);
+ }
+ if (input.keepEndRotation !== undefined) {
+ if (typeof input.keepEndRotation !== 'boolean') {
+ throw invalidField(`${label}.keepEndRotation`, input.keepEndRotation, 'true or false', TypeError);
+ }
+ solver.keepEndRotation = input.keepEndRotation;
+ }
+ if (input.limits !== undefined) {
+ const allowed = spec.chain ? new Set(spec.chain.slice(0, -1)) : nodes;
+ solver.limits = jointLimits(input.limits, `${label}.limits`, allowed);
+ }
+ return solver;
+ }
+ if (input?.type === 'spline' || input?.type === 'spline_ik') {
+ knownKeys(input, ['type', 'chain', 'root', 'end', 'curve', 'stretch', 'weight'], label);
+ const spec = normalizeIkChainSpec(input, nodes, label);
+ const solver = {
+ type: 'spline',
+ ...spec,
+ curve: normalizeIkCurve(input.curve, visibleNodes, `${label}.curve`),
+ weight: ikWeight(input.weight, duration, `${label}.weight`),
+ };
+ if (input.stretch !== undefined) {
+ solver.stretch = normalizeIkStretch(input.stretch, `${label}.stretch`);
+ }
+ return solver;
+ }
+ throw invalidField(`${label}.type`, input?.type, 'one of two-bone, aim, chain or spline');
}
function solverNodes(solver) {
- return solver.type === 'two-bone' ? [solver.root, solver.middle, solver.end] : solver.joints;
+ if (solver.type === 'two-bone') return [solver.root, solver.middle, solver.end];
+ if (solver.type === 'aim') return solver.joints;
+ return solver.chain ?? [solver.root, solver.end];
}
function pointNodes(solver) {
- return [solver.target, solver.pole].filter(point => point?.node).map(point => point.node);
+ const points = [solver.target, solver.pole].filter(point => point?.node).map(point => point.node);
+ return solver.curve?.nodes ? [...points, ...solver.curve.nodes] : points;
}
function ancestorsOf(id, nodesById) {
@@ -499,7 +607,7 @@ function ikRig(ik, recipe) {
function ikChannelClip(ik, duration, loop) {
const tracks = [];
ik.forEach((solver, position) => {
- if (solver.target.keyframes) tracks.push({ target: `target ${position}`, property: 'translation', interpolation: solver.target.interpolation, keyframes: solver.target.keyframes });
+ if (solver.target?.keyframes) tracks.push({ target: `target ${position}`, property: 'translation', interpolation: solver.target.interpolation, keyframes: solver.target.keyframes });
if (solver.pole?.keyframes) tracks.push({ target: `pole ${position}`, property: 'translation', interpolation: solver.pole.interpolation, keyframes: solver.pole.keyframes });
if (solver.weight.keyframes) tracks.push({ target: `weight ${position}`, property: 'value', interpolation: solver.weight.interpolation, keyframes: solver.weight.keyframes });
});
@@ -521,13 +629,30 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
};
const definitions = motion.ik.map((solver, position) => {
const weightOutput = solver.weight.keyframes ? channelOutput(`weight ${position}`) : null;
- const common = {
- target: pointReader(solver.target, `target ${position}`),
- weight: weightOutput ? () => Math.min(1, Math.max(0, weightOutput[0])) : solver.weight,
- };
+ const weight = weightOutput ? () => Math.min(1, Math.max(0, weightOutput[0])) : solver.weight;
+ if (solver.type === 'spline') {
+ const curve = Array.isArray(solver.curve)
+ ? solver.curve
+ : () => solver.curve.nodes.map(nodeId => pose.jointWorld(nodeId).position);
+ return {
+ type: 'spline',
+ ...(solver.chain ? { chain: solver.chain } : { root: solver.root, end: solver.end }),
+ curve, stretch: solver.stretch, weight,
+ };
+ }
+ const common = { target: pointReader(solver.target, `target ${position}`), weight };
if (solver.type === 'aim') {
return { ...common, type: 'aim', joints: solver.joints, forward: solver.forward, worldForward: solver.worldForward, maxAngle: solver.maxAngle };
}
+ if (solver.type === 'chain') {
+ return {
+ ...common, type: 'chain',
+ ...(solver.chain ? { chain: solver.chain } : { root: solver.root, end: solver.end }),
+ ...(solver.pole ? { pole: pointReader(solver.pole, `pole ${position}`) } : {}),
+ poleAngle: solver.poleAngle, stretch: solver.stretch, iterations: solver.iterations,
+ limits: solver.limits, keepEndRotation: solver.keepEndRotation,
+ };
+ }
return {
...common, type: 'two-bone', root: solver.root, middle: solver.middle, end: solver.end,
...(solver.pole ? { pole: pointReader(solver.pole, `pole ${position}`) } : {}),
@@ -537,11 +662,15 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
pose = createSkeletonPose({ rig, ik: definitions });
const indexById = new Map(rig.joints.map((joint, index) => [joint.name, index]));
const baseBindings = rig.joints.map((joint, index) => ({ index, tracks: stagedNodeTracks.get(joint.name) }));
- const solvedIds = new Set(motion.ik.flatMap(solver => {
- if (solver.type === 'aim') return solver.joints;
- return solver.keepEndRotation === false ? [solver.root, solver.middle] : [solver.root, solver.middle, solver.end];
- }));
+ const skippedEnds = new Set(
+ motion.ik
+ .filter(solver => (solver.type === 'two-bone' || solver.type === 'chain') && solver.keepEndRotation === false)
+ .map(solver => solver.end ?? solver.chain[solver.chain.length - 1])
+ );
+ const solvedIds = new Set(pose.solvedJointNames.filter(id => !skippedEnds.has(id)));
const staged = new Map([...solvedIds].map(id => [id, new Float64Array(4)]));
+ const translatedIds = pose.writtenJoints.filter(entry => entry.translation).map(entry => rig.joints[entry.index].name);
+ const stagedTranslations = new Map(translatedIds.map(id => [id, new Float64Array(3)]));
function setBaseFromTracks(localRotations, localTranslations) {
for (const { index, tracks } of baseBindings) {
if (tracks?.rotation) localRotations[index].set(tracks.rotation);
@@ -550,6 +679,7 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
}
return {
staged,
+ stagedTranslations,
/** Solve for a time. `nodePoses` is a staged { id, translation, rotation } list; without it the base is the tracks. */
solve(time, nodePoses) {
channelSampler?.sample(time);
@@ -569,6 +699,9 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
rotation.set(pose.localRotation(indexById.get(id)));
if (!rotation.every(Number.isFinite)) throw new RangeError(`Motion ik produced an invalid rotation for node ${id}.`);
}
+ for (const [id, translation] of stagedTranslations) {
+ translation.set(pose.localTranslation(indexById.get(id)));
+ }
return pose.ikResults;
},
};
@@ -699,6 +832,11 @@ export function compileAgentMotion(input, recipe) {
const nodePatch = output.nodes.get(id);
if (!nodePatch.rotation) nodePatch.rotation = new Float64Array(4);
}
+ for (const id of ikEvaluator.stagedTranslations.keys()) {
+ if (!output.nodes.has(id)) output.nodes.set(id, {});
+ const nodePatch = output.nodes.get(id);
+ if (!nodePatch.translation) nodePatch.translation = new Float64Array(3);
+ }
}
if (constraintEvaluator && !ikUsesStagedPose) {
for (const id of constrainedNodeIds(motion)) {
@@ -753,6 +891,7 @@ export function compileAgentMotion(input, recipe) {
function poseBases() {
const bases = trackBases();
for (const [id, rotation] of ikEvaluator?.staged ?? []) bases.set(id, { ...bases.get(id), rotation });
+ for (const [id, translation] of ikEvaluator?.stagedTranslations ?? []) bases.set(id, { ...bases.get(id), translation });
return bases;
}
return Object.freeze({
@@ -771,6 +910,10 @@ export function compileAgentMotion(input, recipe) {
overrides.set(id, { rotation: Array.from(rotation) });
bases.set(id, { ...bases.get(id), rotation });
}
+ for (const [id, translation] of ikEvaluator.stagedTranslations) {
+ overrides.set(id, { ...overrides.get(id), translation: Array.from(translation) });
+ bases.set(id, { ...bases.get(id), translation });
+ }
}
if (constraintEvaluator) {
for (const [id, frame] of constraintEvaluator.evaluate(time, bases).nodes) {
@@ -851,6 +994,7 @@ export function compileAgentMotion(input, recipe) {
}
if (ikEvaluator && !ikUsesStagedPose) {
for (const [id, rotation] of ikEvaluator.staged) output.nodes.get(id).rotation.set(rotation);
+ for (const [id, translation] of ikEvaluator.stagedTranslations) output.nodes.get(id).translation.set(translation);
}
if (evaluated && !ikUsesStagedPose) {
for (const [id, frame] of evaluated.nodes) {
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 94d7e460..0710da53 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -259,13 +259,13 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
renderFlags: Object.freeze({ nodeFields: Object.freeze(['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher']), motion: 'node track property visible: 1 or 0, STEP', note: 'visible:false hides a node and children; holdout and shadowCatcher need a transparent canvas (Renderer67 transparent:true); flags split batches.' }),
depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset']), warning: 'coplanar-overlap', note: 'decal wins over the surface below; depthLayer stacks decals; resolveCoplanar offset biases the smaller part of a flagged pair.' }),
proceduralMotion: true,
- motionIk: Object.freeze(['two-bone', 'aim']),
+ motionIk: Object.freeze(['two-bone', 'aim', 'chain', 'spline']),
// Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
// Node relations place a mesh node against other mesh nodes (world bounds), solved again after every edit.
relations: Object.freeze({
maxPerNode: 8, maxNodes: 256, sides: Object.freeze(['+x', '-x', '+y', '-y', '+z', '-z']),
kinds: Object.freeze({
- attach: 'to, side, offset: touch the face of the target on side and centre on the other axes; offset is the distance, negative sinks in',
+ attach: 'to, side, offset: touch the target face on side and centre on the other axes; offset is distance, negative sinks in',
gap: 'to, side, offset: as attach on that axis only',
flush: 'to, side, offset: own face on side level with the same face of the target',
align: 'to, axis, at (min, center, max), offset: anchor on one axis',
diff --git a/src/skeleton-pose.js b/src/skeleton-pose.js
index c071d8f5..29a909d0 100644
--- a/src/skeleton-pose.js
+++ b/src/skeleton-pose.js
@@ -157,11 +157,11 @@ const MIN_REST_BEND_FRACTION = 0.02;
* Joint limits from { root: { x: [min, max], y, z }, middle: {...} } in degrees. Angles are the joint's turn away from its
* rest rotation, in its own axes, as Euler XYZ (the order Blender uses). An axis left out is free.
*/
-function createJointLimits(definition, label, jointIndices, prepared) {
+function createJointLimits(definition, label, jointIndices, prepared, roleHint = 'root or middle') {
if (definition === undefined) return [];
- if (!definition || typeof definition !== 'object' || Array.isArray(definition)) throw new TypeError(`${label} limits must be { root, middle } with an x, y or z range each.`);
+ if (!definition || typeof definition !== 'object' || Array.isArray(definition)) throw new TypeError(`${label} limits must be { ${roleHint} } with an x, y or z range each.`);
return Object.entries(definition).map(([role, axes]) => {
- if (!Object.hasOwn(jointIndices, role)) throw new RangeError(`${label} limits: ${role} must be root or middle.`);
+ if (!Object.hasOwn(jointIndices, role)) throw new RangeError(`${label} limits: ${role} must be ${roleHint}.`);
const unknownAxis = Object.keys(axes ?? {}).find(axis => !LIMIT_AXES.includes(axis));
if (unknownAxis !== undefined) throw new RangeError(`${label} limits ${role}: ${unknownAxis} must be x, y or z.`);
const ranges = LIMIT_AXES.map(axis => {
@@ -177,6 +177,67 @@ function createJointLimits(definition, label, jointIndices, prepared) {
});
}
+function resolveChainJoints(definition, label, prepared, resolveJoint) {
+ let joints;
+ let names;
+ if (definition.chain !== undefined) {
+ if (!Array.isArray(definition.chain) || definition.chain.length < 2 || definition.chain.length > 64) {
+ throw new RangeError(`${label} chain must list 2 to 64 joints from base to end.`);
+ }
+ names = definition.chain;
+ joints = names.map(name => resolveJoint(name, label));
+ joints.slice(1).forEach((joint, slot) => {
+ if (!isDescendant(prepared, joint, joints[slot])) {
+ throw new RangeError(`${label}: each chain joint must descend from the one before it.`);
+ }
+ });
+ } else if (definition.root !== undefined && definition.end !== undefined) {
+ const root = resolveJoint(definition.root, label);
+ const end = resolveJoint(definition.end, label);
+ if (!isDescendant(prepared, end, root)) {
+ throw new RangeError(`${label}: end must descend from root.`);
+ }
+ const chain = [];
+ let current = end;
+ while (current >= 0) {
+ chain.push(current);
+ if (current === root) break;
+ current = prepared.joints[current].parent;
+ }
+ joints = chain.reverse();
+ names = joints.map(index => prepared.joints[index].name);
+ } else {
+ throw new TypeError(`${label} needs chain (or root and end).`);
+ }
+ const segmentChildren = [];
+ for (let slot = 0; slot < joints.length - 1; slot++) {
+ const indices = [];
+ let current = joints[slot + 1];
+ while (current !== joints[slot]) {
+ indices.push(current);
+ current = prepared.joints[current].parent;
+ }
+ segmentChildren.push(indices);
+ }
+ return { joints, names, segmentChildren, stretchIndices: segmentChildren.flat() };
+}
+
+function normalizeStretch(value, defaultValue, label) {
+ if (value === undefined) return defaultValue;
+ if (typeof value === 'boolean') return value ? 1 : 0;
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
+ throw new RangeError(`${label} stretch must be a boolean or a number from 0 to 1.`);
+ }
+ return value;
+}
+
+function checkedCurvePoints(points, label) {
+ if (!Array.isArray(points) || points.length < 2 || points.length > 64) {
+ throw new RangeError(`${label} curve must be 2 to 64 [x, y, z] points.`);
+ }
+ return points.map((point, index) => checkedVector(point, `${label} curve[${index}]`));
+}
+
function roundedDegrees(radians) {
return Number((radians / TO_RADIANS).toFixed(4));
}
@@ -252,7 +313,8 @@ function bendWarnings(solver, state, prepared) {
function createSolver(definition, position, prepared, resolveJoint) {
const label = `IK ${position}`;
const weight = weightFunction(definition?.weight ?? 1, `${label} weight`);
- if (typeof definition?.target !== 'function') checkedVector(definition?.target, `${label} target`);
+ const solverType = definition?.type === 'ik' ? 'chain' : definition?.type === 'spline_ik' ? 'spline' : definition?.type;
+ if (solverType !== 'spline' && typeof definition?.target !== 'function') checkedVector(definition?.target, `${label} target`);
if (definition.type === 'two-bone') {
const root = resolveJoint(definition.root, label);
const middle = resolveJoint(definition.middle, label);
@@ -291,7 +353,40 @@ function createSolver(definition, position, prepared, resolveJoint) {
if (!Number.isFinite(maxAngle) || maxAngle <= 0) throw new RangeError(`${label} maxAngle must be a positive number of degrees.`);
return { type: 'aim', label, weight, joints, forward, maxRadians: maxAngle * TO_RADIANS, target: definition.target };
}
- throw new RangeError(`${label} type must be two-bone or aim.`);
+ if (solverType === 'chain') {
+ const { joints, names, segmentChildren, stretchIndices } = resolveChainJoints(definition, label, prepared, resolveJoint);
+ if (definition.pole !== undefined && typeof definition.pole !== 'function') checkedVector(definition.pole, `${label} pole`);
+ const poleAngle = definition.poleAngle ?? 0;
+ if (!Number.isFinite(poleAngle) || poleAngle < -180 || poleAngle > 180) {
+ throw new RangeError(`${label} poleAngle must be degrees from -180 to 180.`);
+ }
+ const stretch = normalizeStretch(definition.stretch, 0, label);
+ const iterations = definition.iterations ?? 16;
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > 64) {
+ throw new RangeError(`${label} iterations must be a whole number from 1 to 64.`);
+ }
+ const limitJoints = {};
+ joints.slice(0, -1).forEach((index, slot) => {
+ limitJoints[names[slot]] = index;
+ limitJoints[prepared.joints[index].name] = index;
+ });
+ const limits = createJointLimits(definition.limits, label, limitJoints, prepared, 'a joint in the chain');
+ return {
+ type: 'chain', label, weight, joints, segmentChildren, stretchIndices,
+ target: definition.target, pole: definition.pole, poleRadians: poleAngle * TO_RADIANS,
+ stretch, iterations, limits, keepEndRotation: definition.keepEndRotation !== false,
+ };
+ }
+ if (solverType === 'spline') {
+ const { joints, segmentChildren, stretchIndices } = resolveChainJoints(definition, label, prepared, resolveJoint);
+ if (typeof definition.curve !== 'function') checkedCurvePoints(definition.curve, label);
+ const stretch = normalizeStretch(definition.stretch, 1, label);
+ return {
+ type: 'spline', label, weight, joints, segmentChildren, stretchIndices,
+ curve: definition.curve, stretch,
+ };
+ }
+ throw new RangeError(`${label} type must be two-bone, aim, chain or spline.`);
}
function resolvedPoint(value, time, reference, label) {
@@ -314,7 +409,7 @@ function createSolverContext(prepared, state, localRotations, localTranslations)
quat.normalize(localRotations[index], quat.slerp(localRotations[index], localRotations[index], scratch, weight));
update();
}
- return { state, prepared, localRotations, update, setWorldRotation };
+ return { state, prepared, localRotations, localTranslations, update, setWorldRotation };
}
/**
@@ -417,7 +512,206 @@ function solveAim(solver, time, context) {
return { reached: error < 0.02, error };
}
-const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim };
+function sampleCatmullRomCurve(points, parameter) {
+ const count = points.length;
+ if (count === 2) return vec3.lerp(new Float64Array(3), points[0], points[1], parameter);
+ const scaled = Math.max(0, Math.min(1, parameter)) * (count - 1);
+ const segment = Math.min(count - 2, Math.floor(scaled));
+ const localT = scaled - segment;
+ const localT2 = localT * localT;
+ const localT3 = localT2 * localT;
+ const p1 = points[segment];
+ const p2 = points[segment + 1];
+ const p0 = segment > 0 ? points[segment - 1] : [2 * p1[0] - p2[0], 2 * p1[1] - p2[1], 2 * p1[2] - p2[2]];
+ const p3 = segment + 2 < count ? points[segment + 2] : [2 * p2[0] - p1[0], 2 * p2[1] - p1[1], 2 * p2[2] - p1[2]];
+ const out = new Float64Array(3);
+ for (let axis = 0; axis < 3; axis++) {
+ const a0 = -0.5 * p0[axis] + 1.5 * p1[axis] - 1.5 * p2[axis] + 0.5 * p3[axis];
+ const a1 = p0[axis] - 2.5 * p1[axis] + 2 * p2[axis] - 0.5 * p3[axis];
+ const a2 = -0.5 * p0[axis] + 0.5 * p2[axis];
+ out[axis] = a0 * localT3 + a1 * localT2 + a2 * localT + p1[axis];
+ }
+ return out;
+}
+
+function buildSplineArcTable(points) {
+ const steps = 128;
+ const samples = Array.from({ length: steps + 1 }, (_, index) => sampleCatmullRomCurve(points, index / steps));
+ const lengths = new Float64Array(steps + 1);
+ for (let index = 1; index <= steps; index++) {
+ lengths[index] = lengths[index - 1] + vec3.distance(samples[index - 1], samples[index]);
+ }
+ const totalLength = lengths[steps];
+ const endTangent = vec3.subtract(new Float64Array(3), samples[steps], samples[steps - 1]);
+ if (vec3.length(endTangent) > NEAR_ZERO) vec3.normalize(endTangent, endTangent);
+ else endTangent[0] = 1;
+ function pointAtDistance(distance) {
+ if (distance <= 0 || totalLength <= NEAR_ZERO) return Float64Array.from(samples[0]);
+ if (distance >= totalLength) {
+ return vec3.scaleAndAdd(new Float64Array(3), samples[steps], endTangent, distance - totalLength);
+ }
+ let low = 0;
+ let high = steps;
+ while (low < high - 1) {
+ const mid = (low + high) >> 1;
+ if (lengths[mid] <= distance) low = mid;
+ else high = mid;
+ }
+ const span = lengths[high] - lengths[low];
+ const alpha = span > NEAR_ZERO ? (distance - lengths[low]) / span : 0;
+ return vec3.lerp(new Float64Array(3), samples[low], samples[high], alpha);
+ }
+ return { totalLength, endTangent, pointAtDistance };
+}
+
+/** Multi-bone IK chain solved by cyclic coordinate descent with optional pole plane, poleAngle, stretch and joint limits. */
+function solveChain(solver, time, context) {
+ const { state, prepared, localRotations, update, setWorldRotation } = context;
+ const weight = checkedWeight(solver.weight, time, `${solver.label} weight`);
+ const end = solver.joints[solver.joints.length - 1];
+ const target = resolvedPoint(solver.target, time, state.positions[end], `${solver.label} target`);
+ if (weight === 0) return { reached: true, error: 0, warnings: [], limited: [] };
+ const baseRotations = solver.joints.map(index => Float64Array.from(localRotations[index]));
+ const baseTranslations = solver.stretchIndices.map(index => Float64Array.from(context.localTranslations[index]));
+ const endRotation = Float64Array.from(state.rotations[end]);
+ let totalLength = 0;
+ for (let slot = 0; slot < solver.joints.length - 1; slot++) {
+ totalLength += vec3.distance(state.positions[solver.joints[slot]], state.positions[solver.joints[slot + 1]]);
+ }
+ const rootPos = Float64Array.from(state.positions[solver.joints[0]]);
+ const toTarget = vec3.subtract(new Float64Array(3), target, rootPos);
+ const targetDistance = vec3.length(toTarget);
+ if (targetDistance < NEAR_ZERO || totalLength < NEAR_ZERO) {
+ return { reached: false, error: vec3.distance(state.positions[end], target), warnings: [], limited: [] };
+ }
+ if (solver.stretch > 0 && targetDistance > totalLength) {
+ const scaleFactor = 1 + (targetDistance / totalLength - 1) * solver.stretch;
+ for (const index of solver.stretchIndices) {
+ vec3.scale(context.localTranslations[index], context.localTranslations[index], scaleFactor);
+ }
+ update();
+ totalLength *= scaleFactor;
+ }
+ const axis = vec3.scale(new Float64Array(3), toTarget, 1 / targetDistance);
+ if (solver.pole !== undefined) {
+ const midJoint = solver.joints[Math.floor(solver.joints.length / 2)];
+ const polePoint = resolvedPoint(solver.pole, time, state.positions[midJoint], `${solver.label} pole`);
+ const toPole = vec3.subtract(new Float64Array(3), polePoint, rootPos);
+ const polePerp = vec3.scaleAndAdd(new Float64Array(3), toPole, axis, -vec3.dot(toPole, axis));
+ if (vec3.length(polePerp) < NEAR_ZERO) vec3.copy(polePerp, perpendicularTo(axis));
+ else vec3.normalize(polePerp, polePerp);
+ if (solver.poleRadians !== 0) {
+ vec3.transformQuat(polePerp, polePerp, quat.setAxisAngle(new Float64Array(4), axis, solver.poleRadians));
+ }
+ const segmentCount = solver.joints.length - 1;
+ for (let slot = 0; slot < segmentCount; slot++) {
+ const joint = solver.joints[slot];
+ const nextJoint = solver.joints[slot + 1];
+ const curDir = vec3.subtract(new Float64Array(3), state.positions[nextJoint], state.positions[joint]);
+ const curLen = vec3.length(curDir);
+ if (curLen <= NEAR_ZERO) continue;
+ vec3.scale(curDir, curDir, 1 / curLen);
+ const arch = targetDistance < totalLength ? (0.5 - (slot + 0.5) / segmentCount) * 0.75 : 0;
+ const aimDir = vec3.normalize(new Float64Array(3), vec3.scaleAndAdd(new Float64Array(3), axis, polePerp, arch));
+ const turn = quat.rotationTo(new Float64Array(4), curDir, aimDir);
+ setWorldRotation(joint, quat.multiply(new Float64Array(4), turn, state.rotations[joint]), 1);
+ }
+ }
+ for (let iteration = 0; iteration < solver.iterations; iteration++) {
+ for (let slot = solver.joints.length - 2; slot >= 0; slot--) {
+ const joint = solver.joints[slot];
+ const jointPos = state.positions[joint];
+ const toEnd = vec3.subtract(new Float64Array(3), state.positions[end], jointPos);
+ const toGoal = vec3.subtract(new Float64Array(3), target, jointPos);
+ const endLen = vec3.length(toEnd);
+ const goalLen = vec3.length(toGoal);
+ if (endLen <= NEAR_ZERO || goalLen <= NEAR_ZERO) continue;
+ vec3.scale(toEnd, toEnd, 1 / endLen);
+ vec3.scale(toGoal, toGoal, 1 / goalLen);
+ const turn = quat.rotationTo(new Float64Array(4), toEnd, toGoal);
+ setWorldRotation(joint, quat.multiply(new Float64Array(4), turn, state.rotations[joint]), 1);
+ }
+ if (solver.limits.length && applyJointLimits(solver.limits, prepared, localRotations).length) update();
+ if (vec3.distance(state.positions[end], target) <= 1e-6) break;
+ }
+ const limited = applyJointLimits(solver.limits, prepared, localRotations);
+ if (limited.length) update();
+ if (solver.keepEndRotation) setWorldRotation(end, endRotation, 1);
+ if (weight < 1) {
+ solver.joints.forEach((index, slot) => {
+ quat.normalize(localRotations[index], quat.slerp(localRotations[index], baseRotations[slot], localRotations[index], weight));
+ });
+ solver.stretchIndices.forEach((index, slot) => {
+ vec3.lerp(context.localTranslations[index], baseTranslations[slot], context.localTranslations[index], weight);
+ });
+ update();
+ }
+ const error = vec3.distance(state.positions[end], target);
+ return { reached: error <= totalLength * 1e-3 + 1e-4, error, warnings: [], limited };
+}
+
+/** Spline IK along a Catmull-Rom curve, fitting each bone chord to its arc-length parameter along the curve. */
+function solveSpline(solver, time, context) {
+ const { state, localRotations, localTranslations, update, setWorldRotation } = context;
+ const weight = checkedWeight(solver.weight, time, `${solver.label} weight`);
+ const rawPoints = typeof solver.curve === 'function' ? solver.curve(time) : solver.curve;
+ const points = checkedCurvePoints(rawPoints, solver.label);
+ if (weight === 0) return { reached: true, error: 0 };
+ const baseRotations = solver.joints.map(index => Float64Array.from(localRotations[index]));
+ const baseTranslations = solver.stretchIndices.map(index => Float64Array.from(localTranslations[index]));
+ const segmentCount = solver.joints.length - 1;
+ const segmentLengths = new Float64Array(segmentCount);
+ const cumulative = new Float64Array(segmentCount + 1);
+ for (let slot = 0; slot < segmentCount; slot++) {
+ segmentLengths[slot] = vec3.distance(state.positions[solver.joints[slot]], state.positions[solver.joints[slot + 1]]);
+ cumulative[slot + 1] = cumulative[slot] + segmentLengths[slot];
+ }
+ const totalBoneLength = cumulative[segmentCount];
+ const table = buildSplineArcTable(points);
+ const spanLength = totalBoneLength + (table.totalLength - totalBoneLength) * solver.stretch;
+ const targets = Array.from({ length: segmentCount + 1 }, (_, slot) => {
+ const fraction = totalBoneLength > NEAR_ZERO ? cumulative[slot] / totalBoneLength : slot / segmentCount;
+ return table.pointAtDistance(fraction * spanLength);
+ });
+ for (let slot = 0; slot < segmentCount; slot++) {
+ const joint = solver.joints[slot];
+ const nextJoint = solver.joints[slot + 1];
+ const jointPos = state.positions[joint];
+ const goalVec = vec3.subtract(new Float64Array(3), targets[slot + 1], jointPos);
+ const goalLen = vec3.length(goalVec);
+ let curVec = vec3.subtract(new Float64Array(3), state.positions[nextJoint], jointPos);
+ let curLen = vec3.length(curVec);
+ if (solver.stretch > 0 && curLen > NEAR_ZERO && goalLen > NEAR_ZERO) {
+ const ratio = 1 + (goalLen / curLen - 1) * solver.stretch;
+ for (const childIndex of solver.segmentChildren[slot]) {
+ vec3.scale(localTranslations[childIndex], localTranslations[childIndex], ratio);
+ }
+ update();
+ curVec = vec3.subtract(new Float64Array(3), state.positions[nextJoint], state.positions[joint]);
+ curLen = vec3.length(curVec);
+ }
+ if (curLen > NEAR_ZERO && goalLen > NEAR_ZERO) {
+ vec3.scale(curVec, curVec, 1 / curLen);
+ vec3.scale(goalVec, goalVec, 1 / goalLen);
+ const turn = quat.rotationTo(new Float64Array(4), curVec, goalVec);
+ setWorldRotation(joint, quat.multiply(new Float64Array(4), turn, state.rotations[joint]), 1);
+ }
+ }
+ if (weight < 1) {
+ solver.joints.forEach((index, slot) => {
+ quat.normalize(localRotations[index], quat.slerp(localRotations[index], baseRotations[slot], localRotations[index], weight));
+ });
+ solver.stretchIndices.forEach((index, slot) => {
+ vec3.lerp(localTranslations[index], baseTranslations[slot], localTranslations[index], weight);
+ });
+ update();
+ }
+ const end = solver.joints[segmentCount];
+ const error = vec3.distance(state.positions[end], targets[segmentCount]);
+ return { reached: error <= Math.max(table.totalLength, totalBoneLength) * 1e-2 + 1e-4, error };
+}
+
+const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim, chain: solveChain, spline: solveSpline };
const GLTF_TRACK_PROPERTIES = { position: 'translation', quaternion: 'rotation', scale: 'scale' };
const GLTF_STEP_INTERPOLATION = 2300;
@@ -638,8 +932,12 @@ export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin)
const resolveJoint = jointResolver(rig, prepared);
const compiledLayers = layers.map((layer, position) => createLayer(layer, position, prepared, resolveJoint));
const solvers = ik.map((solver, position) => createSolver(solver, position, prepared, resolveJoint));
- const solvedIndices = new Set(solvers.flatMap(solver => (solver.type === 'aim' ? solver.joints : [solver.root, solver.middle, solver.end])));
- const translatedIndices = new Set(compiledLayers.flatMap(layer => layer.bindings.filter(binding => binding.property === 'translation').map(binding => binding.index)));
+ const solvedIndices = new Set(solvers.flatMap(solver => (solver.type === 'two-bone' ? [solver.root, solver.middle, solver.end] : solver.joints)));
+ const solverTranslated = solvers.flatMap(solver => (solver.stretch > 0 ? solver.stretchIndices : []));
+ const translatedIndices = new Set([
+ ...compiledLayers.flatMap(layer => layer.bindings.filter(binding => binding.property === 'translation').map(binding => binding.index)),
+ ...solverTranslated,
+ ]);
const writtenIndices = new Set([...solvedIndices, ...translatedIndices, ...compiledLayers.flatMap(layer => layer.bindings.filter(binding => binding.property === 'rotation').map(binding => binding.index))]);
const jointCount = rig.joints.length;
const localRotations = prepared.restRotations.map(rotation => Float64Array.from(rotation));
diff --git a/tests/agent-motion-ik.test.js b/tests/agent-motion-ik.test.js
index fe9f623f..975d7a10 100644
--- a/tests/agent-motion-ik.test.js
+++ b/tests/agent-motion-ik.test.js
@@ -160,7 +160,7 @@ test('recipes export and reload with their ik', () => {
test('mistakes say what to pass', () => {
const create = (ik, overrides) => createAgentScene(armRecipe({ duration: 1, tracks: [], ik }, overrides));
assert.throws(() => createAgentScene(armRecipe({ duration: 1, tracks: [] })), /at least one track, IK solver, constraint or driver/);
- assert.throws(() => create([{ type: 'fabrik', target: [0, 0, 0] }]), /motion\.ik\[0\]\.type: got "fabrik"; expected one of two-bone or aim/);
+ assert.throws(() => create([{ type: 'fabrik', target: [0, 0, 0] }]), /motion\.ik\[0\]\.type: got "fabrik"; expected one of two-bone, aim, chain or spline/);
assert.throws(() => create([armIk([0, 0, 0], { root: 'nope' })]), /motion\.ik\[0\]\.root: got "nope"; expected a node ID in this recipe/);
assert.throws(() => create([armIk({ node: 'nope' })]), /motion\.ik\[0\]\.target\.node: got "nope"; expected a node ID/);
assert.throws(() => create([armIk('here')]), /motion\.ik\[0\]\.target: got "here"; expected \[x, y, z\]/);
@@ -176,7 +176,73 @@ test('mistakes say what to pass', () => {
ik: [armIk([0, 0, 0])],
})), /no scale track on node/);
assert.throws(() => create([{ type: 'aim', joint: 'lamp', target: [0, 0, 0], forward: [0, 0, 1], worldForward: [0, 0, 1] }]), /forward or worldForward, not both/);
- assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionIk], ['two-bone', 'aim']);
+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionIk], ['two-bone', 'aim', 'chain', 'spline']);
+});
+
+test('recipe chain IK and spline IK reach targets, stretch and follow curve nodes', () => {
+ const nodes = [
+ { id: 'b0', translation: [0, 1, 0] },
+ { id: 'b1', parent: 'b0', translation: [0.4, 0, 0] },
+ { id: 'b2', parent: 'b1', translation: [0.4, 0, 0] },
+ { id: 'b3', parent: 'b2', translation: [0.4, 0, 0] },
+ { id: 'tip', parent: 'b3', translation: [0.4, 0, 0], geometry: 'box', material: 'paint', scale: [0.05, 0.05, 0.05] },
+ { id: 'c0', translation: [0, 1, 0] },
+ { id: 'c1', translation: [0.6, 1.5, 0] },
+ { id: 'c2', translation: [1.2, 1.5, 0] },
+ { id: 'c3', translation: [1.8, 1, 0] },
+ ];
+ const makeRecipe = ik => ({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: SEGMENT_MATERIALS,
+ nodes,
+ motion: { duration: 1, tracks: [], ik },
+ });
+
+ // 4-bone chain with pole, poleAngle, stretch and limits.
+ const chainScene = createAgentScene(makeRecipe([{
+ type: 'chain',
+ chain: ['b0', 'b1', 'b2', 'b3', 'tip'],
+ target: [2.0, 1, 0],
+ pole: [0.8, 2, 0],
+ poleAngle: 10,
+ stretch: true,
+ iterations: 20,
+ keepEndRotation: true,
+ limits: { b0: { z: [-90, 90] } },
+ }]));
+ chainScene.sampleMotion(0);
+ assertClose(worldPosition(chainScene, 'tip'), [2.0, 1, 0], 1e-2);
+ assert.equal(chainScene.inspect().motionIk[0].reached, true);
+
+ // Spline IK using control nodes and static points.
+ const splineScene = createAgentScene(makeRecipe([{
+ type: 'spline',
+ root: 'b0',
+ end: 'tip',
+ curve: { nodes: ['c0', 'c1', 'c2', 'c3'] },
+ stretch: 1,
+ }]));
+ splineScene.sampleMotion(0);
+ assertClose(worldPosition(splineScene, 'tip'), [1.8, 1, 0], 2e-2);
+
+ const staticSpline = createAgentScene(makeRecipe([{
+ type: 'spline_ik',
+ chain: ['b0', 'b1', 'b2', 'b3', 'tip'],
+ curve: [[0, 1, 0], [1, 1.4, 0], [2, 1, 0]],
+ stretch: true,
+ }]));
+ staticSpline.sampleMotion(0);
+ assertClose(worldPosition(staticSpline, 'tip'), [2, 1, 0], 2e-2);
+
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'chain', chain: ['b0', 'tip'], root: 'b0', end: 'tip', target: [0, 0, 0] }])), /chain, or root and end, not both/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'chain', chain: ['b0'], target: [0, 0, 0] }])), /2 to 16 node IDs/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'chain', target: [0, 0, 0] }])), /expected chain.*or root and end/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'chain', root: 'b0', end: 'tip', target: [0, 0, 0], iterations: 1.5 }])), /whole number of iterations/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'chain', chain: ['b0', 'b1', 'tip'], target: [0, 0, 0], limits: { c0: { x: [-10, 10] } } }])), /a node ID in the chain/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'spline', root: 'b0', end: 'tip', curve: [[0, 0, 0]] }])), /2 to 64 .* points/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'spline', root: 'b0', end: 'tip', curve: { nodes: ['c0'] } }])), /2 to 64 node IDs/);
+ assert.throws(() => createAgentScene(makeRecipe([{ type: 'spline', root: 'b0', end: 'tip', curve: 'bad' }])), /points or { "nodes"/);
});
test('a node named like a humanoid bone is not mapped to another node', () => {
diff --git a/tests/skeleton-pose.test.js b/tests/skeleton-pose.test.js
index cf866265..5d54b6b9 100644
--- a/tests/skeleton-pose.test.js
+++ b/tests/skeleton-pose.test.js
@@ -315,7 +315,7 @@ test('joints resolve by name or humanoid bone, and mistakes say what to pass', (
assert.throws(() => createSkeletonPose(), /needs a skin or a rig/);
assert.throws(() => createSkeletonPose({ rig, layers: [{}] }), /Layer 0 needs a clip/);
assert.throws(() => createSkeletonPose({ rig, layers: [{ clip: rotationClip('nothing', 10) }] }), /no clip track names a joint/);
- assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'fabrik', target: [0, 0, 0] }] }), /type must be two-bone or aim/);
+ assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'fabrik', target: [0, 0, 0] }] }), /type must be two-bone, aim, chain or spline/);
assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'two-bone', root: 'leftFoot', middle: 'leftLowerLeg', end: 'leftUpperLeg', target: [0, 0, 0] }] }), /end must descend from middle/);
assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'aim', joint: 'head' }] }), /target must be three finite numbers/);
const badTarget = createSkeletonPose({ rig, ik: [{ type: 'aim', joint: 'head', target: () => [Number.NaN, 0, 0] }] });
@@ -346,3 +346,64 @@ test('on a skin with real bind matrices, rest is the identity palette and IK mov
const footVertex = vec3.transformMat4(new Float64Array(3), rest.jointWorld('leftFoot').position, skin.jointMatrices.subarray(footIndex * 16, footIndex * 16 + 16));
assertClose(footVertex, target, 1e-5, 'bound vertex');
});
+
+test('multi-bone chain IK and spline IK solve long chains with pole, poleAngle, stretch, limits and curves', () => {
+ const tentacleRig = {
+ joints: [
+ { name: 'b0', parent: -1, translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'b1', parent: 0, translation: [1, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'b2', parent: 1, translation: [1, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'b3', parent: 2, translation: [1, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'tip', parent: 3, translation: [1, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ ],
+ };
+ const target = [2.2, 1.4, 0.5];
+ const chainPose = createSkeletonPose({
+ rig: tentacleRig,
+ ik: [{
+ type: 'chain',
+ chain: ['b0', 'b1', 'b2', 'b3', 'tip'],
+ target,
+ pole: [1, 3, 0],
+ poleAngle: 15,
+ iterations: 24,
+ limits: { b0: { z: [-80, 80] } },
+ }],
+ });
+ chainPose.apply(0);
+ assert.equal(chainPose.ikResults[0].reached, true);
+ assertClose(chainPose.jointWorld('tip').position, target, 1e-2);
+
+ // Root and end shorthand + stretch beyond rest length (4.0 m -> 5.0 m).
+ const stretchTarget = [5, 0, 0];
+ const stretched = createSkeletonPose({
+ rig: tentacleRig,
+ ik: [{ type: 'chain', root: 'b0', end: 'tip', target: stretchTarget, stretch: 1, weight: 0.5 }],
+ });
+ stretched.apply(0);
+ assertClose(stretched.jointWorld('tip').position, [4.5, 0, 0], 1e-3);
+
+ // Spline IK fits joints along a 4-point curve with and without stretch.
+ const curve = [[0, 0, 0], [1.5, 1, 0], [3, 1, 0], [4.5, 0, 0]];
+ const splinePose = createSkeletonPose({
+ rig: tentacleRig,
+ ik: [{ type: 'spline', chain: ['b0', 'b1', 'b2', 'b3', 'tip'], curve, stretch: true }],
+ });
+ splinePose.apply(0);
+ assert.equal(splinePose.ikResults[0].reached, true);
+ assertClose(splinePose.jointWorld('tip').position, [4.5, 0, 0], 1e-2);
+
+ const unstretchedSpline = createSkeletonPose({
+ rig: tentacleRig,
+ ik: [{ type: 'spline', root: 'b0', end: 'tip', curve: () => [[0, 0, 0], [6, 0, 0]], stretch: false, weight: 0.5 }],
+ });
+ unstretchedSpline.apply(0);
+ assertClose(unstretchedSpline.jointWorld('tip').position, [4, 0, 0], 1e-2);
+
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'chain', chain: ['b0'], target: [1, 0, 0] }] }), /chain must list 2 to 64 joints/);
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'chain', target: [1, 0, 0] }] }), /needs chain/);
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'chain', root: 'b0', end: 'tip', target: [1, 0, 0], poleAngle: 200 }] }), /poleAngle/);
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'chain', root: 'b0', end: 'tip', target: [1, 0, 0], stretch: 2 }] }), /stretch/);
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'chain', root: 'b0', end: 'tip', target: [1, 0, 0], iterations: 0 }] }), /iterations/);
+ assert.throws(() => createSkeletonPose({ rig: tentacleRig, ik: [{ type: 'spline', root: 'b0', end: 'tip', curve: [[0, 0, 0]] }] }), /curve must be 2 to 64/);
+});