diff --git a/docs/goal-ai-map.md b/docs/goal-ai-map.md
index 660e0be..56d7ca5 100644
--- a/docs/goal-ai-map.md
+++ b/docs/goal-ai-map.md
@@ -258,7 +258,14 @@ gives up is an authored elbow direction. Where that swivel leaves the cone, the
the cone and the twist limits, the feasible swivel range of Tolani, Goswami and Badler (2000) (fact 8). When no
swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus twist past its range) is
least, with swing and twist clamped to the limits: at the edge of the feasible set that is the last feasible swivel,
-so a goal crossing the edge moves the targets continuously (the zero-twist clamp it replaces jumped 1.4 rad there). Reach under gravity lands short by PD sag (fact 9); that is its own cut.
+so a goal crossing the edge moves the targets continuously (the zero-twist clamp it replaces jumped 1.4 rad there).
+That choice is stateless, and mirrored swivels tie under it (at the shoulder's sagittal plane, unreached or reached),
+so it must jump somewhere on the tie set. Ruling `ik-swivel-temporal-coherence` makes each `ArmChain` the arm's solver
+across ticks: it holds the previous swivel's basin, takes the stateless choice only when that is better by
+`BasinMargin` (less violation, or less twist when both are feasible), and turns the swivel no faster than
+`SwivelRate`; the first solve after construction or `Reset` is stateless. Both constants are placeholders. What it
+gives up: IK is no longer a pure function of the goal. Not covered: near a half-turn swing the swing-twist split in
+the clamp is singular, so the clamped target can still jump while the held swivel moves smoothly. Reach under gravity lands short by PD sag (fact 9); that is its own cut.
**Goal-target rationale.** A target is tracked by percept Id (fact 11), selection scores (goal, percept) pairs,
and a retarget inside the goal waits the deliberate latency but not the dwell, held only by the commitment
diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
index 004057b..facdba0 100644
--- a/src/Lodur.Core/Actor.cs
+++ b/src/Lodur.Core/Actor.cs
@@ -93,7 +93,7 @@ namespace Lodur
if (_layered)
{
- _rig = new OrientRig(body!, brain);
+ _rig = new OrientRig(body!, brain, tickSeconds);
}
if (physiology != null && !physiology.TryBind())
diff --git a/src/Lodur.Core/Ik.cs b/src/Lodur.Core/Ik.cs
index f8790c0..db7482d 100644
--- a/src/Lodur.Core/Ik.cs
+++ b/src/Lodur.Core/Ik.cs
@@ -91,12 +91,39 @@ namespace Lodur
/// Tolani, Goswami and Badler 2000). When no swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus
/// twist past its limits) is least, and its swing and twist clamp to the limits; as a goal leaves the feasible set that swivel is the
/// last feasible one, so the targets move continuously across the edge.
+ ///
+ /// That rule alone is the stateless rule, and mirrored options tie under it: where two swivels are equally good it must jump from one to
+ /// the other somewhere on the tie set. So a chain is one arm's solver across ticks and carries the arm's previous swivel (ruling
+ /// lodur:ruling:ik-swivel-temporal-coherence): each solve stays in the basin of the previous swivel and moves to the stateless choice only
+ /// when that is better by , never turning the swivel faster than . Better means less limit
+ /// violation, or, both swivels being feasible, less twist. The first solve after construction or is the stateless rule.
+ /// Identical goals can therefore give different targets depending on history; the same history gives the same targets.
+ ///
///
public sealed class ArmChain
{
private readonly Quat _parentRestInverse, _frame, _frameInverse;
private readonly IkVec _parentCentre, _shoulderAnchor, _upper, _lower, _elbowAxis, _twistAxis;
private readonly float _flexSign, _flexLo, _flexHi, _cone, _twistLo, _twistHi, _coneSin2, _coneSinHalf, _coneCosHalf;
+ private readonly float _maxSwivelStep;
+
+ // The previous solve's shoulder target before clamping, whose swivel the next solve starts from; none after construction or Reset.
+ private Quat _previous;
+ private bool _hasPrevious;
+
+ ///
+ /// Radians of limit violation, or of twist when both swivels are feasible, by which the stateless choice must beat the held swivel's
+ /// basin before the arm leaves it. Placeholder: no measured pose cost sets it. It must sit far above the solver's resolution (about
+ /// 1e-5 rad), so noise cannot flip a tie, and well below the 1.0-1.57 rad between the mirrored basins Soul measured, so a clearly
+ /// better basin is taken.
+ ///
+ public const double BasinMargin = 0.05;
+
+ ///
+ /// The fastest the swivel turns, in radians per second. Placeholder: of the order of a deliberate, unhurried shoulder rotation, not a
+ /// measured one.
+ ///
+ public const float SwivelRate = 3f;
// Swivel search: steps of Pi / SwivelSteps outward from the zero-twist swivel, then bisection to the feasible boundary. When none is
// feasible, the least-violating of LeastSteps steps round the circle, refined by golden section.
@@ -109,8 +136,14 @@ namespace Lodur
// Small against the violation's slope of about one, so it barely moves the least-violating swivel.
private const double TwistPreference = 1e-5;
- private ArmChain(BodyPlan plan, Side side)
+ private ArmChain(BodyPlan plan, Side side, double tickSeconds)
{
+ if (!(double.IsFinite(tickSeconds) && tickSeconds > 0.0))
+ {
+ throw new ArgumentException($"the tick length {tickSeconds} s is not finite and positive.");
+ }
+
+ _maxSwivelStep = (float)(SwivelRate * tickSeconds);
var si = plan.JointIndex("Shoulder", side);
var ei = plan.JointIndex("Elbow", side);
var wi = plan.JointIndex("Wrist", side);
@@ -164,7 +197,14 @@ namespace Lodur
}
/// Finds the shoulder, elbow and wrist of by label; if the plan has no such arm.
- public static ArmChain Of(BodyPlan plan, Side side) => new ArmChain(plan, side);
+ /// One chain is one arm's solver across ticks of , which sets how far the swivel turns per solve.
+ public static ArmChain Of(BodyPlan plan, Side side, double tickSeconds) => new ArmChain(plan, side, tickSeconds);
+
+ /// Forgets the previous swivel: the next solve uses the stateless rule.
+ public void Reset() => _hasPrevious = false;
+
+ /// The last solve's shoulder target before clamping, whose swivel the next solve holds (identity before any solve); tests read it.
+ internal Quat Held => _hasPrevious ? _previous : Quat.Identity;
/// The plan's joint ordinals, where the caller writes the two targets.
public int ShoulderJoint { get; }
@@ -185,7 +225,8 @@ namespace Lodur
///
/// Targets that put the wrist anchor on the world point (tx, ty, tz), given the parent part's world rotation and position.
/// Returns false when the point was out of reach or a limit clamped; the targets are then the limits-clamped pose of the swivel that
- /// violates the limits least, continuous with the reached targets at the edge of the feasible set.
+ /// violates the limits least, continuous with the reached targets at the edge of the feasible set, or, while the swivel turns between
+ /// basins, the clamped pose of the swivel on its way. One call is one tick of the arm's history.
///
public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat shoulder, out Quat elbow)
{
@@ -213,11 +254,24 @@ namespace Lodur
// The target is linear in the half-angle of the swivel: Local(phi) = cos(phi / 2) A + sin(phi / 2) B.
var a = _frameInverse * arc * _frame;
var b = _frameInverse * (new Quat(vHat.X, vHat.Y, vHat.Z, 0f) * arc) * _frame;
- var local = Local(a, b, zeroTwist);
- if (!InsideCone(local) && !(SomeSwivelInsideCone(a, b) && NearestFeasible(a, b, zeroTwist, out local)))
+ var phi = Stateless(a, b, zeroTwist, out var clamp);
+ if (_hasPrevious)
{
- // No swivel is feasible: the least-violating one, its swing and twist clamped to the limits.
- local = ClampToLimits(Local(a, b, LeastViolating(a, b, zeroTwist)));
+ // The previous target's swivel on this goal's swivel circle: a and b are orthonormal, so the nearest point is a projection.
+ var held = 2f * MathF.Atan2(Dot(_previous, b), Dot(_previous, a));
+ var basin = BasinOptimum(a, b, zeroTwist, held);
+ var want = ClearlyBetter(a, b, phi, basin) ? phi : basin;
+ phi = held + Ik.Clamp(Wrap(want - held), -_maxSwivelStep, _maxSwivelStep);
+ clamp = !Feasible(Local(a, b, phi));
+ }
+
+ var local = Local(a, b, phi);
+ _previous = local;
+ _hasPrevious = true;
+ if (clamp)
+ {
+ // Infeasible: swing and twist clamped to the limits.
+ local = ClampToLimits(local);
reached = false;
}
@@ -226,6 +280,67 @@ namespace Lodur
return reached;
}
+ // The stateless rule: zero twist inside the cone, else the nearest feasible swivel, else the least-violating one (clamp set).
+ private float Stateless(in Quat a, in Quat b, float zeroTwist, out bool clamp)
+ {
+ clamp = false;
+ if (InsideCone(Local(a, b, zeroTwist))) return zeroTwist;
+ if (SomeSwivelInsideCone(a, b) && NearestFeasible(a, b, zeroTwist, out var feasible)) return feasible;
+ clamp = true;
+ return LeastViolating(a, b, zeroTwist);
+ }
+
+ // The best swivel of the held swivel's basin. When some swivel is feasible: from the held swivel, or the feasible one nearest it,
+ // toward zero twist while feasible. When none is: the least violation downhill from the held swivel.
+ private float BasinOptimum(in Quat a, in Quat b, float zeroTwist, float held)
+ {
+ if (SomeSwivelInsideCone(a, b))
+ {
+ if (Feasible(Local(a, b, held))) return TowardZeroTwist(a, b, zeroTwist, held);
+ if (NearestFeasible(a, b, held, out var start)) return TowardZeroTwist(a, b, zeroTwist, start);
+ }
+
+ return LocalLeastViolating(a, b, held);
+ }
+
+ // From the feasible swivel start toward the zero-twist swivel, the way twist shrinks: the zero-twist swivel if every step there is
+ // feasible, else the feasible boundary on the way.
+ private float TowardZeroTwist(in Quat a, in Quat b, float zeroTwist, float start)
+ {
+ var d = Wrap(start - zeroTwist);
+ if (d == 0f) return zeroTwist;
+ var dir = d > 0f ? -1f : 1f;
+ var dist = MathF.Abs(d);
+ const float step = MathF.PI / SwivelSteps;
+ var inside = start;
+ for (var k = 1; k <= SwivelSteps; k++)
+ {
+ var t = MathF.Min(k * step, dist);
+ var phi = start + dir * t;
+ if (!Feasible(Local(a, b, phi))) return Boundary(a, b, inside, phi);
+ if (t >= dist) return zeroTwist;
+ inside = phi;
+ }
+
+ return inside;
+ }
+
+ // Whether swivel x beats swivel y by the margin: less violation, or, both feasible, less twist.
+ private bool ClearlyBetter(in Quat a, in Quat b, float x, float y)
+ {
+ if (Violation(a, b, x) < Violation(a, b, y) - BasinMargin) return true;
+ var lx = Local(a, b, x);
+ var ly = Local(a, b, y);
+ return Feasible(lx) && Feasible(ly) && MathF.Abs(Twist(lx)) < MathF.Abs(Twist(ly)) - (float)BasinMargin;
+ }
+
+ private static float Twist(in Quat local) => 2f * MathF.Atan2(local.Z, local.W);
+
+ private static float Dot(in Quat p, in Quat q) => p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W;
+
+ // An angle difference into [-pi, pi]: the swivel's period is a full turn.
+ private static float Wrap(float x) => x - 2f * MathF.PI * MathF.Round(x / (2f * MathF.PI));
+
// The shoulder target in the joint frame for the swivel phi, with w >= 0.
private static Quat Local(in Quat a, in Quat b, float phi)
{
@@ -251,15 +366,28 @@ namespace Lodur
private bool Feasible(in Quat local)
{
if (!InsideCone(local)) return false;
- var twist = 2f * MathF.Atan2(local.Z, local.W);
+ var twist = Twist(local);
return twist >= _twistLo && twist <= _twistHi;
}
+ // Bisection between a feasible and an infeasible swivel to the boundary; the feasible end.
+ private float Boundary(in Quat a, in Quat b, float inside, float outside)
+ {
+ for (var i = 0; i < SwivelBisections; i++)
+ {
+ var mid = 0.5f * (inside + outside);
+ if (Feasible(Local(a, b, mid))) inside = mid;
+ else outside = mid;
+ }
+
+ return inside;
+ }
+
// The feasible swivel nearest phi0: step outward both ways, and at the first step that lands inside, bisect back to the boundary;
// of the two sides, the one with the smaller twist. False when no swivel is feasible.
- private bool NearestFeasible(in Quat a, in Quat b, float phi0, out Quat local)
+ private bool NearestFeasible(in Quat a, in Quat b, float phi0, out float swivel)
{
- local = default;
+ swivel = 0f;
const float step = MathF.PI / SwivelSteps;
for (var k = 1; k <= SwivelSteps; k++)
{
@@ -269,21 +397,12 @@ namespace Lodur
{
var phi = phi0 + sign * k * step;
if (!Feasible(Local(a, b, phi))) continue;
- var inside = phi;
- var outside = phi0 + sign * (k - 1) * step;
- for (var i = 0; i < SwivelBisections; i++)
- {
- var mid = 0.5f * (inside + outside);
- if (Feasible(Local(a, b, mid))) inside = mid;
- else outside = mid;
- }
-
- var candidate = Local(a, b, inside);
- var twist = MathF.Abs(2f * MathF.Atan2(candidate.Z, candidate.W));
+ var inside = Boundary(a, b, phi, phi0 + sign * (k - 1) * step);
+ var twist = MathF.Abs(Twist(Local(a, b, inside)));
if (twist < bestTwist)
{
bestTwist = twist;
- local = candidate;
+ swivel = inside;
found = true;
}
}
@@ -334,9 +453,38 @@ namespace Lodur
}
}
+ return Golden(a, b, best - step, best + step);
+ }
+
+ // The least-violating swivel of the held swivel's basin: downhill in steps of a LeastSteps-th of the circle while the violation
+ // falls, then golden section within a step either side.
+ private float LocalLeastViolating(in Quat a, in Quat b, float held)
+ {
+ const double step = 2.0 * Math.PI / LeastSteps;
+ var best = (double)held;
+ var least = Violation(a, b, best);
+ var up = Violation(a, b, best + step);
+ var down = Violation(a, b, best - step);
+ if (up < least || down < least)
+ {
+ var dir = up < down ? 1.0 : -1.0;
+ for (var k = 0; k < LeastSteps; k++)
+ {
+ var next = best + dir * step;
+ var v = Violation(a, b, next);
+ if (v >= least) break;
+ best = next;
+ least = v;
+ }
+ }
+
+ return Golden(a, b, best - step, best + step);
+ }
+
+ // Golden-section search for the least violation on [lo, hi].
+ private float Golden(in Quat a, in Quat b, double lo, double hi)
+ {
const double g = 0.6180339887498949;
- var lo = best - step;
- var hi = best + step;
var p = hi - g * (hi - lo);
var q = lo + g * (hi - lo);
var fp = Violation(a, b, p);
diff --git a/src/Lodur.Core/Orient.cs b/src/Lodur.Core/Orient.cs
index bbaff41..b77cb0f 100644
--- a/src/Lodur.Core/Orient.cs
+++ b/src/Lodur.Core/Orient.cs
@@ -187,7 +187,8 @@ namespace Lodur
///
/// The solvers an Actor's brain needs, resolved once from the body plan: the look chain when any goal looks, wards off or recoils (they read
/// the head), an arm chain for each side an Arms layer can use. A chain the plan cannot give refuses at construction, naming the goal, so a
- /// plan the closed form cannot solve fails at spawn and never mid-tick. Holds no per-tick state, and solving allocates nothing.
+ /// plan the closed form cannot solve fails at spawn and never mid-tick. The arm chains are the Actor's arms across ticks and hold each
+ /// arm's swivel from tick to tick (an arm not driven on a tick keeps its last one); the rig holds nothing else, and solving allocates nothing.
///
internal sealed class OrientRig
{
@@ -196,7 +197,7 @@ namespace Lodur
private readonly ArmChain? _left;
private readonly ArmChain? _right;
- public OrientRig(BodyPlan plan, Brain brain)
+ public OrientRig(BodyPlan plan, Brain brain, double tickSeconds)
{
_plan = plan;
foreach (var goal in brain.Goals)
@@ -223,22 +224,22 @@ namespace Lodur
{
if (_left == null && arms.Side != ArmSide.Right)
{
- _left = Arm(plan, goal.Id, Side.Left);
+ _left = Arm(plan, goal.Id, Side.Left, tickSeconds);
}
if (_right == null && arms.Side != ArmSide.Left)
{
- _right = Arm(plan, goal.Id, Side.Right);
+ _right = Arm(plan, goal.Id, Side.Right, tickSeconds);
}
}
}
}
- private static ArmChain Arm(BodyPlan plan, string goal, Side side)
+ private static ArmChain Arm(BodyPlan plan, string goal, Side side, double tickSeconds)
{
try
{
- return ArmChain.Of(plan, side);
+ return ArmChain.Of(plan, side, tickSeconds);
}
catch (ArgumentException e)
{
diff --git a/tests/Lodur.Core.Tests/IkTests.cs b/tests/Lodur.Core.Tests/IkTests.cs
index 22c24cc..b51088f 100644
--- a/tests/Lodur.Core.Tests/IkTests.cs
+++ b/tests/Lodur.Core.Tests/IkTests.cs
@@ -6,6 +6,9 @@ namespace Lodur.Core.Tests;
public sealed class IkTests
{
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
+
+ // The tick the chains are built for; it sets the swivel step, SwivelRate * Dt.
+ private const double Dt = 0.01;
private readonly ITestOutputHelper _output;
public IkTests(ITestOutputHelper output) => _output = output;
@@ -74,10 +77,12 @@ public sealed class IkTests
[InlineData(Side.Right)]
public void Arm_solve_lands_the_wrist_by_forward_kinematics(Side side)
{
- var arm = ArmChain.Of(Plan, side);
+ var arm = ArmChain.Of(Plan, side, Dt);
var reachedCount = 0;
foreach (var (rot, pos, target) in Grid(arm, 7 + (int)side, 600))
{
+ // Independent goals, not a path: each is the stateless rule.
+ arm.Reset();
if (!arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out var eq)) continue;
reachedCount++;
var wrist = Wrist(arm, rot, pos, sq, eq);
@@ -92,11 +97,12 @@ public sealed class IkTests
[InlineData(Side.Right)]
public void Arm_solve_twists_the_shoulder_only_where_zero_twist_would_leave_the_cone(Side side)
{
- var arm = ArmChain.Of(Plan, side);
+ var arm = ArmChain.Of(Plan, side, Dt);
var joint = Plan.Joints[arm.ShoulderJoint];
var (n, reached, twisted) = (0, 0, 0);
foreach (var (rot, pos, target) in Grid(arm, 21 + (int)side, 600))
{
+ arm.Reset();
var ok = arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out _);
var swing = 2f * MathF.Asin(MathF.Min(1f, MathF.Sqrt(sq.X * sq.X + sq.Y * sq.Y)));
var twist = 2f * MathF.Atan2(sq.Z, sq.W);
@@ -123,7 +129,7 @@ public sealed class IkTests
public void A_wrist_goal_the_zero_twist_swivel_cannot_reach_is_reached_by_twisting_inside_the_limits()
{
// The left ward-off wrist goal for a sound at head height, ahead and to the left: zero twist saturates the cone 20 cm short.
- var arm = ArmChain.Of(Plan, Side.Left);
+ var arm = ArmChain.Of(Plan, Side.Left, Dt);
var joint = Plan.Joints[arm.ShoulderJoint];
var centre = Plan.Parts[arm.ParentPart].Position;
var goal = (0.2988f, 1.74f, 0.2605f);
@@ -141,7 +147,7 @@ public sealed class IkTests
{
// Two stretches of a circle about the shoulder where a goal leaves the feasible set: past the edge no swivel keeps both swing and
// twist inside the limits. Each stretch is 2000 steps of about 0.02 mm.
- var arm = ArmChain.Of(Plan, side);
+ var arm = ArmChain.Of(Plan, side, Dt);
var centre = Plan.Parts[arm.ParentPart].Position;
var s = arm.ShoulderAnchor;
var (worstTurn, worstMove) = (0f, 0f);
@@ -150,6 +156,8 @@ public sealed class IkTests
const int steps = 2000;
var crossings = 0;
var (lastReached, lastShoulder, lastWrist) = (false, Quat.Identity, (0f, 0f, 0f));
+ // Each stretch is its own path.
+ arm.Reset();
for (var i = 0; i <= steps; i++)
{
var th = from + (to - from) * i / steps;
@@ -182,7 +190,7 @@ public sealed class IkTests
[Fact]
public void Out_of_reach_points_the_straight_arm_at_the_target_and_reports_not_reached()
{
- var arm = ArmChain.Of(Plan, Side.Right);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
var s = arm.ShoulderAnchor;
var centre = Plan.Parts[arm.ParentPart].Position;
var dirs = new[] { (0f, -0.5f, 0.87f), (-0.4f, -0.6f, 0.7f) };
@@ -191,6 +199,7 @@ public sealed class IkTests
var l = Len(raw);
var dir = (raw.Item1 / l, raw.Item2 / l, raw.Item3 / l);
var target = (s.X + dir.Item1 * 2f, s.Y + dir.Item2 * 2f, s.Z + dir.Item3 * 2f);
+ arm.Reset();
var reached = arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, target.Item1, target.Item2, target.Item3, out var sq, out var eq);
Assert.False(reached);
var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
@@ -201,13 +210,14 @@ public sealed class IkTests
}
// The same direction well inside reach is reached.
+ arm.Reset();
Assert.True(arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, s.X, s.Y, s.Z + 0.4f, out _, out _));
}
[Fact]
public void Limits_clamp_swing_flex_and_look()
{
- var arm = ArmChain.Of(Plan, Side.Right);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
var s = arm.ShoulderAnchor;
var c = Plan.Parts[arm.ParentPart].Position;
var cone = Plan.Joints[arm.ShoulderJoint].Cone;
@@ -219,10 +229,12 @@ public sealed class IkTests
Assert.True(ZTwist(up) < 1e-5f);
// Near the shoulder the hinge would have to fold past its range.
+ arm.Reset();
Assert.False(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.1f, s.Z + 0.1f, out _, out var folded));
Assert.Equal(lo, 2f * MathF.Atan2(folded.Z, folded.W), 1e-4f);
// A bend inside the range is not a clamp.
+ arm.Reset();
Assert.True(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.25f, s.Z + 0.25f, out _, out var bent));
var flex = 2f * MathF.Atan2(bent.Z, bent.W);
Assert.InRange(flex, lo + 0.05f, hi - 0.05f);
@@ -258,12 +270,14 @@ public sealed class IkTests
[Fact]
public void Left_and_right_mirror()
{
- var left = ArmChain.Of(Plan, Side.Left);
- var right = ArmChain.Of(Plan, Side.Right);
+ var left = ArmChain.Of(Plan, Side.Left, Dt);
+ var right = ArmChain.Of(Plan, Side.Right, Dt);
var c = Plan.Parts[right.ParentPart].Position;
var n = 0;
foreach (var (_, _, target) in Grid(right, 5, 300))
{
+ right.Reset();
+ left.Reset();
var rReached = right.Solve(Quat.Identity, c.X, c.Y, c.Z, target.X, target.Y, target.Z, out var rs, out var re);
var lReached = left.Solve(Quat.Identity, c.X, c.Y, c.Z, -target.X, target.Y, target.Z, out var ls, out var le);
Assert.Equal(rReached, lReached);
@@ -311,10 +325,220 @@ public sealed class IkTests
Assert.Equal(400, aimed);
}
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
+ private static float Swing(Quat q) => 2f * MathF.Atan2(MathF.Sqrt(q.X * q.X + q.Y * q.Y), MathF.Sqrt(q.Z * q.Z + q.W * q.W));
+
+ // Tie lines at the shoulder's sagittal plane (goal relative to the shoulder (dx, y, z)), where two mirrored swivels tie under the
+ // stateless rule (Soul s3 on cut-lodur-orient-goals). The first four are unreached throughout; (-0.224, -0.2) is reached beyond 4 mm
+ // either side; (-0.25, -0.25) is reached throughout, two feasible intervals tying.
+ private static readonly (float Y, float Z)[] TieLines = { (0.12f, -0.4f), (0.2f, -0.2f), (0.25f, 0f), (0.3f, -0.1f), (-0.224f, -0.2f), (-0.25f, -0.25f) };
+
+ ///
+ /// Walks one chain along goals, one solve per tick, from a fresh state: the largest per-tick turn of the shoulder target and the largest
+ /// swing of the held (unclamped) target. With the chain is reset before every solve: the stateless argmin,
+ /// the claimed mutant.
+ ///
+ private static (float Turn, float HeldSwing) Walk(ArmChain arm, IEnumerable<(float X, float Y, float Z)> goals, bool stateless, Quat[]? record = null)
+ {
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var (worst, swing, last, i) = (0f, 0f, Quat.Identity, 0);
+ arm.Reset();
+ foreach (var g in goals)
+ {
+ if (stateless) arm.Reset();
+ arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var sq, out _);
+ if (i > 0) worst = MathF.Max(worst, Turn(sq, last));
+ swing = MathF.Max(swing, Swing(arm.Held));
+ if (record != null) record[i] = sq;
+ last = sq;
+ i++;
+ }
+
+ return (worst, swing);
+ }
+
+ private static IEnumerable<(float X, float Y, float Z)> Line((float X, float Y, float Z) s, float y, float z, float sign, int from, int to, float step)
+ {
+ for (var i = from; i <= to; i++) yield return (s.X + sign * i * step, s.Y + y, s.Z + z);
+ }
+
+ // deterministic-bound-margin for the held swivel's per-tick turn at Dt = 0.01 s (a 0.03 rad swivel step): the geometric mean of the
+ // shipped worst and the least claimed mutant, the stateless argmin (the chain reset every tick). Shipped worst over
+ // the tie lines, the random jumps and the basin switch: 0.0333 rad. Least mutant: 0.5039 rad (a random jump; the tie lines least is 0.9995).
+ // Bound sqrt(0.0333 * 0.5039) = 0.129.
+ private const float HeldTurnBound = 0.129f;
+
+ [Fact]
+ public void Across_a_tie_line_the_arm_keeps_its_swivel_and_the_arms_mirror()
+ {
+ var left = ArmChain.Of(Plan, Side.Left, Dt);
+ var right = ArmChain.Of(Plan, Side.Right, Dt);
+ var (worst, mutant) = (0f, float.MaxValue);
+ var (lq, rq) = (new Quat[101], new Quat[101]);
+ foreach (var (y, z) in TieLines)
+ {
+ // dx from -10 to +10 mm in 0.2 mm ticks; the left arm walks the mirrored path.
+ var held = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), false, rq).Turn;
+ Walk(left, Line(left.ShoulderAnchor, y, z, -1f, -50, 50, 0.0002f), false, lq);
+ var jump = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), true).Turn;
+ _output.WriteLine($"tie line ({y}, {z}): held worst {held:F4} rad per tick, stateless {jump:F4}");
+ (worst, mutant) = (MathF.Max(worst, held), MathF.Min(mutant, jump));
+ for (var i = 0; i < 101; i++)
+ {
+ Assert.Equal(rq[i].X, lq[i].X, 1e-5f);
+ Assert.Equal(-rq[i].Y, lq[i].Y, 1e-5f);
+ Assert.Equal(-rq[i].Z, lq[i].Z, 1e-5f);
+ Assert.Equal(rq[i].W, lq[i].W, 1e-5f);
+ }
+ }
+
+ _output.WriteLine($"worst held {worst:F4}, least stateless worst {mutant:F4}");
+ // Tripwire: every line still ties under the stateless rule, so the bound still tests a tie.
+ Assert.True(mutant > 0.9f, $"a tie line no longer ties: the stateless rule turns only {mutant} rad");
+ Assert.True(worst < HeldTurnBound, $"the shoulder target turned {worst} rad in one tick across a tie");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void The_stateless_jumps_of_random_segments_are_held(Side side)
+ {
+ // Soul's probe: random segments about the shoulder walked in 0.4 mm steps; each step the stateless rule turns over 0.5 rad is
+ // bisected to a gap under 2 microns, where it persists. The held chain walks 2 mm up to the near side, across the gap in one
+ // tick, and 2 mm on.
+ // Excluded and counted: jumps where the held target swings past HalfTurnSwing. Near a half-turn swing the swing-twist split is
+ // singular, so the clamp to the limits turns the target by up to 3 rad for a swivel step of 0.03 rad: the held swivel is
+ // continuous there and the clamped target is not. That is the clamp's defect, outside the temporal-coherence ruling.
+ const float HalfTurnSwing = 3.0f;
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var rng = new Random(side == Side.Left ? 5 : 6);
+ (float X, float Y, float Z) Pt()
+ {
+ double dx, dy, dz, l;
+ do { dx = rng.NextDouble() * 2 - 1; dy = rng.NextDouble() * 2 - 1; dz = rng.NextDouble() * 2 - 1; l = Math.Sqrt(dx * dx + dy * dy + dz * dz); }
+ while (l is < 0.05 or > 1.0);
+ var r = (float)(0.05 + rng.NextDouble() * 0.7);
+ return (s.X + (float)(dx / l) * r, s.Y + (float)(dy / l) * r, s.Z + (float)(dz / l) * r);
+ }
+
+ Quat Fresh((float X, float Y, float Z) g)
+ {
+ arm.Reset();
+ arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var q, out _);
+ return q;
+ }
+
+ static (float X, float Y, float Z) Lerp((float X, float Y, float Z) a, (float X, float Y, float Z) b, float u) => (a.X + (b.X - a.X) * u, a.Y + (b.Y - a.Y) * u, a.Z + (b.Z - a.Z) * u);
+ var (found, held, singular, worst, mutant) = (0, 0, 0, 0f, float.MaxValue);
+ var path = new (float X, float Y, float Z)[12];
+ for (var k = 0; k < 400 && found < 40; k++)
+ {
+ var a = Pt();
+ var b = Pt();
+ var steps = (int)(Len(Sub(b, a)) / 0.0004f) + 1;
+ var prev = Fresh(a);
+ for (var i = 1; i <= steps; i++)
+ {
+ var q1 = Fresh(Lerp(a, b, (float)i / steps));
+ if (Turn(q1, prev) > 0.5f)
+ {
+ found++;
+ var (lo, hi, qlo, qhi) = (Lerp(a, b, (float)(i - 1) / steps), Lerp(a, b, (float)i / steps), prev, q1);
+ for (var it = 0; it < 40 && Len(Sub(hi, lo)) > 2e-6f; it++)
+ {
+ var mid = Lerp(lo, hi, 0.5f);
+ var qm = Fresh(mid);
+ if (Turn(qm, qlo) >= Turn(qm, qhi)) (hi, qhi) = (mid, qm);
+ else (lo, qlo) = (mid, qm);
+ }
+
+ Assert.True(Turn(qlo, qhi) > 0.5f, $"a stateless jump vanished on bisection: {Turn(qlo, qhi)} rad");
+ var u = Sub(b, a);
+ var step = 0.0004f / Len(u);
+ for (var j = 0; j < 6; j++) path[j] = Lerp(lo, Add(lo, u), (j - 5) * step);
+ for (var j = 0; j < 6; j++) path[6 + j] = Lerp(hi, Add(hi, u), j * step);
+ var walk = Walk(arm, path, false);
+ if (walk.HeldSwing > HalfTurnSwing)
+ {
+ singular++;
+ }
+ else
+ {
+ held++;
+ worst = MathF.Max(worst, walk.Turn);
+ mutant = MathF.Min(mutant, Walk(arm, path, true).Turn);
+ }
+ }
+
+ prev = q1;
+ }
+ }
+
+ _output.WriteLine($"{side}: {found} stateless jumps, {held} held (worst {worst:F4} rad per tick, least stateless worst {mutant:F4}), {singular} at the half-turn swing");
+ Assert.True(found >= 40, $"only {found} stateless jumps found; the probe no longer finds the ties");
+ Assert.True(held >= 25, $"only {held} jumps away from the half-turn swing; the bound no longer tests many");
+ Assert.True(worst < HeldTurnBound, $"the shoulder target turned {worst} rad in one tick at a stateless jump");
+ }
+
+ [Fact]
+ public void A_clearly_better_basin_is_taken_at_the_swivel_rate_and_reset_restores_the_stateless_rule()
+ {
+ // The feasible tie: goal (dx, -0.25, -0.25) from the shoulder is reached throughout, by two mirrored feasible swivels that tie at
+ // dx 0. From dx -10 mm in 0.2 mm ticks the arm holds its basin past the tie; once the stateless swivel's twist is smaller by the
+ // margin it turns there, no faster than the swivel step.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var fresh = ArmChain.Of(Plan, Side.Right, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ Quat Solve(ArmChain chain, float dx, out bool reached)
+ {
+ reached = chain.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X + dx, s.Y - 0.25f, s.Z - 0.25f, out var q, out _);
+ return q;
+ }
+
+ var (worst, last, heldAt, switchedAt) = (0f, Quat.Identity, float.NaN, float.NaN);
+ for (var i = -50; i <= 1000; i++)
+ {
+ var dx = i * 0.0002f;
+ var q = Solve(arm, dx, out _);
+ fresh.Reset();
+ var stateless = Solve(fresh, dx, out _);
+ if (i > -50) worst = MathF.Max(worst, Turn(q, last));
+ if (i == 10)
+ {
+ // 2 mm past the tie the arm is still in its basin, the other side of the stateless choice.
+ heldAt = Turn(q, stateless);
+ }
+
+ if (float.IsNaN(switchedAt) && i > 10 && Turn(q, stateless) < 0.01f) switchedAt = dx;
+ last = q;
+ }
+
+ _output.WriteLine($"2 mm past the tie: {heldAt:F3} rad from the stateless target; switched by dx {switchedAt * 1000f:F1} mm; worst {worst:F4} rad per tick");
+ Assert.True(heldAt > 1f, $"2 mm past the tie the arm left its basin ({heldAt} rad from the stateless target)");
+ Assert.False(float.IsNaN(switchedAt), "the arm never took the clearly better basin");
+ Assert.True(worst < HeldTurnBound, $"the shoulder target turned {worst} rad in one tick");
+
+ // Reset forgets the swivel: the next solve is the stateless rule, bit for bit, where the held arm differs.
+ arm.Reset();
+ Solve(arm, -0.01f, out _);
+ var held = Solve(arm, 0.002f, out _);
+ arm.Reset();
+ var reset = Solve(arm, 0.002f, out var r1);
+ fresh.Reset();
+ var expected = Solve(fresh, 0.002f, out var r2);
+ Assert.Equal(expected, reset);
+ Assert.Equal(r2, r1);
+ Assert.True(Turn(held, reset) > 1f, "the held arm already matched the stateless target, so the reset proves nothing");
+ }
+
[Fact]
public void Solving_allocates_nothing()
{
- var arm = ArmChain.Of(Plan, Side.Right);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
var look = LookChain.Of(Plan);
var s = arm.ShoulderAnchor;
var rot = Quat.FromAxisAngle(0f, 1f, 0f, 0.2f);
@@ -343,7 +567,7 @@ public sealed class IkTests
{
var parts = new[] { new PartDef("A", Side.Center, PartShape.Sphere, (0.1f, 0f, 0f), (0f, 0f, 0f), Quat.Identity, 1f, 1f, 0f) };
var bare = new BodyPlan(parts, Array.Empty(), Array.Empty());
- Assert.Throws(() => ArmChain.Of(bare, Side.Left));
+ Assert.Throws(() => ArmChain.Of(bare, Side.Left, Dt));
Assert.Throws(() => LookChain.Of(bare));
}
}
diff --git a/tests/Lodur.Core.Tests/OrientTests.cs b/tests/Lodur.Core.Tests/OrientTests.cs
index 5de221f..5b684b9 100644
--- a/tests/Lodur.Core.Tests/OrientTests.cs
+++ b/tests/Lodur.Core.Tests/OrientTests.cs
@@ -69,7 +69,7 @@ public sealed class OrientTests
private static Brain BrainOf(PoseBehaviour b) => new() { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
- private static OrientRig RigOf(PoseBehaviour b) => new(Plan, BrainOf(b));
+ private static OrientRig RigOf(PoseBehaviour b) => new(Plan, BrainOf(b), Dt);
private static Percept At((float X, float Y, float Z) p, ulong id = 1) => new(id, Thing, p.X, p.Y, p.Z, 1.0, 0.0);
@@ -167,7 +167,7 @@ public sealed class OrientTests
var t = parts[Torso];
foreach (var s in new[] { Side.Left, Side.Right })
{
- var arm = ArmChain.Of(Plan, s);
+ var arm = ArmChain.Of(Plan, s, Dt);
var used = side == ArmSide.Both || (side == ArmSide.Left) == (s == Side.Left);
if (used)
{
@@ -220,8 +220,8 @@ public sealed class OrientTests
var meet = Add(head, (u.X * distance, u.Y * distance, u.Z * distance));
var t = parts[Torso];
var leftAxis = Rot(t.Rotation * Plan.Parts[Torso].Rotation.Conjugate(), (1f, 0f, 0f));
- var wristL = Wrist(ArmChain.Of(Plan, Side.Left), t, Unflinch(got, Side.Left, out var elL), elL);
- var wristR = Wrist(ArmChain.Of(Plan, Side.Right), t, Unflinch(got, Side.Right, out var elR), elR);
+ var wristL = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(got, Side.Left, out var elL), elL);
+ var wristR = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(got, Side.Right, out var elR), elR);
Assert.True(Len(Sub(wristL, meet)) < spread + 1e-3f, $"left wrist {Len(Sub(wristL, meet))} m from the meeting point");
Assert.True(Len(Sub(wristR, meet)) < spread + 1e-3f, $"right wrist {Len(Sub(wristR, meet))} m from the meeting point");
// Either side of the line, the left toward the torso's left: the across sign is what separates these from each other.
@@ -234,7 +234,7 @@ public sealed class OrientTests
// The targets the layer wrote for one arm (the flinch blend is zero here, so they are the solution).
private static Quat Unflinch(Quat[] targets, Side side, out Quat elbow)
{
- var arm = ArmChain.Of(Plan, side);
+ var arm = ArmChain.Of(Plan, side, Dt);
elbow = targets[arm.ElbowJoint];
return targets[arm.ShoulderJoint];
}
@@ -248,8 +248,8 @@ public sealed class OrientTests
var with = Run(b, parts, At((3f, 1f, -2f)));
for (var m = 0; m < Joints; m++) SameBits(without[m], with[m]);
var t = parts[Torso];
- var wl = Wrist(ArmChain.Of(Plan, Side.Left), t, Unflinch(with, Side.Left, out var el), el);
- var wr = Wrist(ArmChain.Of(Plan, Side.Right), t, Unflinch(with, Side.Right, out var er), er);
+ var wl = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(with, Side.Left, out var el), el);
+ var wr = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(with, Side.Right, out var er), er);
Assert.True(MathF.Abs(wr.X - -0.2f) < 2e-3f && MathF.Abs(wr.Y - 1.3f) < 2e-3f && MathF.Abs(wr.Z - 0.3f) < 2e-3f, $"right wrist {wr}");
Assert.True(MathF.Abs(wl.X + wr.X) < 1e-4f && MathF.Abs(wl.Y - wr.Y) < 1e-4f && MathF.Abs(wl.Z - wr.Z) < 1e-4f, $"left {wl} does not mirror right {wr}");
}
@@ -323,7 +323,7 @@ public sealed class OrientTests
var t = parts[Torso];
LookChain.Of(Plan).Solve(t.Rotation, t.X, t.Y, t.Z, target.X, target.Y, target.Z, out var neck);
- var arm = ArmChain.Of(Plan, Side.Right);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
var p = parts[arm.ParentPart];
arm.Solve(p.Rotation, p.X, p.Y, p.Z, target.X, target.Y, target.Z, out var shoulder, out var elbow);
for (var m = 0; m < Joints; m++)
diff --git a/tests/Lodur.Tests/IkReachTests.cs b/tests/Lodur.Tests/IkReachTests.cs
index 707fa44..12b4807 100644
--- a/tests/Lodur.Tests/IkReachTests.cs
+++ b/tests/Lodur.Tests/IkReachTests.cs
@@ -22,7 +22,8 @@ public sealed class IkReachTests
///
/// Wrist error bound at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 2.98 cm over the three free-floating targets
/// (probe 3.0, 2.3, 1.0 cm), and the least claimed mutant, 4.78 cm (the parent rotation conjugate dropped in the creation-frame transform): margin 1.27 each side.
- /// Also killed: swing order flipped, 5.22 cm; the joint frame applied the wrong way round, 5.58 cm. A flipped elbow flex reads 33 cm.
+ /// Also killed: swing order flipped, 5.29 cm (5.22 before the arm held its swivel across ticks); the joint frame applied the wrong way round,
+ /// 5.58 cm. A flipped elbow flex reads 33 cm.
/// Twist is not this metric's mutant (the arm tracks twist weakly); the Core twist test claims it.
///
private const float FreeBound = 0.0377f;
@@ -39,7 +40,7 @@ public sealed class IkReachTests
world.AddJoint(Box3DSoaJointKind.Weld, stool, ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
}
- var arm = ArmChain.Of(Plan, Side.Right);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
var strength = new float[Plan.Joints.Count];
var target = new Quat[Plan.Joints.Count];
Array.Fill(strength, 1f);