diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
index 57ff0f9..fbf1885 100644
--- a/src/Lodur.Core/Actor.cs
+++ b/src/Lodur.Core/Actor.cs
@@ -40,6 +40,8 @@ namespace Lodur
private long _tick;
private int _goal;
private int _pending = -1;
+ private ulong _target;
+ private ulong _pendingTarget;
private long _switchTick;
private long _goalSince;
// The entry ramp of the goal in force: its length in ticks (-1: none, as for the Start goal) and the gain and arousal it started from.
@@ -140,6 +142,30 @@ namespace Lodur
public Percept Percept(int slot) => _perception.Percept(slot);
+ /// The id of the percept the committed goal targets; 0 for an untargeted goal. Only the Brain's choice, committed after the latency, writes it.
+ public ulong TargetId => _target;
+
+ /// The slot whose Id equals ; default (Id 0) when the target is 0 or forgotten.
+ public Percept Target
+ {
+ get
+ {
+ if (_target != 0UL)
+ {
+ for (var s = 0; s < _perception.PerceptCount; s++)
+ {
+ var p = _perception.Percept(s);
+ if (p.Id == _target)
+ {
+ return p;
+ }
+ }
+ }
+
+ return default;
+ }
+ }
+
///
/// Runs one physics step's worth of nervous system. The point spans hold one entry per region; the strengths
/// and targets spans one entry per muscle, written for the body to follow. The emitters are the game's point
@@ -207,26 +233,34 @@ namespace Lodur
// pending. Within the goal in force's minimum dwell only a strictly higher-priority goal is decided on.
if (_pending < 0)
{
- var wanted = _brain.Select(_drive, _goal);
- if (wanted != _goal && (_tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted].Priority > _brain.Goals[_goal].Priority))
+ var sr = _perception.SenseRegion;
+ var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], new Choice(_goal, _target));
+ if (wanted != new Choice(_goal, _target)
+ && (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority))
{
- _pending = wanted;
+ _pending = wanted.Goal;
+ _pendingTarget = wanted.Target;
_switchTick = _tick + _latency;
}
}
if (_pending >= 0 && _tick == _switchTick)
{
+ var changed = _pending != _goal;
_goal = _pending;
+ _target = _pendingTarget;
_pending = -1;
- _goalSince = _tick;
- events |= TickEvents.GoalChanged;
- _rampTicks = _entryTicks[_goal];
- _rampGain0 = _drive.SensoryGain;
- _rampArousal0 = _drive.Arousal;
- if (_brain.Goals[_goal].EntryResolve is double entry)
+ if (changed)
{
- _drive.Enter(_driveP, entry);
+ _goalSince = _tick;
+ events |= TickEvents.GoalChanged;
+ _rampTicks = _entryTicks[_goal];
+ _rampGain0 = _drive.SensoryGain;
+ _rampArousal0 = _drive.Arousal;
+ if (_brain.Goals[_goal].EntryResolve is double entry)
+ {
+ _drive.Enter(_driveP, entry);
+ }
}
}
diff --git a/src/Lodur.Core/Brain.cs b/src/Lodur.Core/Brain.cs
index c5610ab..8343155 100644
--- a/src/Lodur.Core/Brain.cs
+++ b/src/Lodur.Core/Brain.cs
@@ -22,20 +22,85 @@ namespace Lodur
Below,
}
+ internal static class DriveReads
+ {
+ internal static double Read(in DriveState drive, DriveQuantity quantity) => quantity switch
+ {
+ DriveQuantity.Pain => drive.Pain,
+ DriveQuantity.Strain => drive.Strain,
+ DriveQuantity.Arousal => drive.Arousal,
+ DriveQuantity.Resolve => drive.Resolve,
+ DriveQuantity.Breaks => (double)drive.Breaks,
+ _ => drive.WillBroken ? 1.0 : 0.0,
+ };
+ }
+
+ /// What a consideration reads: a percept's distance from the observer, its salience, the seconds since it was sensed, or a drive quantity.
+ public enum ConsiderationInput
+ {
+ Distance,
+ Salience,
+ SecondsSinceSensed,
+ Drive,
+ }
+
+ ///
+ /// One response curve over an input, in [0, 1]: t = clamp01((x - X0) / (X1 - X0)), y = Y0 + (Y1 - Y0) * t^Exponent, clamped. A goal's pair
+ /// score is its Priority times every consideration's response. Drive reads off the drive state.
+ ///
+ public readonly record struct Consideration(ConsiderationInput Input, double X0, double X1, double Y0, double Y1, double Exponent = 1.0, DriveQuantity Quantity = default)
+ {
+ public double Response(double x)
+ {
+ var t = Math.Clamp((x - X0) / (X1 - X0), 0.0, 1.0);
+ return Math.Clamp(Y0 + (Y1 - Y0) * Math.Pow(t, Exponent), 0.0, 1.0);
+ }
+ }
+
+ /// The game's kinds a targeted goal accepts; Lodur never interprets them.
+ public sealed record TargetFilter
+ {
+ private IReadOnlyList _kinds = Array.AsReadOnly(Array.Empty());
+
+ /// Copied when set; read back as a read-only view.
+ public IReadOnlyList Kinds
+ {
+ get => _kinds;
+ init
+ {
+ var copy = new uint[value.Count];
+ for (var i = 0; i < copy.Length; i++)
+ {
+ copy[i] = value[i];
+ }
+
+ _kinds = Array.AsReadOnly(copy);
+ }
+ }
+
+ internal bool Accepts(uint kind)
+ {
+ for (var i = 0; i < _kinds.Count; i++)
+ {
+ if (_kinds[i] == kind)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+
+ /// The Brain's choice: a goal index and the id of the percept it targets (0: untargeted).
+ public readonly record struct Choice(int Goal, ulong Target);
+
/// One test of the drive state: the quantity against a threshold.
public readonly record struct Condition(DriveQuantity Quantity, ConditionOp Op, double Threshold)
{
public bool Holds(in DriveState drive)
{
- var v = Quantity switch
- {
- DriveQuantity.Pain => drive.Pain,
- DriveQuantity.Strain => drive.Strain,
- DriveQuantity.Arousal => drive.Arousal,
- DriveQuantity.Resolve => drive.Resolve,
- DriveQuantity.Breaks => (double)drive.Breaks,
- _ => drive.WillBroken ? 1.0 : 0.0,
- };
+ var v = DriveReads.Read(drive, Quantity);
return Op == ConditionOp.AtLeast ? v >= Threshold : v < Threshold;
}
}
@@ -117,6 +182,60 @@ namespace Lodur
}
}
+ /// The kind of thing this goal targets; null is an untargeted goal. Whether a target exists is decided in , not by Eligible.
+ public TargetFilter? Target { get; init; }
+
+ private Consideration[] _considerations = Array.Empty();
+ private IReadOnlyList _considerationsView = Array.AsReadOnly(Array.Empty());
+
+ /// Multiplied with Priority to score each (goal, percept) pair. Copied when set; read back as a read-only view.
+ public IReadOnlyList Considerations
+ {
+ get => _considerationsView;
+ init
+ {
+ _considerations = new Consideration[value.Count];
+ for (var c = 0; c < _considerations.Length; c++)
+ {
+ _considerations[c] = value[c];
+ }
+
+ _considerationsView = Array.AsReadOnly(_considerations);
+ }
+ }
+
+ internal double Score(in DriveState drive, in Percept percept, float ox, float oy, float oz)
+ {
+ var score = Priority;
+ for (var c = 0; c < _considerations.Length; c++)
+ {
+ var k = _considerations[c];
+ double x;
+ switch (k.Input)
+ {
+ case ConsiderationInput.Drive:
+ x = DriveReads.Read(drive, k.Quantity);
+ break;
+ case ConsiderationInput.Distance:
+ {
+ double dx = percept.X - ox, dy = percept.Y - oy, dz = percept.Z - oz;
+ x = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+ break;
+ }
+ case ConsiderationInput.Salience:
+ x = percept.Salience;
+ break;
+ default:
+ x = percept.SecondsSinceSensed;
+ break;
+ }
+
+ score *= k.Response(x);
+ }
+
+ return score;
+ }
+
internal bool Eligible(in DriveState drive)
{
for (var c = 0; c < _when.Length; c++)
@@ -163,11 +282,22 @@ namespace Lodur
/// How long a chosen switch takes to commit; a decision in flight commits even if its condition lapses.
public double DeliberateLatencySeconds { get; init; } = 0.1;
- /// The goal wanted now: the eligible goal of highest priority, ties to the current goal then the lowest index; the current goal if none is eligible.
- public int Select(in DriveState drive, int current)
+ /// How much the current (goal, target) pair's score is multiplied by, finite and at least 1; 1 is no commitment.
+ public double TargetCommitment { get; init; } = 1.0;
+
+ ///
+ /// The pair wanted now. Each eligible untargeted goal is one pair (goal, 0) scored Priority times its Drive considerations; each eligible
+ /// targeted goal is one pair per percept slot with a non-zero Id and a Kind it accepts, scored Priority times every consideration. The pair
+ /// equal to is multiplied by . The highest score wins; ties go to the current pair,
+ /// then the lowest goal index, then the lowest slot; with no pair at all the current choice stays. A percept Id is only compared, never decoded.
+ ///
+ public Choice Select(in DriveState drive, Perception perception, float observerX, float observerY, float observerZ, Choice current)
{
- var best = -1;
- var bestPriority = 0.0;
+ var best = current;
+ var bestScore = 0.0;
+ var bestIsCurrent = false;
+ var found = false;
+ var slots = perception.PerceptCount;
for (var i = 0; i < Goals.Count; i++)
{
var goal = Goals[i];
@@ -176,14 +306,42 @@ namespace Lodur
continue;
}
- if (best < 0 || goal.Priority > bestPriority || (goal.Priority == bestPriority && i == current))
+ if (goal.Target is null)
{
- best = i;
- bestPriority = goal.Priority;
+ Offer(i, 0UL, goal.Score(drive, default, observerX, observerY, observerZ), current, ref best, ref bestScore, ref bestIsCurrent, ref found);
+ continue;
+ }
+
+ for (var s = 0; s < slots; s++)
+ {
+ var percept = perception.Percept(s);
+ if (percept.Id == 0UL || !goal.Target.Accepts(percept.Kind))
+ {
+ continue;
+ }
+
+ Offer(i, percept.Id, goal.Score(drive, percept, observerX, observerY, observerZ), current, ref best, ref bestScore, ref bestIsCurrent, ref found);
}
}
- return best < 0 ? current : best;
+ return found ? best : current;
+ }
+
+ private void Offer(int goal, ulong target, double score, Choice current, ref Choice best, ref double bestScore, ref bool bestIsCurrent, ref bool found)
+ {
+ var isCurrent = goal == current.Goal && target == current.Target;
+ if (isCurrent)
+ {
+ score *= TargetCommitment;
+ }
+
+ if (!found || score > bestScore || (score == bestScore && isCurrent && !bestIsCurrent))
+ {
+ best = new Choice(goal, target);
+ bestScore = score;
+ bestIsCurrent = isCurrent;
+ found = true;
+ }
}
internal void Validate()
@@ -203,9 +361,39 @@ namespace Lodur
throw new ArgumentException("DeliberateLatencySeconds must be finite and not negative.");
}
+ if (!(double.IsFinite(TargetCommitment) && TargetCommitment >= 1.0))
+ {
+ throw new ArgumentException("TargetCommitment must be finite and at least 1.");
+ }
+
var muscles = -1;
foreach (var goal in Goals)
{
+ if (goal.Target is { } filter && filter.Kinds.Count == 0)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a Target needs at least one kind.");
+ }
+
+ if ((goal.Target != null || goal.Considerations.Count > 0) && !(goal.Priority >= 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Target or considerations.");
+ }
+
+ foreach (var k in goal.Considerations)
+ {
+ if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
+ || !(k.Y0 >= 0.0 && k.Y0 <= 1.0) || !(k.Y1 >= 0.0 && k.Y1 <= 1.0)
+ || !(double.IsFinite(k.Exponent) && k.Exponent > 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a consideration needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
+ }
+
+ if (k.Input != ConsiderationInput.Drive && goal.Target is null)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Distance, Salience and SecondsSinceSensed considerations need a targeted goal.");
+ }
+ }
+
if (!double.IsFinite(goal.Priority) || !(goal.Pull >= 0.0 && goal.Pull <= 1.0))
{
throw new ArgumentException($"Goal {goal.Id}: priority must be finite and pull in [0, 1].");
diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs
index 61db099..d72ce57 100644
--- a/src/Lodur.Core/Perception.cs
+++ b/src/Lodur.Core/Perception.cs
@@ -236,6 +236,9 @@ namespace Lodur
///
public double ChannelAfferent(Channel channel) => _senseAfferent[(int)channel];
+ /// The region whose point the senses are sensed at.
+ public int SenseRegion => _senseRegion;
+
/// The number of percept slots: the capacity, or 0 with no senses. A slot is free when its percept's id is 0.
public int PerceptCount => _pId.Length;
diff --git a/tests/Lodur.Core.Tests/BrainTests.cs b/tests/Lodur.Core.Tests/BrainTests.cs
index 84a9a29..1be2dba 100644
--- a/tests/Lodur.Core.Tests/BrainTests.cs
+++ b/tests/Lodur.Core.Tests/BrainTests.cs
@@ -12,6 +12,10 @@ public sealed class BrainTests
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
+ private static readonly Perception Deaf = new(new NerveParameters(), 0.01, 1);
+
+ private static int Pick(Brain brain, DriveState drive, int current) => brain.Select(drive, Deaf, 0f, 0f, 0f, new Choice(current, 0)).Goal;
+
private static Condition Pain(ConditionOp op, double t) => new(DriveQuantity.Pain, op, t);
private sealed record Run(List Changes, List Goals, long Broke, long[] Held);
@@ -72,12 +76,12 @@ public sealed class BrainTests
Goal("d", 9.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)),
},
};
- Assert.Equal(1, brain.Select(calm, 0)); // b and c tie at the top: the lowest index
- Assert.Equal(2, brain.Select(calm, 2)); // the current goal wins a tie
- Assert.Equal(1, brain.Select(calm, 3)); // d is ineligible: current is not kept for its own sake
+ Assert.Equal(1, Pick(brain, calm, 0)); // b and c tie at the top: the lowest index
+ Assert.Equal(2, Pick(brain, calm, 2)); // the current goal wins a tie
+ Assert.Equal(1, Pick(brain, calm, 3)); // d is ineligible: current is not kept for its own sake
var none = new Brain { Goals = new[] { Goal("x", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)), Goal("y", 0.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)) } };
- Assert.Equal(1, none.Select(calm, 1)); // nothing eligible: the current goal
- Assert.Equal(0, none.Select(calm, 0));
+ Assert.Equal(1, Pick(none, calm, 1)); // nothing eligible: the current goal
+ Assert.Equal(0, Pick(none, calm, 0));
}
[Fact]
diff --git a/tests/Lodur.Core.Tests/GoalTargetTests.cs b/tests/Lodur.Core.Tests/GoalTargetTests.cs
new file mode 100644
index 0000000..60b6686
--- /dev/null
+++ b/tests/Lodur.Core.Tests/GoalTargetTests.cs
@@ -0,0 +1,314 @@
+using System;
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class GoalTargetTests
+{
+ private const double Dt = 0.01;
+ private const uint Thing = 7;
+ private const uint Other = 9;
+ private static readonly float[] Zero = { 0f };
+ private static readonly BoxStimulus[] NoBoxes = Array.Empty();
+
+ private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Consideration[]? considerations = null, params Condition[] when) => new()
+ {
+ Id = id, Priority = priority, When = when, Target = target, Considerations = considerations ?? Array.Empty(),
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ };
+
+ private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
+
+ private static Consideration Nearer(double far) => new(ConsiderationInput.Distance, 0.0, far, 1.0, 0.0);
+
+ private static Emitter At(ulong id, float x, uint kind = Thing, double intensity = 1.0, float radius = 20f) =>
+ new(Channel.Audio, x, 0f, 0f, radius, intensity, id, kind);
+
+ private static Perception Ears(int capacity = 4, double memory = 5.0) =>
+ new(new NerveParameters(), Dt, 1, new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 },
+ 0, new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
+
+ private static Perception Hearing(params Emitter[] emitters)
+ {
+ var p = Ears();
+ p.Sense(Zero, Zero, Zero, NoBoxes, emitters, 1.0);
+ return p;
+ }
+
+ private static Choice Pick(Brain brain, Perception p, Choice current, DriveState drive = default) => brain.Select(drive, p, 0f, 0f, 0f, current);
+
+ private static int SlotOf(Perception p, ulong id)
+ {
+ for (var s = 0; s < p.PerceptCount; s++)
+ {
+ if (p.Percept(s).Id == id) return s;
+ }
+
+ return -1;
+ }
+
+ [Fact]
+ public void An_untargeted_brain_selects_as_before()
+ {
+ var calm = default(DriveState);
+ var always = new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0);
+ var hears = Hearing(At(1, 1f));
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 2.0, when: always), Goal("b", 5.0, when: always), Goal("c", 5.0, when: always),
+ Goal("d", 9.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)),
+ },
+ };
+ // Percepts in the room change nothing for goals that name no target.
+ Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(0, 0), calm));
+ Assert.Equal(new Choice(2, 0), Pick(brain, hears, new Choice(2, 0), calm));
+ Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(3, 0), calm));
+ var none = new Brain { Goals = new[] { Goal("x", 1.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)) } };
+ Assert.Equal(new Choice(0, 77), Pick(none, hears, new Choice(0, 77), calm));
+ }
+
+ [Fact]
+ public void A_targeted_goal_with_no_percept_of_its_kinds_is_not_chosen()
+ {
+ var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Other)) } };
+ // A percept of another kind, and free slots (Id 0), make no pair.
+ var wrongKind = Hearing(At(1, 1f, Thing));
+ Assert.Equal(new Choice(0, 0), Pick(brain, wrongKind, new Choice(0, 0)));
+ Assert.Equal(new Choice(0, 0), Pick(brain, Ears(), new Choice(0, 0)));
+
+ var rightKind = Hearing(At(1, 1f, Thing), At(2, 3f, Other));
+ Assert.Equal(new Choice(1, 2), Pick(brain, rightKind, new Choice(0, 0)));
+
+ // Only targeted goals, none with a percept: the current choice stays.
+ var only = new Brain { Goals = new[] { Goal("chase", 5.0, Kinds(Other)) } };
+ Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 0)));
+ Assert.Equal(new Choice(0, 55), Pick(only, wrongKind, new Choice(0, 55)));
+ }
+
+ [Fact]
+ public void Considerations_multiply_priority_and_the_best_pair_wins()
+ {
+ // Distance: the nearer of two things.
+ var near = Hearing(At(1, 6f), At(2, 2f));
+ var go = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 2), Pick(go, near, default));
+
+ // Salience: the louder thing wins when the curve rises; the quieter when it falls.
+ var loud = Hearing(At(1, 1f, intensity: 0.2), At(2, 1f, intensity: 0.9));
+ var rising = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) }) } };
+ var falling = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 1.0, 0.0) }) } };
+ Assert.Equal(2UL, Pick(rising, loud, default).Target);
+ Assert.Equal(1UL, Pick(falling, loud, default).Target);
+
+ // Priority times the Drive curve: a goal at priority 4 whose Arousal curve zeroes it loses to priority 1.
+ var drained = new DriveState { Arousal = 0.0 };
+ var duel = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("brave", 4.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0, 1.0, DriveQuantity.Arousal) }),
+ Goal("plain", 1.0, Kinds(Thing)),
+ },
+ };
+ Assert.Equal(1, Pick(duel, near, default, drained).Goal);
+ Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 1.0 }).Goal);
+ Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 0.5 }).Goal); // 2.0 > 1.0
+
+ // The curve itself: clamped, shaped by the exponent, inverted by Y0 > Y1.
+ var c = new Consideration(ConsiderationInput.Salience, 2.0, 4.0, 0.0, 1.0, 2.0);
+ Assert.Equal(0.0, c.Response(1.0));
+ Assert.Equal(0.25, c.Response(3.0));
+ Assert.Equal(1.0, c.Response(9.0));
+ }
+
+ [Fact]
+ public void Ties_go_to_the_current_pair_then_lowest_goal_then_lowest_slot()
+ {
+ // Equal distance on either side of the observer: two equal scores in slots 0 and 1.
+ var twins = Hearing(At(10, 3f), At(20, -3f));
+ Assert.True(SlotOf(twins, 10) < SlotOf(twins, 20));
+ var one = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 10), Pick(one, twins, default)); // lowest slot
+ Assert.Equal(new Choice(0, 20), Pick(one, twins, new Choice(0, 20))); // the current pair
+ Assert.Equal(new Choice(0, 10), Pick(one, twins, new Choice(0, 10)));
+
+ var two = new Brain { Goals = new[] { Goal("a", 1.0, Kinds(Thing), new[] { Nearer(10.0) }), Goal("b", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 10), Pick(two, twins, new Choice(1, 99))); // lowest goal, then slot
+ Assert.Equal(new Choice(1, 20), Pick(two, twins, new Choice(1, 20))); // current beats the lower goal
+ }
+
+ [Fact]
+ public void Commitment_holds_the_current_target_until_a_challenger_beats_it_by_the_multiplier()
+ {
+ // Distance 2 scores 0.75, distance 4 scores 0.5 on a curve over 8.
+ var hears = Hearing(At(1, 4f), At(2, 2f));
+ Brain With(double commitment) => new() { TargetCommitment = commitment, Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }) } };
+ Assert.Equal(2UL, Pick(With(1.0), hears, new Choice(0, 1)).Target); // no commitment: the nearer wins
+ Assert.Equal(2UL, Pick(With(1.4), hears, new Choice(0, 1)).Target); // 0.5 * 1.4 = 0.70 < 0.75
+ Assert.Equal(1UL, Pick(With(1.5), hears, new Choice(0, 1)).Target); // 0.75 tie goes to the current pair
+ Assert.Equal(1UL, Pick(With(2.0), hears, new Choice(0, 1)).Target);
+ Assert.Equal(2UL, Pick(With(2.0), hears, default).Target); // the multiplier is for the current pair only
+
+ // It does not carry over to another goal's pair on the same target.
+ var rival = new Brain
+ {
+ TargetCommitment = 2.0,
+ Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }), Goal("flee", 1.2, Kinds(Thing), new[] { Nearer(8.0) }) },
+ };
+ Assert.Equal(new Choice(0, 1), Pick(rival, hears, new Choice(0, 1))); // 0.5 * 2.0 = 1.0 beats flee's 1.2 * 0.75 = 0.9, on the same thing or the nearer
+ Assert.Equal(new Choice(1, 2), Pick(rival, hears, default)); // uncommitted, flee on the nearer wins
+ }
+
+ private static Actor Hunter(Brain brain, int capacity = 4, double memory = 5.0) =>
+ new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
+
+ private static TickEvents Tick(Actor a, params Emitter[] emitters) =>
+ a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
+
+ [Fact]
+ public void A_retarget_waits_the_latency_and_fires_no_goal_change_or_entry_effect()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("idle", 0.0),
+ new GoalSpec
+ {
+ Id = "chase", Priority = 1.0, EntryResolve = 0.9, Effort = 0.1, Target = Kinds(Thing), Considerations = new[] { Nearer(30.0) },
+ When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0) },
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+ var a = Hunter(brain);
+ // Takes over the goal and the nearer thing, a latency after it is first heard.
+ var changes = 0;
+ for (var i = 0; i < 40; i++) changes += (Tick(a, At(1, 5f), At(2, 9f)) & TickEvents.GoalChanged) != 0 ? 1 : 0;
+ Assert.Equal(1, changes);
+ Assert.Equal(1, a.GoalIndex);
+ Assert.Equal(1UL, a.TargetId);
+ Assert.Equal(1UL, a.Target.Id);
+
+ for (var i = 0; i < 50; i++) Tick(a, At(1, 5f), At(2, 9f));
+ var inGoal = a.SecondsInGoal;
+ var resolve = a.Drive.Resolve;
+ Assert.True(resolve < 0.89, "the goal's effort should have drained resolve below its entry value by now");
+
+ // Thing 2 comes closer than thing 1: the pair changes a latency later, and nothing else does.
+ long first = -1;
+ for (var i = 0; i < 30; i++)
+ {
+ var e = Tick(a, At(1, 5f), At(2, 1f));
+ Assert.Equal(TickEvents.None, e & TickEvents.GoalChanged);
+ if (first < 0 && a.TargetId == 2) first = i;
+ if (first < 0)
+ {
+ Assert.Equal(1UL, a.TargetId);
+ Assert.Equal(1, a.GoalIndex);
+ }
+ }
+
+ Assert.Equal(10, first); // Latency: round(0.1 s / 10 ms)
+ Assert.Equal(2UL, a.Target.Id);
+ Assert.Equal(inGoal + 30 * Dt, a.SecondsInGoal, 9);
+ Assert.True(a.Drive.Resolve < resolve, "EntryResolve must not be applied again by a retarget: resolve keeps draining");
+ }
+
+ [Fact]
+ public void A_forgotten_target_reads_id_zero_and_the_brain_reselects()
+ {
+ var brain = new Brain { Goals = new[] { Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) } };
+ var a = Hunter(brain, capacity: 2, memory: 0.2);
+ for (var i = 0; i < 30; i++) Tick(a, At(1, 2f), At(2, 9f));
+ Assert.Equal(1UL, a.TargetId);
+
+ // Thing 1 stops sounding and is forgotten after its memory; its slot is taken by thing 3, which must not be read as the target.
+ var window = false;
+ for (var i = 0; i < 120 && a.TargetId == 1; i++)
+ {
+ Tick(a, At(2, 9f), At(3, 15f));
+ if (a.TargetId == 1 && a.Target.Id == 0) window = true;
+ Assert.NotEqual(3UL, a.Target.Id);
+ }
+
+ Assert.True(window, "the committed id outlived its percept, which should read as the default percept");
+ Assert.Equal(2UL, a.TargetId);
+ Assert.Equal(2UL, a.Target.Id);
+ }
+
+ [Fact]
+ public void Target_filters_and_considerations_are_validated()
+ {
+ static Actor Make(GoalSpec g, double commitment = 1.0) => new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { g }, TargetCommitment = commitment });
+ var ok = Goal("ok", 1.0, Kinds(Thing), new[] { Nearer(5.0) });
+ Make(ok);
+
+ var bad = new Action[]
+ {
+ () => Make(Goal("g", 1.0, Kinds())),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, double.NaN, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, double.PositiveInfinity, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 2.0, 2.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, -0.1, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.1) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, 0.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, double.NaN) })),
+ () => Make(Goal("g", 1.0, null, new[] { Nearer(5.0) })),
+ () => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", -1.0, Kinds(Thing))),
+ () => Make(Goal("g", -1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(ok, 0.99),
+ () => Make(ok, double.NaN),
+ () => Make(ok, double.PositiveInfinity),
+ };
+ for (var i = 0; i < bad.Length; i++)
+ {
+ Assert.True(Throws(bad[i]), $"case {i} was accepted");
+ }
+
+ // A negative priority stays legal on a goal with neither.
+ Make(Goal("g", -1.0));
+ Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) }));
+
+ static bool Throws(Action a)
+ {
+ try { a(); return false; }
+ catch (ArgumentException e) { return e.Message.Contains("g") || e.Message.Contains("TargetCommitment"); }
+ }
+ }
+
+ [Fact]
+ public void Ticking_with_targets_allocates_nothing()
+ {
+ var brain = new Brain
+ {
+ TargetCommitment = 1.2,
+ Goals = new[]
+ {
+ Goal("idle", 0.0),
+ Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0), new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.2, 1.0), new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.5, 1.0, 1.0, DriveQuantity.Arousal) }),
+ },
+ };
+ var a = Hunter(brain);
+ var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
+ for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++)
+ {
+ emitters[1] = At(2, 9f - (i % 8));
+ a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters);
+ }
+
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ Assert.NotEqual(0UL, a.TargetId);
+ }
+}