diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..e0c0bf4
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,7 @@
+
+
+
+ $(LODUR_ROOT)
+ $(MSBuildThisFileDirectory)..\Lodur
+
+
diff --git a/docs/pain-sweep.md b/docs/pain-sweep.md
index d8d6038..b409db0 100644
--- a/docs/pain-sweep.md
+++ b/docs/pain-sweep.md
@@ -2,7 +2,7 @@
`tools/PainSweep/Program.cs` runs the pain box puppet over a grid of box
intensity (rows) and withdrawal-reflex suppression strength (columns,
-`PainBoxParameters.MaxSuppression`: the largest fraction of the reflex the will
+`PainBoxParameters.Reflex.MaxSuppression`: the largest fraction of the reflex the will
can hold down). It is engine-free and deterministic; the same build prints the
same table.
@@ -41,14 +41,11 @@ first flinch, flinch count, area under the pain curve before the hand leaves,
peak strain, or the fraction of seeds that break by a deadline. Which one says
what a player should feel?
-## Build and run (no `dotnet restore`)
+## Build and run
```
-D=/opt/commons/opt/dotnet; REF=$D/packs/Microsoft.NETCore.App.Ref/10.0.14/ref/net10.0
-dotnet $D/sdk/10.0.403/Roslyn/bincore/csc.dll -nologo -nullable:enable -target:exe \
- -out:$TMPDIR/painsweep/PainSweep.dll -noconfig -nostdlib+ $(for f in $REF/*.dll; do echo -n "-r:$f "; done) \
- src/BadDay.Core/*.cs tools/PainSweep/Program.cs
-printf '{"runtimeOptions":{"tfm":"net10.0","framework":{"name":"Microsoft.NETCore.App","version":"10.0.14"}}}' \
- > $TMPDIR/painsweep/PainSweep.runtimeconfig.json
-dotnet $TMPDIR/painsweep/PainSweep.dll
+dotnet run --project tools/PainSweep
```
+
+The project references `BadDay.Core` and through it the sibling Lodur checkout (`LODUR_ROOT`, else
+`..\Lodur`); it needs no Ymir and no native build.
diff --git a/src/BadDay.Cli/Program.cs b/src/BadDay.Cli/Program.cs
index ec383ba..da55d74 100644
--- a/src/BadDay.Cli/Program.cs
+++ b/src/BadDay.Cli/Program.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using BadDay.Core;
+using Lodur;
namespace BadDay.Cli;
@@ -39,7 +40,7 @@ public static class Program
var p = new PainBoxParameters
{
BoxIntensity = Num(opts, "intensity", 0.8),
- ObjectivePull = Num(opts, "pull", 0.5),
+ Drive = new DriveParameters { ObjectivePull = Num(opts, "pull", 0.5) },
BoxDisableAtSeconds = opts.ContainsKey("disable-at") ? Num(opts, "disable-at", 0) : null,
MaxSeconds = Num(opts, "max", 120),
SampleEverySeconds = Num(opts, "every", 1),
diff --git a/src/BadDay.Core/BadDay.Core.csproj b/src/BadDay.Core/BadDay.Core.csproj
index 9488531..487f396 100644
--- a/src/BadDay.Core/BadDay.Core.csproj
+++ b/src/BadDay.Core/BadDay.Core.csproj
@@ -5,4 +5,7 @@
disable
BadDay.Core
+
+
+
diff --git a/src/BadDay.Core/PainBox.cs b/src/BadDay.Core/PainBox.cs
new file mode 100644
index 0000000..d9eccce
--- /dev/null
+++ b/src/BadDay.Core/PainBox.cs
@@ -0,0 +1,37 @@
+using System;
+using Lodur;
+
+namespace BadDay.Core;
+
+///
+/// The game's box: its schedule. A noxious intensity ramped in with seeded jitter, switched off at the disable
+/// time. It writes the intensity of a Lodur and nothing else; what the intensity does
+/// to a character is Lodur's.
+///
+public sealed class PainBox
+{
+ private readonly PainBoxParameters _p;
+ private readonly SplitMix64 _rng;
+
+ public PainBox(PainBoxParameters parameters, SplitMix64 rng)
+ {
+ _p = parameters;
+ _rng = rng;
+ DisableTick = parameters.BoxDisableAtSeconds is { } d
+ ? (long)Math.Round(d / parameters.TickSeconds)
+ : long.MaxValue;
+ }
+
+ /// The first tick the box is off; when it is never disabled.
+ public long DisableTick { get; }
+
+ /// Writes this tick's intensity. Always draws the jitter, so the stream does not depend on state.
+ public void Write(long tick, ref BoxStimulus box)
+ {
+ double jitter = _rng.NextSigned();
+ double ramp = Math.Min(1.0, tick * _p.TickSeconds / _p.BoxRampSeconds);
+ box.Intensity = tick < DisableTick
+ ? Math.Max(0.0, _p.BoxIntensity * ramp * (1.0 + _p.BoxNoise * jitter))
+ : 0.0;
+ }
+}
diff --git a/src/BadDay.Core/PainBoxParameters.cs b/src/BadDay.Core/PainBoxParameters.cs
index 7e3f3d8..518df6d 100644
--- a/src/BadDay.Core/PainBoxParameters.cs
+++ b/src/BadDay.Core/PainBoxParameters.cs
@@ -19,33 +19,14 @@ public sealed record PainBoxParameters
/// When set, the box switches off at this time (the game disables it).
public double? BoxDisableAtSeconds { get; init; }
- // Nerve: threshold, sensitisation under sustained stimulus, conduction delay.
- 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;
+ // The nervous model is Lodur's: nerve, drive, reflex and the hold behaviour keep their records and defaults.
+ // Hold matters to the body run only; the headless run ignores what it writes.
+ public Lodur.NerveParameters Nerve { get; init; } = new();
+ public Lodur.DriveParameters Drive { get; init; } = new();
+ public Lodur.WithdrawalParameters Reflex { get; init; } = new();
+ public Lodur.HoldParameters Hold { get; init; } = new();
- // Drive: pain, strain from holding a reflex down, resolve.
- 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;
-
- // Reflex: how much of it will can hold down, and the latencies.
- public double MaxSuppression { get; init; } = 0.95;
- public double FlinchLeakThreshold { get; init; } = 0.3;
- public double FlinchRefractorySeconds { get; init; } = 0.5;
- public double WithdrawalLatencySeconds { get; init; } = 0.1;
-
- // Goals: how hard the objective ("keep the hand in the box") 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-seed trait spread (fraction): nociceptor gain and resolve drain.
+ // Per-seed trait spread (fraction): nociceptor gain (Nerve.Gain) and resolve drain (Drive.DrainTrait).
public double TraitJitter { get; init; } = 0.2;
public double SampleEverySeconds { get; init; } = 1.0;
diff --git a/src/BadDay.Core/PainBoxSession.cs b/src/BadDay.Core/PainBoxSession.cs
new file mode 100644
index 0000000..12762a6
--- /dev/null
+++ b/src/BadDay.Core/PainBoxSession.cs
@@ -0,0 +1,137 @@
+using System;
+using System.Collections.Generic;
+using Lodur;
+
+namespace BadDay.Core;
+
+///
+/// One run of the pain box: the seed's traits, the box schedule, a Lodur , and the recorder.
+/// The headless run and the body run both drive it, one per step, and differ only in where
+/// the hand point comes from and what ends the run. The session decides nothing about the character: the
+/// timeline rows are end-of-tick state read from the Actor, and nothing reads them back.
+///
+public sealed class PainBoxSession
+{
+ private readonly PainBoxParameters _p;
+ private readonly PainBox _box;
+ private readonly BoxStimulus[] _sources;
+ private readonly List _timeline = new();
+ private readonly long _maxTick;
+ private readonly long _sampleEvery;
+ private double _stimulus;
+ private long _breakTick = -1;
+ private int _flinches;
+ private Outcome _outcome = Outcome.Endured;
+ private long _endTick;
+
+ /// The stimulus volume the hand is held in; its intensity is the session's to write.
+ public PainBoxSession(PainBoxParameters p, ulong seed, BoxStimulus box, int regionCount,
+ ReadOnlySpan holdPose, ReadOnlySpan withdrawPose)
+ {
+ _p = p;
+ var rng = new SplitMix64(seed);
+ // Per-seed traits, drawn first and in fixed order so the stream never shifts.
+ double gainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
+ double drainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
+ Seed = seed;
+ Actor = new Actor(p.TickSeconds, regionCount, p.Nerve with { Gain = gainTrait }, p.Reflex,
+ p.Drive with { DrainTrait = drainTrait }, p.Hold, holdPose, withdrawPose);
+ _box = new PainBox(p, rng);
+ _sources = new[] { box };
+ _maxTick = Ticks(p.MaxSeconds);
+ _sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds));
+ _endTick = _maxTick;
+ }
+
+ public ulong Seed { get; }
+ public Actor Actor { get; }
+
+ /// The stimulus volume, with this tick's intensity once has run.
+ public ref readonly BoxStimulus Box => ref _sources[0];
+
+ /// Ticks run so far; the tick the next runs.
+ public long TickIndex => Actor.TickCount;
+
+ /// True once the run is over: the box was disabled, the time ran out, or the caller ended it.
+ public bool Finished { get; private set; }
+
+ /// True from the tick the deliberate withdrawal begins.
+ public bool Withdrew { get; private set; }
+
+ ///
+ /// The disable check, before ticking: if the box switches off now while the will still holds, the run ends
+ /// with the will intact and this returns true. A will already broken is not given back by the box going off.
+ ///
+ public bool Disabled()
+ {
+ long tick = TickIndex;
+ if (tick != _box.DisableTick || Actor.Goal != Lodur.Goal.Hold) return false;
+ _stimulus = 0.0;
+ _outcome = Outcome.BoxDisabled;
+ _endTick = tick;
+ Log(tick, EntryKind.BoxDisabled);
+ Finished = true;
+ return true;
+ }
+
+ ///
+ /// One step: the box writes its intensity, the Actor runs on the caller's hand points and writes the
+ /// caller's strengths and targets, and the tick's rows are logged from the flags and the end-of-tick state.
+ ///
+ public TickEvents Tick(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z,
+ Span strengths, Span targets)
+ {
+ long tick = TickIndex;
+ _box.Write(tick, ref _sources[0]);
+ var events = Actor.Tick(x, y, z, _sources, strengths, targets);
+ _stimulus = Actor.Stimulus(0);
+
+ if ((events & TickEvents.Flinch) != 0)
+ {
+ _flinches++;
+ Log(tick, EntryKind.Flinch);
+ }
+ if ((events & TickEvents.WillBroke) != 0)
+ {
+ _breakTick = tick;
+ Log(tick, EntryKind.WillBroke);
+ }
+ if (tick % _sampleEvery == 0) Log(tick, EntryKind.Sample);
+ if ((events & TickEvents.Withdrew) != 0)
+ {
+ Withdrew = true;
+ _outcome = Outcome.WillBroke;
+ _endTick = tick;
+ Log(tick, EntryKind.Withdrew);
+ }
+ else if (tick == _maxTick && _outcome == Outcome.Endured)
+ {
+ Log(tick, EntryKind.Endured);
+ }
+ if (tick >= _maxTick) Finished = true;
+ return events;
+ }
+
+ /// Ends the run at instead of where the session would (the body run ends when the hand is out).
+ public void EndAt(long tick)
+ {
+ _endTick = tick;
+ Finished = true;
+ }
+
+ public PainBoxResult Result() => new(
+ Seed, _outcome, Ms(_endTick),
+ _breakTick >= 0 ? Ms(_breakTick) : null,
+ _flinches, _timeline);
+
+ public long Ms(long tick) => (long)Math.Round(tick * _p.TickSeconds * 1000.0);
+
+ private long Ticks(double seconds) => (long)Math.Round(seconds / _p.TickSeconds);
+
+ private void Log(long tick, EntryKind kind)
+ {
+ var d = Actor.Drive;
+ _timeline.Add(new TimelineEntry(Ms(tick), kind, _stimulus, d.Pain, d.Strain, d.Resolve,
+ Actor.Goal == Lodur.Goal.Withdraw ? Goal.Withdraw : Goal.HoldHand));
+ }
+}
diff --git a/src/BadDay.Core/PainBoxSimulation.cs b/src/BadDay.Core/PainBoxSimulation.cs
index 3392f40..f612b71 100644
--- a/src/BadDay.Core/PainBoxSimulation.cs
+++ b/src/BadDay.Core/PainBoxSimulation.cs
@@ -1,124 +1,27 @@
-using System;
-using System.Collections.Generic;
+using Lodur;
namespace BadDay.Core;
///
-/// One virtual human with a hand in a pain box. Layers follow Lodur's target
-/// (perception, reflex, drive, behaviour), flattened to one fixed-step loop:
-/// the box emits a stimulus, a nociceptor with sensitisation turns it into an
-/// afferent signal delayed by conduction, the delayed signal feeds pain and the
-/// withdrawal reflex, will (resolve) suppresses the reflex at a strain cost,
-/// and strain plus pain drain resolve. When resolve reaches zero the goal
-/// switches from HoldHand to Withdraw and the hand leaves after the reflex
-/// latency. There is no body, no physics and no balance here.
+/// The headless pain box: one virtual human with a hand fixed inside the box, run to the deliberate
+/// withdrawal. The nervous model (perception, reflex, drive, behaviour) is Lodur's ; this
+/// owns the box, the seed, the trait draw and the recorder. No body, no physics and no balance.
///
public static class PainBoxSimulation
{
public static PainBoxResult Run(PainBoxParameters p, ulong seed)
{
- var rng = new SplitMix64(seed);
- // Per-seed traits, drawn first and in fixed order so the stream never shifts.
- double gainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
- double drainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
-
- long maxTick = Ticks(p.MaxSeconds, p.TickSeconds);
- long disableTick = p.BoxDisableAtSeconds is { } d ? Ticks(d, p.TickSeconds) : long.MaxValue;
- long sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds, p.TickSeconds));
- long refractory = Ticks(p.FlinchRefractorySeconds, p.TickSeconds);
- long withdrawLatency = Math.Max(1, Ticks(p.WithdrawalLatencySeconds, p.TickSeconds));
- int delayTicks = (int)Ticks(p.ConductionDelaySeconds, p.TickSeconds);
-
- var delay = new double[Math.Max(1, delayTicks)]; // afferent signal in flight along the nerve
- double dt = p.TickSeconds;
- double sens = 1.0, pain = 0.0, strain = 0.0, resolve = 1.0, stimulus = 0.0;
- var goal = Goal.HoldHand;
- long lastFlinch = long.MinValue / 2;
- long breakTick = -1, withdrawTick = -1;
- int flinches = 0;
- var timeline = new List();
- var outcome = Outcome.Endured;
- long endTick = maxTick;
-
- void Log(long tick, EntryKind kind) => timeline.Add(new TimelineEntry(
- Ms(tick, p.TickSeconds), kind, stimulus, pain, strain, resolve, goal));
-
- for (long tick = 0; tick <= maxTick; tick++)
+ var pose = new[] { Quat.Identity };
+ var session = new PainBoxSession(p, seed, new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f), 1, pose, pose);
+ var point = new float[1]; // the hand sits at the box centre
+ var strengths = new float[1]; // the behaviour's output has no body to move
+ var targets = new Quat[1];
+ while (!session.Finished)
{
- bool boxOn = tick < disableTick;
- if (tick == disableTick && goal == Goal.HoldHand)
- {
- stimulus = 0.0;
- outcome = Outcome.BoxDisabled;
- endTick = tick;
- Log(tick, EntryKind.BoxDisabled);
- break;
- }
-
- // Box -> stimulus (always draw jitter so the stream is independent of state).
- double jitter = rng.NextSigned();
- double ramp = Math.Min(1.0, tick * dt / p.BoxRampSeconds);
- stimulus = boxOn ? Math.Max(0.0, p.BoxIntensity * ramp * (1.0 + p.BoxNoise * jitter)) : 0.0;
-
- // Nociceptor: threshold, sensitisation, then conduction delay.
- double above = Math.Max(0.0, stimulus - p.NociceptorThreshold);
- sens += dt * (p.SensitisationGrowth * above - p.SensitisationRecovery * (sens - 1.0));
- sens = Math.Clamp(sens, 1.0, p.SensitisationCap);
- int slot = (int)(tick % delay.Length);
- double arrived = delay[slot]; // written delayTicks ticks ago
- delay[slot] = above * sens * gainTrait;
-
- // Pain: afferent drives it up toward 1, it decays on its own.
- pain += dt * (p.PainRise * arrived * (1.0 - pain) - p.PainDecay * pain);
- pain = Math.Clamp(pain, 0.0, 1.0);
-
- // Reflex: will holds down a fraction of it; the leak is a flinch,
- // the effort of holding is strain. Not free, per reflex-gain-from-drive.
- double suppression = goal == Goal.HoldHand ? p.MaxSuppression * resolve : 0.0;
- double leak = arrived * (1.0 - suppression);
- if (goal == Goal.HoldHand && leak > p.FlinchLeakThreshold && tick - lastFlinch >= refractory)
- {
- lastFlinch = tick;
- flinches++;
- Log(tick, EntryKind.Flinch);
- }
- strain += dt * (arrived * suppression - p.StrainRecover * strain);
- strain = Math.Max(0.0, strain);
-
- // Will decays under load, scaled down by how hard the objective pulls.
- if (goal == Goal.HoldHand)
- {
- double drain = (p.ResolveDrainPain * pain + p.ResolveDrainStrain * strain)
- * (1.0 - p.ObjectivePull) * drainTrait;
- double recovery = pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - resolve) : 0.0;
- resolve = Math.Clamp(resolve + dt * (recovery - drain), 0.0, 1.0);
- if (resolve <= 0.0)
- {
- goal = Goal.Withdraw;
- breakTick = tick;
- withdrawTick = tick + withdrawLatency;
- Log(tick, EntryKind.WillBroke);
- }
- }
-
- if (tick % sampleEvery == 0) Log(tick, EntryKind.Sample);
-
- if (tick == withdrawTick)
- {
- outcome = Outcome.WillBroke;
- endTick = tick;
- Log(tick, EntryKind.Withdrew);
- break;
- }
- if (tick == maxTick) Log(tick, EntryKind.Endured);
+ if (session.Disabled()) break;
+ session.Tick(point, point, point, strengths, targets);
+ if (session.Withdrew) break;
}
-
- return new PainBoxResult(
- seed, outcome, Ms(endTick, p.TickSeconds),
- breakTick >= 0 ? Ms(breakTick, p.TickSeconds) : null,
- flinches, timeline);
+ return session.Result();
}
-
- private static long Ticks(double seconds, double tickSeconds) => (long)Math.Round(seconds / tickSeconds);
- private static long Ms(long tick, double tickSeconds) => (long)Math.Round(tick * tickSeconds * 1000.0);
}
diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs
index 3bf7dba..c42c1f2 100644
--- a/tests/BadDay.Tests/Program.cs
+++ b/tests/BadDay.Tests/Program.cs
@@ -66,7 +66,7 @@ public static class Program
("a stronger objective pull holds the will longer", () =>
{
long Break(double pull) =>
- PainBoxSimulation.Run(Default with { ObjectivePull = pull }, 5).TimeToBreakMs ?? long.MaxValue;
+ PainBoxSimulation.Run(Default with { Drive = Default.Drive with { ObjectivePull = pull } }, 5).TimeToBreakMs ?? long.MaxValue;
Check(Break(0.0) < Break(0.5) && Break(0.5) < Break(0.8), "break times not ordered by pull");
}),
diff --git a/tools/PainSweep/PainSweep.csproj b/tools/PainSweep/PainSweep.csproj
new file mode 100644
index 0000000..a3bdb90
--- /dev/null
+++ b/tools/PainSweep/PainSweep.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Exe
+ net10.0
+ enable
+ disable
+
+
+
+
+
diff --git a/tools/PainSweep/Program.cs b/tools/PainSweep/Program.cs
index e61b400..b987376 100644
--- a/tools/PainSweep/Program.cs
+++ b/tools/PainSweep/Program.cs
@@ -4,6 +4,7 @@ using System.Globalization;
using System.Linq;
using System.Text;
using BadDay.Core;
+using Lodur;
// Grid sweep: stimulus intensity (rows) x withdrawal-reflex suppression strength
// (columns, PainBoxParameters.MaxSuppression). Each cell runs Seeds consecutive
@@ -17,7 +18,7 @@ double[] suppressions = { 0.0, 0.25, 0.5, 0.75, 0.95, 1.0 };
var inv = CultureInfo.InvariantCulture;
var sb = new StringBuilder();
-sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pull {new PainBoxParameters().ObjectivePull:F2})\n");
+sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pull {new PainBoxParameters().Drive.ObjectivePull:F2})\n");
sb.Append("intensity\\suppr ");
foreach (var s in suppressions) sb.Append(s.ToString("F2", inv).PadLeft(10));
sb.Append('\n');
@@ -26,7 +27,7 @@ foreach (var i in intensities)
sb.Append(i.ToString("F2", inv).PadRight(16));
foreach (var s in suppressions)
{
- var p = new PainBoxParameters { BoxIntensity = i, MaxSuppression = s };
+ var p = new PainBoxParameters { BoxIntensity = i, Reflex = new WithdrawalParameters { MaxSuppression = s } };
var sweep = SweepSummary.Run(p, FirstSeed, Seeds);
string cell = sweep.MedianBreakMs is { } ms
? (ms / 1000.0).ToString("F1", inv) + (sweep.Broke < Seeds ? $"({sweep.Broke}/{Seeds})" : "")