diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
index facdba0..e0ab11e 100644
--- a/src/Lodur.Core/Actor.cs
+++ b/src/Lodur.Core/Actor.cs
@@ -168,6 +168,12 @@ namespace Lodur
_drive.Attention = attention;
}
+ ///
+ /// Forgets the arms' history: each arm's next solve is the stateless rule, as on the first tick. For a caller that moves the body
+ /// discontinuously (a teleport, a respawn) so the arms do not carry a swivel from the old place. Nothing for an actor without arms.
+ ///
+ public void ResetArms() => _rig?.ResetArms();
+
public Brain Brain => _brain;
/// The index in 's goals of the goal in force; it changes only on the tick that reports .
diff --git a/src/Lodur.Core/Ik.cs b/src/Lodur.Core/Ik.cs
index db7482d..f789745 100644
--- a/src/Lodur.Core/Ik.cs
+++ b/src/Lodur.Core/Ik.cs
@@ -99,6 +99,12 @@ namespace Lodur
/// 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.
///
+ ///
+ /// The clamp splits the target into swing and twist, and that split is singular at a half-turn swing, where the swing direction turns by
+ /// up to a half turn for a small change in the target. Within of it the clamp keeps the previous tick's swing
+ /// direction, blending from the fresh one across the band's width again (ruling lodur:ruling:ik-clamp-singular-uses-previous); the first
+ /// solve after construction or clamps along the fresh direction.
+ ///
///
public sealed class ArmChain
{
@@ -111,6 +117,9 @@ namespace Lodur
private Quat _previous;
private bool _hasPrevious;
+ // The previous solve's swing direction, the angle of the shoulder target's swing axis in the frame's xy plane, after clamping.
+ private float _swingDirection;
+
///
/// 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
@@ -125,6 +134,13 @@ namespace Lodur
///
public const float SwivelRate = 3f;
+ ///
+ /// Radians of swing short of a half turn within which the clamp keeps the previous tick's swing direction; across the band's width
+ /// again beyond it the direction blends from the fresh one. Placeholder: it covers the half-turn jumps of the random-jump test
+ /// (held swing 3.005 to 3.141 rad), and is not derived from a measured cost.
+ ///
+ public const float SingularBand = 0.25f;
+
// 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.
private const int SwivelSteps = 90;
@@ -200,7 +216,7 @@ namespace Lodur
/// 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.
+ /// Forgets the previous swivel and swing direction: 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.
@@ -266,14 +282,19 @@ namespace Lodur
}
var local = Local(a, b, phi);
+ var hold = _hasPrevious;
_previous = local;
_hasPrevious = true;
if (clamp)
{
// Infeasible: swing and twist clamped to the limits.
- local = ClampToLimits(local);
+ local = ClampToLimits(local, hold);
reached = false;
}
+ else
+ {
+ _swingDirection = SwingDirection(local);
+ }
shoulder = local;
elbow = Quat.FromAxisAngle(0f, 0f, 1f, flex);
@@ -512,17 +533,47 @@ namespace Lodur
return (float)(fp <= fq ? p : q);
}
- // Twist clamped to its range and swing to the cone, the swing direction kept. The target is swing * twist, the twist about the frame
- // z and the swing about an axis in its xy plane.
- private Quat ClampToLimits(in Quat local)
+ // The swing-twist split: the twist about the frame z as (tz, tw), the half-angle's sine and cosine, and the swing as (sx, sy, sw), its
+ // axis in the xy plane; local = swing * twist. At a half-turn swing the twist is undefined: read it as none.
+ private static void Split(in Quat local, out float tz, out float tw, out float sx, out float sy, out float sw)
{
- // At a half-turn swing the twist is undefined: read it as none.
- var tl = MathF.Sqrt(local.Z * local.Z + local.W * local.W);
- var tz = tl > 1e-6f ? local.Z / tl : 0f;
- var tw = tl > 1e-6f ? local.W / tl : 1f;
- var sx = tw * local.X - tz * local.Y;
- var sy = tz * local.X + tw * local.Y;
- var sw = tl;
+ sw = MathF.Sqrt(local.Z * local.Z + local.W * local.W);
+ tz = sw > 1e-6f ? local.Z / sw : 0f;
+ tw = sw > 1e-6f ? local.W / sw : 1f;
+ sx = tw * local.X - tz * local.Y;
+ sy = tz * local.X + tw * local.Y;
+ }
+
+ private static float SwingDirection(in Quat local)
+ {
+ Split(local, out _, out _, out var sx, out var sy, out _);
+ return MathF.Atan2(sy, sx);
+ }
+
+ // Twist clamped to its range and swing to the cone, the swing direction kept. Near a half-turn swing the split is singular: the swing
+ // direction turns by up to a half turn for a small change in the target. There, with a previous solve (hold), the direction is the
+ // previous tick's (ruling lodur:ruling:ik-clamp-singular-uses-previous), blended continuously from the fresh one across the band's
+ // outer edge, and the twist is read against that direction; the direction used is kept for the next tick.
+ private Quat ClampToLimits(in Quat local, bool hold)
+ {
+ Split(local, out var tz, out var tw, out var sx, out var sy, out var sw);
+ var sl = MathF.Sqrt(sx * sx + sy * sy);
+ var weight = hold ? Ik.Clamp((2f * MathF.Atan2(sl, sw) - (MathF.PI - 2f * SingularBand)) / SingularBand, 0f, 1f) : 0f;
+ if (weight > 0f)
+ {
+ var fresh = MathF.Atan2(sy, sx);
+ var dir = fresh + weight * Wrap(_swingDirection - fresh);
+ // The swing about dir that carries the target's xy part: the twist half-angle is dir less the xy part's angle, taken in
+ // [-pi / 2, pi / 2] (a half turn of the half-angle is the same rotation).
+ var half = dir - MathF.Atan2(local.Y, local.X);
+ half -= MathF.PI * MathF.Round(half / MathF.PI);
+ tz = MathF.Sin(half);
+ tw = MathF.Cos(half);
+ sx = sl * MathF.Cos(dir);
+ sy = sl * MathF.Sin(dir);
+ }
+
+ _swingDirection = MathF.Atan2(sy, sx);
var s2 = sx * sx + sy * sy;
if (s2 > _coneSin2)
{
@@ -532,9 +583,9 @@ namespace Lodur
sw = _coneCosHalf;
}
- var half = 0.5f * Ik.Clamp(2f * MathF.Atan2(tz, tw), _twistLo, _twistHi);
- tz = MathF.Sin(half);
- tw = MathF.Cos(half);
+ var twistHalf = 0.5f * Ik.Clamp(2f * MathF.Atan2(tz, tw), _twistLo, _twistHi);
+ tz = MathF.Sin(twistHalf);
+ tw = MathF.Cos(twistHalf);
return new Quat(tw * sx + tz * sy, tw * sy - tz * sx, sw * tz, sw * tw);
}
}
diff --git a/src/Lodur.Core/Orient.cs b/src/Lodur.Core/Orient.cs
index b77cb0f..7607059 100644
--- a/src/Lodur.Core/Orient.cs
+++ b/src/Lodur.Core/Orient.cs
@@ -188,7 +188,7 @@ 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. 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.
+ /// arm's swivel from tick to tick (an arm not driven on a tick keeps its last one, until ); the rig holds nothing else, and solving allocates nothing.
///
internal sealed class OrientRig
{
@@ -247,6 +247,13 @@ namespace Lodur
}
}
+ /// Forgets both arms' held swivels and swing directions: each arm's next solve is the stateless rule.
+ public void ResetArms()
+ {
+ _left?.Reset();
+ _right?.Reset();
+ }
+
/// The arm whose shoulder is nearer the target; ties go to the right.
public Side NearerArm(ReadOnlySpan parts, in Percept target)
{
diff --git a/tests/Lodur.Core.Tests/IkTests.cs b/tests/Lodur.Core.Tests/IkTests.cs
index b51088f..cd38518 100644
--- a/tests/Lodur.Core.Tests/IkTests.cs
+++ b/tests/Lodur.Core.Tests/IkTests.cs
@@ -364,9 +364,10 @@ public sealed class IkTests
}
// 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.
+ // shipped worst and the least claimed mutant. Claimed mutants: the stateless argmin (the chain reset every tick), and the clamp along the
+ // fresh swing direction at the half-turn swing (no hold). Shipped worst over the tie lines, all 81 random jumps and the basin switch:
+ // 0.0333 rad. Least mutant: 0.5039 rad, the stateless argmin at a random jump (tie lines least 0.9995); the fresh-direction clamp turns
+ // 2.27 to 3.00 rad at 18 of the 20 half-turn jumps (2.98 right, 3.00 left worst). Bound sqrt(0.0333 * 0.5039) = 0.129.
private const float HeldTurnBound = 0.129f;
[Fact]
@@ -407,9 +408,8 @@ public sealed class IkTests
// 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.
+ // Counted: jumps where the held target swings past HalfTurnSwing, where the swing-twist split is singular and the clamp holds the
+ // previous swing direction; the tripwire keeps the bound testing that band.
const float HalfTurnSwing = 3.0f;
var arm = ArmChain.Of(Plan, side, Dt);
var s = arm.ShoulderAnchor;
@@ -432,7 +432,7 @@ public sealed class IkTests
}
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 (found, singular, worst, mutant) = (0, 0, 0f, float.MaxValue);
var path = new (float X, float Y, float Z)[12];
for (var k = 0; k < 400 && found < 40; k++)
{
@@ -461,25 +461,18 @@ public sealed class IkTests
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);
- }
+ if (walk.HeldSwing > HalfTurnSwing) singular++;
+ 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");
+ _output.WriteLine($"{side}: {found} stateless jumps (worst held {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(singular >= 5, $"only {singular} jumps at the half-turn swing; the bound no longer tests the singular clamp");
Assert.True(worst < HeldTurnBound, $"the shoulder target turned {worst} rad in one tick at a stateless jump");
}
diff --git a/tests/Lodur.Core.Tests/OrientTests.cs b/tests/Lodur.Core.Tests/OrientTests.cs
index 5b684b9..6518579 100644
--- a/tests/Lodur.Core.Tests/OrientTests.cs
+++ b/tests/Lodur.Core.Tests/OrientTests.cs
@@ -491,6 +491,46 @@ public sealed class OrientTests
Same(baseline[left], targets[left]);
}
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void ResetArms_makes_both_arms_solve_the_stateless_rule_again(Side side)
+ {
+ // Reach with both arms along the feasible tie of one arm's shoulder (goal (dx, -0.25, -0.25) from it, mirrored for the left), from
+ // dx -10 mm to 2 mm past the tie: that arm holds its basin, away from the stateless target. After ResetArms the next tick writes the
+ // stateless solve for both arms, bit for bit.
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
+ var a = Watcher(Watching(b), Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var arms = new[] { ArmChain.Of(Plan, Side.Left, Dt), ArmChain.Of(Plan, Side.Right, Dt) };
+ var tie = side == Side.Left ? arms[0] : arms[1];
+ var sign = side == Side.Left ? -1f : 1f;
+ var s = tie.ShoulderAnchor;
+ (float X, float Y, float Z) Goal(float dx) => (s.X + sign * dx, s.Y - 0.25f, s.Z - 0.25f);
+ for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, Goal(-0.01f)));
+ Assert.Equal(1UL, a.TargetId);
+ for (var i = -50; i <= 10; i++) Step(a, parts, targets, Emit(1, Goal(i * 0.0002f)));
+ var held = (Quat[])targets.Clone();
+ a.ResetArms();
+ Step(a, parts, targets, Emit(1, Goal(0.002f)));
+
+ var t = a.Target;
+ Assert.Equal(Goal(0.002f), (t.X, t.Y, t.Z));
+ foreach (var arm in arms)
+ {
+ var p = parts[arm.ParentPart];
+ arm.Solve(p.Rotation, p.X, p.Y, p.Z, t.X, t.Y, t.Z, out var shoulder, out var elbow);
+ SameBits(Flinched(shoulder, Quat.Identity, 0f), targets[arm.ShoulderJoint]);
+ SameBits(Flinched(elbow, Quat.Identity, 0f), targets[arm.ElbowJoint]);
+ }
+
+ var held2 = held[tie.ShoulderJoint];
+ var reset = targets[tie.ShoulderJoint];
+ var turn = 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(held2.X * reset.X + held2.Y * reset.Y + held2.Z * reset.Z + held2.W * reset.W)));
+ Assert.True(turn > 1f, $"the held {side} arm was only {turn} rad from the stateless target, so the reset proves nothing");
+ }
+
[Fact]
public void A_tie_goes_to_the_right_arm()
{