diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs new file mode 100644 index 0000000..b5ea509 --- /dev/null +++ b/src/Lodur.Core/Actor.cs @@ -0,0 +1,114 @@ +using System; + +namespace Lodur +{ + /// What happened on one tick. + [Flags] + public enum TickEvents + { + None = 0, + /// A reflex flinched while the will still held. + Flinch = 1, + /// Resolve reached zero this tick. + WillBroke = 2, + /// Deliberate behaviour took over, the withdrawal latency after the will broke. + Withdrew = 4, + } + + /// + /// One character's nervous state and the per-tick order: perception, reflex, drive, behaviour. The caller + /// supplies one point per body region, the game's stimulus sources, and the spans the behaviour writes its + /// strengths and targets into; the Actor writes nothing else of the caller's and never touches physics. + /// Everything is allocated in the constructor, and the same inputs give the same outputs. + /// + public sealed class Actor + { + private readonly double _dt; + private readonly DriveParameters _driveP; + private readonly long _withdrawLatency; + private readonly Perception _perception; + private readonly WithdrawalReflex[] _reflexes; + private readonly HoldAgainstReflex _behaviour; + private DriveState _drive = DriveState.Fresh; + private long _tick; + private long _withdrawTick = -1; + private bool _withdrew; + + public Actor( + double tickSeconds, int regionCount, + NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, HoldParameters hold, + ReadOnlySpan holdPose, ReadOnlySpan withdrawPose) + { + _dt = tickSeconds; + _driveP = drive; + _withdrawLatency = Math.Max(1, (long)Math.Round(withdrawal.LatencySeconds / tickSeconds)); + _perception = new Perception(nerve, tickSeconds, regionCount); + _reflexes = new WithdrawalReflex[regionCount]; + for (var r = 0; r < regionCount; r++) + { + _reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds); + } + + _behaviour = new HoldAgainstReflex(hold, holdPose, withdrawPose); + } + + public int RegionCount => _reflexes.Length; + + /// Ticks run so far. + public long TickCount => _tick; + + /// A snapshot of the drive; nothing but writes it. + public DriveState Drive => _drive; + + /// Hold until the will breaks, Withdraw from then on. + public Goal Goal => _drive.WillBroken ? Goal.Withdraw : Goal.Hold; + + public double Stimulus(int region) => _perception.Stimulus(region); + + public double Afferent(int region) => _perception.Afferent(region); + + /// + /// 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. + /// + public TickEvents Tick( + ReadOnlySpan regionX, ReadOnlySpan regionY, ReadOnlySpan regionZ, + ReadOnlySpan sources, Span strengths, Span targets) + { + var events = TickEvents.None; + var holding = !_drive.WillBroken; + + _perception.Sense(regionX, regionY, regionZ, sources); + + double afferent = 0.0, strainLoad = 0.0, leak = 0.0; + for (var r = 0; r < _reflexes.Length; r++) + { + var a = _perception.Afferent(r); + var flinch = _reflexes[r].Step(a, _drive); + afferent += a; + strainLoad += _reflexes[r].StrainLoad; + leak += _reflexes[r].Leak; + if (flinch && holding) + { + events |= TickEvents.Flinch; + } + } + + if (_drive.Step(_driveP, _dt, afferent, strainLoad)) + { + events |= TickEvents.WillBroke; + _withdrawTick = _tick + _withdrawLatency; + } + + if (_tick == _withdrawTick) + { + events |= TickEvents.Withdrew; + _withdrew = true; + } + + _behaviour.Write(_withdrew ? Goal.Withdraw : Goal.Hold, leak, _drive.Strain, _tick * _dt, strengths, targets); + _tick++; + return events; + } + } +} diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs new file mode 100644 index 0000000..ed55aac --- /dev/null +++ b/src/Lodur.Core/DriveState.cs @@ -0,0 +1,59 @@ +using System; + +namespace Lodur +{ + /// The drive's tunables: how pain and strain accumulate, and how they drain the will. + public sealed record DriveParameters + { + public double PainRise { get; init; } = 1.0; + public double PainDecay { get; init; } = 0.05; + public double StrainRecover { get; init; } = 0.1; + public double ResolveDrainPain { get; init; } = 0.012; + public double ResolveDrainStrain { get; init; } = 0.05; + public double ResolveRecovery { get; init; } = 0.02; + public double ResolveRecoversBelowPain { get; init; } = 0.1; + + /// How hard the objective pulls, 0..1. It scales resolve drain by (1 - pull); it is not a second resolve bar. + public double ObjectivePull { get; init; } = 0.5; + + /// Per-character multiplier on resolve drain (the consumer draws its trait spread). + public double DrainTrait { get; init; } = 1.0; + } + + /// + /// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the + /// reflex held down, resolve drains under both and recovers when pain is low. Resolve reaching zero breaks + /// the will, and a broken will never mends. Only the owning steps it. + /// + public struct DriveState + { + public double Pain { get; private set; } + public double Strain { get; private set; } + public double Resolve { get; private set; } + public bool WillBroken { get; private set; } + + internal static DriveState Fresh => new DriveState { Resolve = 1.0 }; + + /// Steps one tick; returns true on the tick the will breaks. + internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad) + { + Pain = Math.Min(Math.Max(Pain + dt * (p.PainRise * afferent * (1.0 - Pain) - p.PainDecay * Pain), 0.0), 1.0); + Strain = Math.Max(0.0, Strain + dt * (strainLoad - p.StrainRecover * Strain)); + if (WillBroken) + { + return false; + } + + var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain) * (1.0 - p.ObjectivePull) * p.DrainTrait; + var recovery = Pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - Resolve) : 0.0; + Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0); + if (Resolve <= 0.0) + { + WillBroken = true; + return true; + } + + return false; + } + } +} diff --git a/src/Lodur.Core/HoldAgainstReflex.cs b/src/Lodur.Core/HoldAgainstReflex.cs new file mode 100644 index 0000000..45c63ad --- /dev/null +++ b/src/Lodur.Core/HoldAgainstReflex.cs @@ -0,0 +1,81 @@ +using System; + +namespace Lodur +{ + /// What a character is trying to do. Today: hold against the reflex, or withdraw. + public enum Goal + { + Hold, + Withdraw, + } + + /// The layer-4 stand-in's tunables. + public sealed record HoldParameters + { + /// Muscle strength written for every muscle, in [0, 1] (above 1 an explicit PD arm sags and drifts). + public float HoldStrength { get; init; } = 1f; + + /// How far the reflex leak pulls the pose from hold toward withdraw, per unit of leak. + public double FlinchGain { get; init; } = 0.3; + + /// Strain shake amplitude (blend fraction) per unit of strain. Zero strain, no shake. + public double StrainShake { get; init; } = 0.03; + + /// Shake frequency. A few Hz: the arm's PD filters anything faster to nothing. + public double ShakeHz { get; init; } = 3.5; + } + + /// + /// Layer 4 stand-in: hold a pose against the withdrawal reflex. The target is the hold pose blended toward + /// the withdraw pose by the reflex leak and a strain-scaled shake; once the goal is Withdraw it is the + /// withdraw pose. It writes per-muscle strength and target rotation into the caller's spans and nothing else + /// (invariant body-one-interface). The poses are the caller's data, one rotation per muscle. + /// + public sealed class HoldAgainstReflex + { + private readonly HoldParameters _p; + private readonly Quat[] _hold; + private readonly Quat[] _withdraw; + + public HoldAgainstReflex(HoldParameters parameters, ReadOnlySpan holdPose, ReadOnlySpan withdrawPose) + { + if (holdPose.Length != withdrawPose.Length) + { + throw new ArgumentException("The hold and withdraw poses need one rotation per muscle each."); + } + + _p = parameters; + _hold = holdPose.ToArray(); + _withdraw = withdrawPose.ToArray(); + } + + public int MuscleCount => _hold.Length; + + /// The blend toward the withdraw pose: 1 once withdrawing, else the clamped leak and shake. + public double Blend(Goal goal, double leak, double strain, double seconds) + { + if (goal == Goal.Withdraw) + { + return 1.0; + } + + var w = leak * _p.FlinchGain + _p.StrainShake * strain * Math.Sin(2.0 * Math.PI * _p.ShakeHz * seconds); + return Math.Min(Math.Max(w, 0.0), 1.0); + } + + public void Write(Goal goal, double leak, double strain, double seconds, Span strengths, Span targets) + { + if (strengths.Length != _hold.Length || targets.Length != _hold.Length) + { + throw new ArgumentException($"strengths and targets need {_hold.Length} entries, one per muscle."); + } + + var w = (float)Blend(goal, leak, strain, seconds); + for (var m = 0; m < _hold.Length; m++) + { + strengths[m] = _p.HoldStrength; + targets[m] = Quat.Nlerp(_hold[m], _withdraw[m], w); + } + } + } +} diff --git a/src/Lodur.Core/IsExternalInit.cs b/src/Lodur.Core/IsExternalInit.cs new file mode 100644 index 0000000..a925713 --- /dev/null +++ b/src/Lodur.Core/IsExternalInit.cs @@ -0,0 +1,7 @@ +// Lets C# 9 records use init accessors on netstandard2.1, which does not ship this marker type. +namespace System.Runtime.CompilerServices +{ + internal static class IsExternalInit + { + } +} diff --git a/src/Lodur.Core/PdMuscle.cs b/src/Lodur.Core/PdMuscle.cs index 05c0cb1..33e2ead 100644 --- a/src/Lodur.Core/PdMuscle.cs +++ b/src/Lodur.Core/PdMuscle.cs @@ -30,6 +30,18 @@ namespace Lodur return new Quat(x * s, y * s, z * s, MathF.Cos(half)); } + /// Normalised linear blend from (t = 0) to (t = 1), the shorter way round. + public static Quat Nlerp(in Quat a, in Quat b, float t) + { + var s = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f; + var x = a.X + t * (s * b.X - a.X); + var y = a.Y + t * (s * b.Y - a.Y); + var z = a.Z + t * (s * b.Z - a.Z); + var w = a.W + t * (s * b.W - a.W); + var inv = 1f / MathF.Sqrt(x * x + y * y + z * z + w * w); + return new Quat(x * inv, y * inv, z * inv, w * inv); + } + /// Rotates the vector v by this quaternion. public void Rotate(float vx, float vy, float vz, out float rx, out float ry, out float rz) { diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs new file mode 100644 index 0000000..fba72f1 --- /dev/null +++ b/src/Lodur.Core/Perception.cs @@ -0,0 +1,115 @@ +using System; + +namespace Lodur +{ + /// + /// A game stimulus: an axis-aligned box volume with an intensity the game writes every tick. Lodur reads + /// it and decides containment and transduction; the box is never a physics body. + /// + public struct BoxStimulus + { + public float CenterX, CenterY, CenterZ; + public float HalfX, HalfY, HalfZ; + + /// Noxious intensity inside the box, written by the game each tick (0..1 in the slice's scale). + public double Intensity; + + public BoxStimulus(float centerX, float centerY, float centerZ, float halfX, float halfY, float halfZ, double intensity = 0.0) + { + CenterX = centerX; CenterY = centerY; CenterZ = centerZ; + HalfX = halfX; HalfY = halfY; HalfZ = halfZ; + Intensity = intensity; + } + + /// True when the point is inside the box or on one of its faces. + public bool Contains(float x, float y, float z) => + MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ; + } + + /// The nerve's tunables: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain. + public sealed record NerveParameters + { + public double NociceptorThreshold { get; init; } = 0.1; + public double SensitisationGrowth { get; init; } = 0.04; + public double SensitisationRecovery { get; init; } = 0.02; + public double SensitisationCap { get; init; } = 2.0; + public double ConductionDelaySeconds { get; init; } = 0.06; + + /// Per-character nociceptor gain (the consumer draws its trait spread). + public double Gain { get; init; } = 1.0; + } + + /// + /// Layer 1 for one character, a fixed number of body regions. Each tick it takes one point per region and the + /// game's stimulus sources and produces, per region, the stimulus there and the afferent signal after + /// threshold, sensitisation and conduction delay. Everything is allocated in the constructor. + /// + public sealed class Perception + { + private readonly NerveParameters _p; + private readonly double _dt; + private readonly int _regions; + private readonly int _slots; + private readonly double[] _ring; // afferent signal in flight along the nerve, region-major + private readonly double[] _sens; + private readonly double[] _stimulus; + private readonly double[] _afferent; + private long _tick; + + public Perception(NerveParameters parameters, double tickSeconds, int regionCount) + { + _p = parameters; + _dt = tickSeconds; + _regions = regionCount; + var delayTicks = (int)Math.Round(parameters.ConductionDelaySeconds / tickSeconds); + _slots = Math.Max(1, delayTicks); + _ring = new double[regionCount * _slots]; + _sens = new double[regionCount]; + Array.Fill(_sens, 1.0); + _stimulus = new double[regionCount]; + _afferent = new double[regionCount]; + } + + public int RegionCount => _regions; + + /// The stimulus at the region's point this tick: the largest intensity among the boxes containing it. + public double Stimulus(int region) => _stimulus[region]; + + /// The afferent signal arriving this tick: what the nerve took in a conduction delay ago. + public double Afferent(int region) => _afferent[region]; + + /// Senses once per physics step. The spans are the caller's, one point per region. + public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources) + { + if (x.Length != _regions || y.Length != _regions || z.Length != _regions) + { + throw new ArgumentException($"x, y and z need {_regions} entries, one per region."); + } + + var slot = (int)(_tick % _slots); + for (var r = 0; r < _regions; r++) + { + var stimulus = 0.0; + for (var i = 0; i < sources.Length; i++) + { + if (sources[i].Intensity > stimulus && sources[i].Contains(x[r], y[r], z[r])) + { + stimulus = sources[i].Intensity; + } + } + + // Nociceptor: threshold, then sensitisation, then conduction delay. + var above = Math.Max(0.0, stimulus - _p.NociceptorThreshold); + var sens = _sens[r] + _dt * (_p.SensitisationGrowth * above - _p.SensitisationRecovery * (_sens[r] - 1.0)); + sens = Math.Min(Math.Max(sens, 1.0), _p.SensitisationCap); + _sens[r] = sens; + var ring = r * _slots + slot; + _afferent[r] = _ring[ring]; // written one conduction delay ago + _ring[ring] = above * sens * _p.Gain; + _stimulus[r] = stimulus; + } + + _tick++; + } + } +} diff --git a/src/Lodur.Core/WithdrawalReflex.cs b/src/Lodur.Core/WithdrawalReflex.cs new file mode 100644 index 0000000..0655188 --- /dev/null +++ b/src/Lodur.Core/WithdrawalReflex.cs @@ -0,0 +1,57 @@ +using System; + +namespace Lodur +{ + /// The withdrawal reflex's tunables, and the latency of the deliberate withdrawal that takes over from it. + public sealed record WithdrawalParameters + { + /// How much of the reflex a fully resolved will can hold down (0..1). + public double MaxSuppression { get; init; } = 0.95; + public double FlinchLeakThreshold { get; init; } = 0.3; + public double FlinchRefractorySeconds { get; init; } = 0.5; + + /// How long after the will breaks deliberate behaviour withdraws. + public double LatencySeconds { get; init; } = 0.1; + } + + /// + /// Layer 2 for one body region. Its gain is set ahead of time by the drive: it reads the drive state the + /// previous tick left, before the drive steps (invariant reflex-gain-from-drive). What the suppression holds + /// down is the strain load; what leaks past is the reflex command and, over the threshold, a flinch. + /// + public sealed class WithdrawalReflex + { + private readonly WithdrawalParameters _p; + private readonly long _refractory; + private long _tick; + private long _lastFlinch = long.MinValue / 2; + + public WithdrawalReflex(WithdrawalParameters parameters, double tickSeconds) + { + _p = parameters; + _refractory = (long)Math.Round(parameters.FlinchRefractorySeconds / tickSeconds); + } + + /// The part of the afferent signal that gets past the will this tick. + public double Leak { get; private set; } + + /// The part the will holds down this tick: the strain the drive accumulates. + public double StrainLoad { get; private set; } + + /// Steps once; returns true on a flinch (leak over the threshold, outside the refractory window). + public bool Step(double afferent, in DriveState drive) + { + var suppression = drive.WillBroken ? 0.0 : _p.MaxSuppression * drive.Resolve; + Leak = afferent * (1.0 - suppression); + StrainLoad = afferent * suppression; + var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory; + if (flinch) + { + _lastFlinch = _tick; + } + + _tick++; + return flinch; + } + } +}