diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs index 2a0c290..9d04ca5 100644 --- a/src/Lodur.Core/Actor.cs +++ b/src/Lodur.Core/Actor.cs @@ -48,6 +48,11 @@ namespace Lodur throw new ArgumentException("WillMendsAt must be in (0, 1]."); } + if (!(drive.WillCurve > 0.0 && double.IsFinite(drive.WillCurve))) + { + throw new ArgumentException("WillCurve must be finite and above 0."); + } + _dt = tickSeconds; _driveP = drive; _brain = brain; @@ -156,7 +161,10 @@ namespace Lodur } } - _brain.Goals[_goal].Behaviour.Write(leak, _drive.Strain, _tick * _dt, (_tick - _goalSince) * _dt, strengths, targets); + // Every voluntary layer is held by will, in contest with the reflex; an involuntary one (the onset of a goal) is not. + var secondsInGoal = (_tick - _goalSince) * _dt; + var weight = secondsInGoal >= _brain.Goals[_goal].InvoluntarySeconds ? Math.Pow(_drive.Will, _driveP.WillCurve) : 1.0; + _brain.Goals[_goal].Behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets); _tick++; return events; } diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs index 80993c5..8d0c985 100644 --- a/src/Lodur.Core/DriveState.cs +++ b/src/Lodur.Core/DriveState.cs @@ -30,6 +30,12 @@ namespace Lodur /// Once the will has broken it mends when resolve climbs back to this, in (0, 1]; it can then break again. public double WillMendsAt { get; init; } = 0.25; + + /// + /// How a voluntary layer's strength follows the will: the weight is Will^WillCurve, finite and above 0. Below 1 the layer + /// holds most of its strength until the will is nearly gone; above 1 it fades as soon as the will drops. + /// + public double WillCurve { get; init; } = 0.25; } /// diff --git a/src/Lodur.Core/PoseBehaviour.cs b/src/Lodur.Core/PoseBehaviour.cs index 41524fd..67f2135 100644 --- a/src/Lodur.Core/PoseBehaviour.cs +++ b/src/Lodur.Core/PoseBehaviour.cs @@ -114,7 +114,13 @@ namespace Lodur return Math.Min(Math.Max(w, 0.0), 1.0); } - public void Write(double leak, double strain, double seconds, double secondsInGoal, Span strengths, Span targets) + /// + /// Writes one tick's strengths and targets. The strength is scaled by the + /// in [0, 1] (the will that powers the layer, or 1 while it is involuntary) plus the leaked + /// reflex, capped at 1: a reflex that gets past a failing will still moves the muscle. The target rule is + /// , unchanged. + /// + public void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span strengths, Span targets) { var count = MuscleCount; if (strengths.Length != count || targets.Length != count) @@ -122,7 +128,13 @@ namespace Lodur throw new ArgumentException($"strengths and targets need {count} entries, one per muscle."); } + if (!(weight >= 0.0 && weight <= 1.0)) + { + throw new ArgumentOutOfRangeException(nameof(weight), "The weight must be in [0, 1]."); + } + var w = (float)Blend(leak, strain, seconds); + var strength = Hold.HoldStrength * (float)Math.Min(1.0, weight + leak * Hold.FlinchGain); var k = _keys.Length; var from = 0; var to = 0; @@ -144,7 +156,7 @@ namespace Lodur a = Quat.Nlerp(_keys[from][m], _keys[to][m], phase); } - strengths[m] = Hold.HoldStrength; + strengths[m] = strength; targets[m] = Quat.Nlerp(a, _flinch[m], w); } } diff --git a/tests/Lodur.Core.Tests/PoseBehaviourTests.cs b/tests/Lodur.Core.Tests/PoseBehaviourTests.cs index 38b8e71..a81dc31 100644 --- a/tests/Lodur.Core.Tests/PoseBehaviourTests.cs +++ b/tests/Lodur.Core.Tests/PoseBehaviourTests.cs @@ -10,11 +10,11 @@ public sealed class PoseBehaviourTests private static PoseBehaviour Held(HoldParameters? p = null) => new() { Keys = new[] { Hold }, FlinchPose = Withdraw, Hold = p ?? new HoldParameters() }; - private static (float[] S, Quat[] T) Write(PoseBehaviour b, double leak, double strain, double t, double inGoal = 0.0) + private static (float[] S, Quat[] T) Write(PoseBehaviour b, double leak, double strain, double t, double inGoal = 0.0, double weight = 1.0) { var s = new float[2]; var q = new Quat[2]; - b.Write(leak, strain, t, inGoal, s, q); + b.Write(weight, leak, strain, t, inGoal, s, q); return (s, q); } @@ -68,6 +68,36 @@ public sealed class PoseBehaviourTests Assert.All(s, x => Assert.Equal(0.6f, x)); } + [Theory] + [InlineData(1.0, 0.0, 1.0)] + [InlineData(0.5, 0.0, 0.5)] + [InlineData(0.0, 0.0, 0.0)] + [InlineData(0.2, 0.1, 0.5)] + [InlineData(0.9, 0.2, 1.0)] // capped at 1, never past it + public void A_voluntary_strength_is_the_hold_strength_scaled_by_the_weight_plus_the_leak_capped_at_one(double weight, double leak, double expectedScale) + { + var hold = new HoldParameters { HoldStrength = 0.8f, FlinchGain = 3.0, StrainShake = 0.0 }; + var (s, _) = Write(Held(hold), leak, 0.0, 0.0, weight: weight); + // weight + leak x FlinchGain: 0.2 + 0.1 x 3 = 0.5; 0.9 + 0.2 x 3 caps at 1. + Assert.All(s, x => Assert.Equal(0.8f * (float)expectedScale, x)); + } + + [Fact] + public void The_weight_scales_strength_only_the_targets_are_the_same_at_every_weight() + { + var b = Held(new HoldParameters { StrainShake = 0.4 }); + var (_, full) = Write(b, 0.07, 0.6, 0.31, weight: 1.0); + var (_, faint) = Write(b, 0.07, 0.6, 0.31, weight: 0.1); + for (var m = 0; m < full.Length; m++) SameBits(full[m], faint[m]); + } + + [Theory] + [InlineData(-0.01)] + [InlineData(1.01)] + [InlineData(double.NaN)] + public void A_weight_outside_zero_to_one_is_refused(double weight) => + Assert.Throws(() => Held().Write(weight, 0.0, 0.0, 0.0, 0.0, new float[2], new Quat[2])); + [Fact] public void The_shake_is_zero_at_zero_strain_and_its_amplitude_grows_with_strain() { @@ -125,8 +155,8 @@ public sealed class PoseBehaviourTests { var b = Held(); Assert.Equal(2, b.MuscleCount); - Assert.Throws(() => b.Write(0.0, 0.0, 0.0, 0.0, new float[1], new Quat[2])); - Assert.Throws(() => b.Write(0.0, 0.0, 0.0, 0.0, new float[2], new Quat[3])); + Assert.Throws(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[1], new Quat[2])); + Assert.Throws(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[2], new Quat[3])); Brain Of(PoseBehaviour p) => new() { Goals = new[] { new GoalSpec { Id = "g", Behaviour = p } } }; Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(new PoseBehaviour()))); diff --git a/tests/Lodur.Core.Tests/WillTests.cs b/tests/Lodur.Core.Tests/WillTests.cs index bc17c1f..129bb93 100644 --- a/tests/Lodur.Core.Tests/WillTests.cs +++ b/tests/Lodur.Core.Tests/WillTests.cs @@ -263,4 +263,82 @@ public sealed class WillTests Of(Base() with { EntryResolve = 0.0, Effort = 0.0, InvoluntarySeconds = double.PositiveInfinity })); _ = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(Base() with { EntryResolve = 1.0 })); } + + private static HoldParameters Hold07 => new() { HoldStrength = 0.7f }; + + [Fact] + public void A_voluntary_goal_writes_its_hold_strength_times_Will_to_the_WillCurve_with_no_leak() + { + // Effort drains resolve at a known rate with recovery off and the box off, so the leak is zero and Will is a clean ramp. + var drive = new DriveParameters { ResolveRecovery = 0.0, WillCurve = 0.5 }; + var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 }; + var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 0.5, Behaviour = pose } } }; + var r = new PainBoxReplay(1, drive: drive, brain: brain, jitter: 0.0); + var last = float.MaxValue; + for (var i = 0; i < 150; i++) + { + r.Tick(false); + Assert.Equal(0.0, r.Actor.Afferent(0)); + var will = r.Actor.Drive.Will; + Assert.Equal(0.7f * (float)Math.Sqrt(will), r.Strengths[0]); + Assert.Equal(r.Strengths[0], r.Strengths[1]); + Assert.True(r.Strengths[0] <= last); + last = r.Strengths[0]; + } + + Assert.True(last < 0.6f, "the strength never fell with the will"); + } + + [Fact] + public void A_goal_that_takes_over_at_resolve_zero_writes_full_hold_strength_while_involuntary_and_what_leaks_while_voluntary() + { + float AtBreak(double involuntary) + { + var release = new GoalSpec + { + Id = "release", Priority = 1.0, InvoluntarySeconds = involuntary, + When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, + Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 }, + }; + var brain = new Brain { Goals = new[] { new GoalSpec { Id = "objective", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 } }, release } }; + var r = new PainBoxReplay(1, brain: brain); + TickEvents e; + do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000); + Assert.Equal(0.0, r.Actor.Drive.Resolve); + Assert.True(r.Actor.Afferent(0) > 0.3); + return r.Strengths[0]; + } + + Assert.Equal(0.7f, AtBreak(double.PositiveInfinity)); + Assert.True(AtBreak(0.0) < 0.7f * 0.5f, "a voluntary goal at zero will held its strength"); + } + + [Theory] + [InlineData(1.0, 0.7f)] + [InlineData(0.3, 0.7f * 0.7401198f)] // 0.3 ^ 0.25 + public void The_tick_a_goal_takes_over_its_entry_resolve_is_the_will_its_first_write_is_weighted_by(double entry, float expected) + { + var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 }; + var brain = new Brain + { + Goals = new[] + { + new GoalSpec { Id = "composure", Behaviour = pose }, + new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = entry, When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = pose }, + }, + }; + var r = new PainBoxReplay(1, brain: brain); + TickEvents e; + do { e = r.Tick(r.Actor.Drive.Breaks == 0); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000); + Assert.Equal(0.0, r.Actor.Afferent(0)); + Assert.Equal(expected, r.Strengths[0], 4); + } + + [Theory] + [InlineData(0.0)] + [InlineData(-1.0)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + public void A_WillCurve_that_is_not_finite_and_above_zero_is_refused(double curve) => + Assert.Throws(() => new PainBoxReplay(1, drive: new DriveParameters { WillCurve = curve })); } diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs index bdf6d6c..b0eea69 100644 --- a/tests/Lodur.Tests/ConnectedPainBoxTests.cs +++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs @@ -23,7 +23,7 @@ internal sealed class ConnectedPainBox : IDisposable public readonly Quat[] Target = new Quat[HumanoidRagdoll.MuscleCount]; private SplitMix64 _rng; - public ConnectedPainBox(ulong seed, HoldParameters? hold = null) + public ConnectedPainBox(ulong seed, HoldParameters? hold = null, DriveParameters? driveTunables = null) { World = new Box3DSoaWorld(capacity: HumanoidRagdoll.LimbCount + 2, jointCapacity: HumanoidRagdoll.MuscleCount + 1); World.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f); @@ -67,7 +67,7 @@ internal sealed class ConnectedPainBox : IDisposable }, }; Actor = new Actor(Dt, HumanoidRagdoll.RegionCount, new NerveParameters { Gain = gain }, new WithdrawalParameters(), - new DriveParameters { DrainTrait = drain }, brain); + (driveTunables ?? new DriveParameters()) with { DrainTrait = drain }, brain); } public Box3DSoaView View => World.View; @@ -130,9 +130,9 @@ public sealed class ConnectedPainBoxTests private sealed record Timeline(List Flinches, long Broke, long Withdrew, List<(long Tick, (float X, float Y, float Z) Hand, bool InBox)> Hand, ulong Hash); - private static Timeline Run(ulong seed, HoldParameters? hold = null, double maxSeconds = 25.0) + private static Timeline Run(ulong seed, HoldParameters? hold = null, double maxSeconds = 25.0, DriveParameters? drive = null) { - using var s = new ConnectedPainBox(seed, hold); + using var s = new ConnectedPainBox(seed, hold, drive); var t = new Timeline(new List(), -1, -1, new List<(long, (float, float, float), bool)>(), 0); long broke = -1, withdrew = -1; var max = (long)(maxSeconds / ConnectedPainBox.Dt); @@ -177,8 +177,11 @@ public sealed class ConnectedPainBoxTests [Fact] public void The_movement_is_the_leak_not_the_body_without_it_the_hand_holds_still_and_with_it_the_hand_is_pulled_away_by_the_last_flinch() { - var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0); - var full = Run(seed: 1); + // Both runs hold at full strength until the will is nearly gone (a WillCurve this small weights by ~1): the will's own + // sag of the hold, which would move even a leak-free arm, is pinned in the next test, so this isolates the leak. + var flat = new DriveParameters { WillCurve = 0.001 }; + var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0, flat); + var full = Run(seed: 1, drive: flat); Assert.Equal(full.Flinches, plain.Flinches); // the nervous state does not depend on the arm while the hand is in the box // No leak, no shake: after settling, the hand stays within 2.3 cm of the hold point until the will breaks. @@ -189,6 +192,16 @@ public sealed class ConnectedPainBoxTests Assert.True(Dist(full.Hand[last].Hand, plain.Hand[last].Hand) > 0.023f); } + [Fact] + public void A_failing_will_sags_the_hold_even_with_no_leak_and_no_shake_while_a_strong_will_holds_still() + { + var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0); + // Early, resolve is high and the weight near 1: the hand stays within 2.3 cm of the hold point (seed 1 measured 0.8-2.0 cm to 8 s). + for (var i = 3 * Hz; i < 6 * Hz; i++) Assert.True(Dist(plain.Hand[i].Hand, Centre) <= 0.023f, $"drift {Dist(plain.Hand[i].Hand, Centre)} at tick {i}"); + // Late, the will is nearly gone: the voluntary hold has gone slack and the arm sags well out of the box before the break (measured 0.14 m at 14.2 s). + Assert.True(Dist(plain.Hand[(int)plain.Broke - 60].Hand, Centre) > 0.1f); + } + private static float VerticalPeakToPeak(Timeline t, int fromSecond) { var seg = t.Hand.Skip(fromSecond * Hz).Take(Hz).Select(h => h.Hand.Y).ToList(); @@ -239,11 +252,12 @@ public sealed class ConnectedPainBoxTests } [Fact] - public void Seed_1_to_16_seconds_replays_the_world_the_break_and_the_deliberate_switch_recorded_at_the_pre_brain_base() + public void Seed_1_to_16_seconds_replays_the_world_the_break_and_the_deliberate_switch_recorded_at_the_will_mix() { - // Recorded at Lodur 5d0fec8, before the Brain: the pain box authored as a Brain must drive the body with the same bits. + // Recorded at the will mix (voluntary strength = hold x Will^WillCurve + leak). Until then the bits were the pre-Brain base's + // (Lodur 5d0fec8, hand=e283e3615b6b2cbc); the break and switch ticks and the flinch count did not move, the arm's track did. var t = Run(seed: 1, maxSeconds: 16.0); - Assert.Equal("broke=1770 withdrew=1782 flinches=16 hand=e283e3615b6b2cbc world=cd1902f3dd65af64", + Assert.Equal("broke=1770 withdrew=1782 flinches=16 hand=a0fafe85c80e98f7 world=83155f2abf0e7e91", $"broke={t.Broke} withdrew={t.Withdrew} flinches={t.Flinches.Count} hand={HandTrackHash(t):x16} world={t.Hash:x16}"); } }