diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..78ef940
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+*.sh text eol=lf
+tests/Lodur.Core.Tests/pain-box-golden.tsv text eol=lf
diff --git a/Lodur.slnx b/Lodur.slnx
index b755d72..3a5ebc3 100644
--- a/Lodur.slnx
+++ b/Lodur.slnx
@@ -1,5 +1,6 @@
+
diff --git a/README.md b/README.md
index b079601..b90a90b 100644
--- a/README.md
+++ b/README.md
@@ -4,16 +4,23 @@ A physics character middleware for characters that **feel and react**: they
pull back from something hot, jump when poked, and, if they want their
objective badly enough, crawl toward it after losing a leg.
-**Status: design plus a first slice of layer 5.** The design is
-[`docs/lodur-target.md`](docs/lodur-target.md); read it first. What runs today is a
-PD-muscle active ragdoll on Ymir's Box3D SoA world: [`docs/first-slice.md`](docs/first-slice.md)
-(measured and unmeasured). Layers 1-4 (perception, reflex, drive, behaviour) are not
-coded.
+**Status: layers 1-3 and a layer-4 stand-in run on a PD-muscle ragdoll on Ymir.** The
+design is [`docs/lodur-target.md`](docs/lodur-target.md); read it first. `Lodur.Core`
+holds perception, the withdrawal reflex, the drive state and a hold-against-reflex
+stand-in, run per character by `Actor`; `Lodur.Body.Ymir` is the PD-muscle active ragdoll
+on Ymir's Box3D SoA world ([`docs/first-slice.md`](docs/first-slice.md), measured and
+unmeasured). Behaviour selection beyond the stand-in, impairment and the learned tracker
+are not coded.
-Entry points: `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
-`src/Lodur.Body.Ymir/HumanoidRagdoll.cs` (the ragdoll and `Drive`), `tests/Lodur.Tests`
-(stand, fall, rest, same-seed-same-hash). Needs a sibling Ymir checkout at
-`main` (the SoA joints merge, 2026-11-10, or later); `dotnet test tests/Lodur.Tests` builds its native library with cmake.
+Entry points: `src/Lodur.Core/Actor.cs` (one character's nervous state, one tick per
+physics step), `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
+`src/Lodur.Body.Ymir/HumanoidRagdoll.cs` (the ragdoll, `Drive` and `ReadRegions`),
+`tests/Lodur.Core.Tests` (the layers and parity with the pain box; builds without Ymir),
+`tests/Lodur.Tests` (stand, fall, rest, same-seed-same-hash, and the connected pain box:
+`ConnectedPainBoxTests`). The map this was cut from is
+[`docs/connect-rungs-map.md`](docs/connect-rungs-map.md). Needs a sibling Ymir checkout at
+`main` (the SoA joints merge, 2026-11-10, or later); `dotnet test tests/Lodur.Tests` builds
+its native library with cmake.
## The problem
@@ -27,10 +34,12 @@ time. Lodur is that layer.
## Shape (planned)
- **Core** (C#, no engine references): perception, reflexes, a drive state of
- pain, shock, adrenaline and resolve that evolves every tick, and behaviour
- selection that turns the drive into targets plus muscle strength.
+ pain, shock, adrenaline and resolve that evolves every tick (the will breaks
+ at zero resolve and mends as it recovers, and can break again), and behaviour
+ selection that turns the drive into targets plus muscle strength, weighted by
+ the will available to each voluntary pose.
- **Body** (per engine): follows those targets on the engine's own articulated
- physics. v1 is a PD-tracking active ragdoll in Unity; v2 adds a small learned
+ physics. v1 is a PD-tracking active ragdoll on Ymir; v2 adds a small learned
tracker for upright balance behind the same interface.
## First consumer
diff --git a/docs/bds-mvp-map.md b/docs/bds-mvp-map.md
new file mode 100644
index 0000000..46366d8
--- /dev/null
+++ b/docs/bds-mvp-map.md
@@ -0,0 +1,344 @@
+# Bad Day Simulator MVP on Lodur and Ymir (map)
+
+Imagination pass `bds-mvp-map`, nibu-imagination, session nibu-self-2026-11-17, 2026-11-20.
+Serves `lodur:ruling:bds-mvp-scope` and `lodur:ruling:bds-sandbox-arenas-will-economy`, under target
+`lodur:target:r3`. Committed as `Lodur/docs/bds-mvp-map.md`; the bases, probes and body facts below are as of the pass (Modeling refreshed the state columns and the cut table on 2026-11-20, see "Landed since the pass"); the target r4 text below went to
+`docs/lodur-target.md` when Self admits r4.
+
+## Bases
+
+| Repo | Base | Note |
+|---|---|---|
+| GameCult/Ymir | `0b0321a` (main) | Box3D v0.1.0 at `extern/box3d` 8441b4a |
+| GameCult/Lodur | `1491bed` (read), main now `a048827` | rung 3 sensory load merged to main during this pass (a048827); Lodur anchors below are at 1491bed and move with it |
+| GameCult/BadDaySimulator | `a218c55` (main) | |
+| Godot client | none | a parallel Imagination maps `client-ready-sim`, `godot-client-v1`; not admitted at 5566 |
+
+In-flight specs this map sequences around (no report unless noted): `rung3-sensory-load` (merged), `rung3-office-stress`, `rung4-goal-flip`, `rung4-office-flip`.
+
+## Landed since the pass (Modeling, 2026-11-20; mains: Ymir `5104b17`, Lodur `f9e302e`, BDS `bd01101`)
+
+Body facts 1 and 8-10 below describe the bases, not today. What the cuts changed; the owners' inputs, outputs, derived
+state and forbidden writers are in `docs/lodur-target.md` ("Who writes what, per tick") and BDS's README ("Who owns
+what"); rulings and specs are cited by id, not restated.
+
+- **Ymir** (ABI 8): contact and hit facts with materials, exact per-step contact impulse, grab anchor, motor joint,
+ point impulse, ray, joint handles with generations, tombstoned joint lanes, and joint origin lanes (the joint
+ frame's origin in the world, on body A). Not landed: thresholds, overload facts, removal of bodies and joints
+ (`ymir-break-and-remove`, still refused by the API).
+- **Lodur**: the drive's will breaks and mends as a recurring event (`Breaks`, `WillMendsAt`); `Will` = min(resolve x
+ attention, consciousness) is derived; every voluntary pose is written at `Will^WillCurve` (the will mix), an
+ involuntary goal onset at full weight; goals carry `EntryResolve`, `Effort`, `InvoluntarySeconds`, and `SensoryGain`,
+ `EntryArousal`, `EntrySeconds` (the Actor ramps gain and arousal over the entry, Perception gates the sense channels
+ with the gain and refuses one outside [0, 1]). Startle (the Attention writer) and physiology (the Consciousness
+ writer) are not built.
+- **BDS**: the chamber and the office are scenarios on one stepping session each; the office arc is snap, rage, calm
+ (the stress column is arousal), and each scenario's release goal is declared by id. The Godot client draws the
+ body run as one skinned SDF puppet: `PuppetField` meshes, `PuppetModel` owns bind, signature and rebuild,
+ `PuppetSkin` skins every frame and derives the surface, `Puppet` owns the Godot mesh and the build counter, the
+ shader only draws the bevel, `RenderCheck` is the windowed oracle. Not landed: a sandbox session, commands,
+ levels, runtime bodies.
+
+## Body facts (probes)
+
+All probes 2026-11-20, read-only on `F:\Projects`; the C probe is
+`scratchpad/imag-mvp/probe/probe.c`, built with StrawberryPerl gcc 13.2
+(`gcc -O1 -std=c17 -mavx2 -I extern/box3d/include -I extern/box3d/src probe.c extern/box3d/src/*.c`)
+against Ymir's pinned Box3D, sphere r 0.1 m, density 1000, 1/120 s, 4 substeps, sleep off, one worker.
+
+1. **Ymir SoA has none of what the MVP needs from physics.** `native/Ymir.Box3D/ymir_box3d_soa.c`: body kinds
+ sphere/static box/capsule/box only (42-48, check at 365); joint kinds revolute/spherical/weld only (50-55,
+ C# `Box3DSoaWorld.cs:13-18`); no remove, no kinematic body, no motor joint, no impulse, no raycast, no events;
+ `add_body` builds every shape with `b3DefaultShapeDef()` (453) whose `enableContactEvents` is **false** in
+ v0.1.0 (`extern/box3d/src/types.c:66-80`, the field is zero-initialised). Lanes are dense, append-only
+ (`count++` at 485), capacity fixed at create (289-333), views are zero-copy pointers fixed for the world's life
+ (`Box3DSoaWorld.cs:150-155`). Duplicate stable ids are refused by a linear scan (419-425). Shape `userData`
+ already carries the stable id (454).
+2. **Box3D v0.1.0 has every API the MVP needs.** Headers: `b3World_GetContactEvents` (box3d.h:69),
+ `b3World_GetJointEvents` (72), `b3DestroyBody` (490), `b3Body_SetTargetTransform` (557),
+ `b3Body_ApplyLinearImpulse` (598), `b3DestroyJoint` (1014), `b3Joint_GetConstraintForce/Torque` (1059/1062),
+ `b3Joint_SetForceThreshold/TorqueThreshold` (1080/1086), `b3CreateMotorJoint` (1219), `b3_kinematicBody`
+ (types.h:230), `b3JointDef.forceThreshold/torqueThreshold` (types.h:622/625, default `FLT_MAX`,
+ joint.c:28-29), `b3MotorJointDef` with linear/angular spring hertz, damping and max force (types.h:696-730),
+ manifold points with `normalImpulse` and `totalNormalImpulse` (types.h:2573/2577). This corrects
+ `lodur:research:mvp-prior-art.contact-events` ("no normal-impulse accessor found in the docs"): the
+ accessor is `b3Body_GetContactData` / `b3Contact_GetData` manifolds.
+3. **Contact events, run.** With `enableContactEvents` and `enableHitEvents` on both shapes, a sphere dropped
+ 1.4 m gave 1 begin, 1 hit (approach 5.25 m/s), 0 ends over 120 steps. At rest, the manifold's
+ `normalImpulse` summed to 0.0873 per step against m g dt = 0.349: it is the **last substep's** impulse
+ (0.349 / 4). Force from a contact is `totalNormalImpulse / dt`, or `normalImpulse * substeps / dt`.
+4. **End events after removal, run.** Destroying a resting body gives **no** end event in the destroy call's
+ buffer and **one** after the next step, carrying the destroyed shape's id (invalid by then).
+ `b3Body_Disable` behaves the same. So a consumer must resolve a dead shape id to the stable id it had. Ymir's
+ planar session already does this: `ymir_box3d.c:694-712` (`ymir_session_resolve_event_shape`, a
+ retired-shape table filled at removal, 1420-1437) and drains begin/hit/end with manifold details at 773-830.
+ The SoA world should reuse that pattern, not invent one.
+5. **Joint over threshold, run.** A spherical joint with `forceThreshold` 200 N under a ramped pull reported one
+ `b3JointEvent` on the step the force crossed it; `b3Joint_GetConstraintForce` read 1241.9 N on that step; the
+ joint is **not** destroyed by Box3D (event only); `b3DestroyJoint` from the event left the child falling free.
+ Joint events are only for awake joints; Ymir disables sleep (soa.c:337, 447), so every joint reports.
+6. **Grab, run.** A shapeless kinematic body moved by `b3Body_SetTargetTransform` each step, joined to a 4.19 kg
+ sphere by a motor joint (linear spring 5 Hz, damping 0.7, max spring force 50 N, angular spring off), held
+ the sphere at (0.72, 1.02) against a target of (1.0, 1.5): the max force (50 N against 41 N of weight) bounds
+ the pull, as the Box2D v3 drag sample states (`lodur:research:mvp-prior-art.grab-drag`). Destroying the
+ grabbed body destroyed the motor joint with it (`b3Joint_IsValid` 0).
+7. **Impulse at a point, run.** `b3Body_ApplyLinearImpulse` of 1 N s, 0.1 m above the centre, gave v 0.28 m/s and
+ spin -5.0 rad/s: an off-centre poke turns the part, which the force lanes (centre of mass only, soa.c:593-626)
+ cannot do.
+8. **Lodur today.** Perception senses named box volumes at points only (`Perception.cs:82-113`); regions are two
+ hand points (`HumanoidRagdoll.cs:12-16`, 148-170); one reflex kind (`WithdrawalReflex.cs`); drive is pain,
+ strain, resolve, `WillBroken` (`DriveState.cs`); behaviour blends two poses by leak and shake
+ (`PoseBehaviour.cs:87-115`); the body takes 12 strengths and 12 joint-space targets
+ (`HumanoidRagdoll.cs:120-146`). No IK, no clips, no physiology, no grip, no part tree beyond the `Limb` and
+ `Muscle` enums. Rung 3 adds emitters and arousal; rung 4 the goal flip and `PoseBehaviour`.
+9. **BDS today.** Headless and body pain box only (`src/BadDay.Ymir/BodyPainBox.cs`); the world is built per run
+ with capacity 15 (58); the puppet is welded to a stool because the PD ragdoll cannot balance for 15 s (59-62).
+ No session type survives beyond a run, no commands, no level content.
+10. **Godot today.** Nothing; no repo under `F:\Projects` matches.
+
+## The systems, by owner
+
+`exists` cites base code; `new` is MVP work and names the cut that builds it (cut order below).
+
+### Ymir (physics facts and actuators; decides nothing about bodies' meaning)
+
+| System | State | Cut |
+|---|---|---|
+| Contact facts: begin/end/hit per step with stable ids, lanes, point, normal, approach speed, material ids; per-body contact force lane | landed (ABI 5-7; `docs/soa-world.md`: facts per step, exact per-step contact impulse per body and per hit); planar session precedent `ymir_box3d.c:694-830` | `ymir-contact-facts` |
+| Material id per body (u64, the game's), carried on hit facts | landed (the body's `material_id`, on the hit facts) | `ymir-contact-facts` |
+| Raycast (closest hit: lane, stable id, point, normal, fraction) for picking and hitscan | landed (ABI 5) | `ymir-grab-anchor` |
+| Grab anchor: shapeless kinematic body moved by target transform; motor joint (linear/angular spring, max force) | landed (ABI 5-6: grab release, joint handles with generations; probe 6) | `ymir-grab-anchor` |
+| Point impulse command | landed (ABI 5; probe 7) | `ymir-grab-anchor` |
+| Joint stress: per-joint force/torque thresholds (create and set), overload facts with measured force/torque | new; probe 5 | `ymir-break-and-remove` |
+| Runtime removal of bodies and joints; tombstoned lanes; reuse after a step; removal facts (incl. joints that die with a body); end-touch attribution for dead shapes | new; probe 4 | `ymir-break-and-remove` |
+| Placeable joint kinds for building (motor-driven revolute, prismatic, distance/rope, spring) | new | follow-up `ymir-joint-kinds` |
+| More shapes (hulls, compounds) for authored props | new | follow-up `ymir-shapes` |
+
+### Lodur (general character middleware; no gore)
+
+| System | Layer | State | Cut |
+|---|---|---|---|
+| Part tree: the body plan as content (parts, parent, side, max HP, coverage, vital flags, muscles, Ymir lane binding) | 3 data + 5 binding | new; today `Limb`/`Muscle` enums | `lodur-physiology` |
+| Touch perception per part: pressure (contact force), impact (hit speed, material), external-joint pull (grab, strap) | 1 (+5 reads Ymir) | new | `lodur-touch` |
+| Reflexes: withdrawal (exists), startle on sensory and touch onsets, flinch-from-touch, brace on impact | 2 | withdrawal exists `WithdrawalReflex.cs` and reads `Will`; rest new | `lodur-startle-attention`, `lodur-reflex-set` |
+| Physiology as drive state: per-part HP and injuries, body blood fraction, bleeding, pain sum, shock, consciousness, capacities scaling muscle strength, death | 3 | new | `lodur-physiology` |
+| Will economy: resolve (exists) times attention (new, startle drains it) is the budget every voluntary layer draws on; reflexes act against it | 3/4 | landed except attention: `Will` = min(resolve x attention, consciousness) in `DriveState`, read by the reflex and the will mix; the Attention and Consciousness slots read 1 until startle and physiology write them | `lodur-startle-attention` (open), `lodur-will-mix` (landed `afb8df3`) |
+| Voluntary motor layers: hold pose (exists as `PoseBehaviour`), clip player, IK goals (reach, look, aim), grip; mixed by will | 4 | hold exists, weighted by `Will^WillCurve` (`PoseBehaviour.Write`; an involuntary goal onset writes at weight 1); rest new | `lodur-will-mix`, `lodur-ik-goals`, `lodur-clips` |
+| Body interface: strengths + joint targets (exists) + IK goals with weights | 5 | partial `HumanoidRagdoll.Drive` | `lodur-ik-goals` |
+| Severing: physiology decides; binding removes the joint in Ymir; impairment states derived per part, mirror-symmetric | 3 decides, 5 executes | new | `lodur-sever-impair` |
+| Grip: hand holds an object by a breakable weld whose threshold follows grip strength; drop on pain, overload, unconsciousness; the tool frame is an IK end effector | 4/5 | new | `lodur-grip` |
+
+### Bad Day Simulator (content, rules, sandbox; owns the gore)
+
+| System | State | Cut |
+|---|---|---|
+| Sandbox session: one deterministic world with puppets and objects; command queue (spawn, remove, grab begin/move/end, poke, cut, place joint, wire) | new; today per-run `BodyPainBox.Run` | follow-up `bds-sandbox-session` (after `client-ready-sim`) |
+| Damage content: material ids to insult kinds and gains (blade Cut, bat Blunt, spike Pierce), tear from joint overload | new | follow-up `bds-damage-content` |
+| Gore presentation data: blood colour, bleed particle rates by wound, decal sets, stump caps, gibs | new; waits on `bds-gore-look` | follow-up `bds-gore-content` |
+| Levels and arenas as CultCache: objects, joints, stimulus volumes, emitters, triggers, signal wires; arenas are levels built with the player's commands | new | follow-up `bds-level-content` |
+| Contraption logic: signals between objects (switch, timer, sensor volume, motor, emitter) ticked in the session | new | follow-up `bds-contraption-signals` |
+| Guns and ballistics: hitscan by Ymir raycast, recoil impulse, damage content | new | follow-up `bds-guns` |
+
+### Godot client
+
+| System | State | Cut |
+|---|---|---|
+| Render bodies from Ymir lanes by stable id | landed: `BodyRenderer` draws static boxes and `Puppet` the dynamic bodies as one skinned SDF mesh (BDS README, "Who owns what") | `godot-client-v1` |
+| Bodies added and removed at runtime from Ymir lifecycle facts | new | follow-up `godot-runtime-bodies` |
+| Input to commands: ray pick, grab drag, poke, cut, place, wire | new | follow-up `godot-interaction` |
+| Blood visuals from BDS gore events (particles at wounds, decals at hits, stump caps) | new | follow-up `godot-blood` |
+| Building tools UI over the level commands | new | follow-up `godot-build-tools` |
+
+## Authority map (MVP)
+
+**Owner of each decision, one each.**
+
+- **Whether a body or joint exists in the world:** Ymir, on command only. Ymir never removes anything on its
+ own; a joint over threshold is a fact, not a removal (probe 5: Box3D itself does the same).
+- **What touched what this step, how hard:** Ymir's contact facts and contact-force lane. Nothing else derives
+ touch from geometry; the box-volume stimuli stay named game stimuli (a heat source is not a contact).
+- **What damage an insult does to a part, and whether a part is severed, disabled or dead:** Lodur physiology,
+ from insults (part, kind, magnitude) the binding builds out of Ymir facts and the game's material table.
+ **The joint break threshold is no longer an owner; it is a stress sensor** whose facts become Tear insults.
+- **What the body tries to do:** Lodur's will mix: voluntary layers weighted by available will, reflexes against
+ it (ruling `bds-sandbox-arenas-will-economy`). `PoseBehaviour`'s blend (`PoseBehaviour.cs:87-115`) is
+ no longer an owner; it becomes one voluntary layer (hold pose) inside the mix.
+- **Muscle strength ceiling:** physiology capacities times consciousness; the will mix may only scale down from
+ it. Content gains are parameters, not owners.
+- **Where the player's hand is and what it holds:** BDS sandbox session (grab handle); Ymir executes the anchor.
+- **What a material means (sharp, blunt, hot) and how gore looks:** BDS content. Lodur sees only insult kinds.
+- **What is drawn:** Godot, from Ymir lanes and lifecycle facts, BDS presentation events. Godot owns no
+ simulation state and never writes a lane.
+
+**Inputs/outputs per tick (one order, the body run's order today, `BodyPainBox.cs:106-110`, extended):**
+BDS applies queued commands (spawn/remove/grab target/impulse) → Ymir step → Ymir facts (contacts, hits,
+overloads, removals) → binding turns facts into per-part touch samples and insults → Actor tick: perception,
+reflex (gain from last tick's drive), drive and physiology, will mix → binding writes strengths, targets, IK
+solve onto torque lanes, executes severing and grip changes as commands for the next step → BDS emits
+presentation events (wound opened, part severed, death) → Godot draws.
+
+**Derived state:** impairment state per part (from HP, severed, nerve flags); capacities; consciousness;
+"dead"; blood visuals; Godot node set (from lifecycle facts); joint overload (a sensor reading).
+
+**Forbidden writers:** Godot writing any lane or calling Ymir directly; BDS setting muscle strengths or targets
+(body-one-interface); Ymir destroying a joint on threshold; any per-wound lookup choosing behaviour
+(drive-is-state); a voluntary layer writing targets outside the will weighting; the binding deciding damage.
+
+**Shared paths:** player grab, a scripted grab in an arena, and a level load all go through the session's
+command queue; arenas are levels; a player cut and a falling blade go through the same contact-to-insult path;
+a torn limb and a cut limb go through the same physiology severing decision; reload of a level replays the
+same commands as building it.
+
+**Deletion lines:** `PoseBehaviour.Blend` as the motor owner (in `lodur-will-mix`, landed: `Blend` now only mixes the hold layer's flinch pose, the strength is the will mix); hand-only `Region`
+enum and `ReadRegions` as perception's body model (in `lodur-touch`, replaced by parts); the per-run world in
+`BodyPainBox.Run` as BDS's only world (in `bds-sandbox-session`, scenario runs become sessions,
+follow-up `scenario-session-unify`).
+
+## Model page: identity, lifecycle, authority
+
+| Kind | Named by | Lifecycle | Decides | Persisted |
+|---|---|---|---|---|
+| Ymir body lane | caller's `stable_id` (u64, unique among live bodies of a world) and its lane while alive | add → live → removed (tombstoned) → lane reusable after the next completed step | Ymir on command | no (the level persists what spawned it) |
+| Ymir joint lane | lane while alive; caller may tag | add → live → removed by command or with its body | Ymir on command | no |
+| Body part (def) | (body plan content id, part label) | authored content, immutable at runtime | content (game), schema Lodur | CultCache content |
+| Body part (state) | (actor, part label) | spawned with the actor → intact → impaired/disabled → severed or dead; never resurrected in MVP (`bds-reattach`) | Lodur physiology | no in MVP (`bds-gore-look` option persist) |
+| Wound (injury) | (actor, part, ordinal) | opened by an insult → bleeding → clotting (content rate) → closed; no tending in MVP | Lodur physiology | no |
+| Blood (body) | (actor) scalar fraction | 1.0 at spawn, falls by bleeding, recovers only while nothing bleeds (RimWorld, `rw-blood-bleeding`) | Lodur physiology | no |
+| Blood visual (pool, decal, spray) | presentation instance | emitted from wound/hit events, fades or stays per `bds-gore-look` | BDS presentation data, Godot draws | no (question) |
+| Severed part | the stable ids of its bodies (they survive; only the joint goes) | severed → loose physics prop owned by the session, grabbable, removable by the player | physiology severs; session owns the prop after | no |
+| Grab | (session, pointer) handle; anchor's stable id | begin on ray pick → target moved per tick → end on release, or ends when its body is removed (Ymir removal fact) | BDS session | no |
+| Impairment state | (actor, limb slot, side) | derived each tick from part states; closed set `Intact, Impaired, Disabled, Severed` per limb slot, mirror-symmetric | derived (physiology) | no |
+| Animation clip | content id | authored, immutable | content (BDS), schema Lodur | CultCache content |
+| IK goal | (actor, chain) for chain in the closed set `ArmL, ArmR, LegL, LegR, Look, Aim` | written every tick by a voluntary layer, weighted by will, consumed by the binding's solver | Lodur will mix | no |
+| Held object (grip) | (actor, hand side) → object stable id | grip begins on behaviour or level content → weld joint with threshold = grip strength → released by behaviour, reflex, unconsciousness or overload | Lodur grip state; Ymir weld executes | level may author "starts holding X" (content) |
+| Level / arena | content id | authored with player tools, saved, loaded by replaying commands | BDS | CultCache |
+| Contact / hit / overload / removal fact | (step, ordinal) | one step | Ymir | no |
+| Attention | (actor) scalar | 1.0, and nothing writes it yet but the test seam `Actor.SetWillSlots`; startle will drop it, recovering in under a second | Lodur drive | no |
+
+## Questions for the operator and Deru (one batch; admitted as `question`s)
+
+1. `bds-gore-look`: what gore looks like and whether it stays. Options: stylised (bright blood, decals and
+ spurts, capped stumps, no viscera), realistic (wound textures, exposed bone, gibs), stylised with a content
+ slider. Recommend stylised default with presentation data shaped to take a realism slider later; blood
+ visuals fade per session and are never saved in levels. Grounds: People Playground reads clearly with
+ stylised blood (`mvp-prior-art.pp-physiology`); the sim (wounds, blood fraction) is the same for every
+ option, so only BDS content and Godot change.
+2. `bds-death`: what kills a puppet and what death looks like. Options: RimWorld rules (consciousness 0,
+ blood loss 100%, lethal part destroyed: head, neck, torso, heart), then limp and permanent until reset;
+ People Playground rules (no hard line; integrity and oxygen fade, revivable by an item); no death in the
+ MVP (unconscious only). Recommend RimWorld rules with a session reset, revival items later
+ (`rw-consciousness`, `rw-body-tree`, `pp-physiology`).
+3. `bds-reattach`: can parts be put back. Options: no; prop-only (the player may weld a severed arm back with
+ the joint tool, it hangs limp and stays Severed to physiology); full heal. Recommend prop-only: it costs
+ nothing (it is the joint tool) and keeps physiology one-way.
+4. `bds-dismember-trigger`: what takes a part off. Options: blades and extreme force both (Cut insults past a
+ part's HP, and Tear from joint overload while grabbed or hit); blades only; an explicit sever tool. Recommend
+ both through one severing rule (DF: severed limbs common; Box3D thresholds as sensors, `joint-break-apis`).
+5. `bds-upright`: how the puppet stays up in the MVP. Options: seated or strapped (today's stool weld); an
+ assist pin on pelvis and torso whose strength is consciousness times will, so a fainting puppet collapses
+ (PuppetMaster pin weights, euphoria doc 10.1); hung or suspended; learned balance (v2, out of MVP per
+ `euphoria-body-layer-order`). Recommend the assist pin: it is a voluntary layer in the will mix, reads as
+ standing, and its failure is the collapse People Playground shows.
+6. `bds-mvp-clips`: which animations exist. Options: poses only (idle, guard, cower, protect-head, brace, reach,
+ aim); poses plus a few looping clips (idle sway, struggle, writhe); generated clips from Vili. Recommend poses
+ plus three loops, authored as pose keys (rung 4's `PoseBehaviour` generalised); Vili clips when its retarget to
+ this ragdoll exists.
+7. `bds-will-visible`: what failing will looks like. Options: tremor and sag (strain shake exists,
+ `PoseBehaviour.cs:89`), slower and shorter reaches, aim wander; plus an on-screen will bar; plus vocal or
+ facial cues (presentation). Recommend tremor, sag, slower reach and aim wander from the will mix, plus a
+ debug bar; voice later.
+
+## Target r4 (landed: `5d0fec8` and r5 `58c2201`; `docs/lodur-target.md` is now the text)
+
+Keep r3's invariants and add:
+
+- `one-severance-owner`: A part is damaged, disabled or severed only by Lodur's physiology; Ymir reports
+ contacts and joint stress and removes a joint only on command; no physics threshold removes anything by itself.
+- `will-is-the-budget`: Every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
+ available will (resolve times attention, capped by consciousness); reflexes act against it with their own
+ gains; nothing writes targets outside that mix.
+- `sandbox-is-content`: An arena is a level built from the commands the player has; no engine path exists only
+ for an arena; levels are CultCache.
+
+Replace r3's first not-in-scope line with: "Adapting to body topology outside the authored part tree (new
+limbs, re-rooted trees, morphology-agnostic learned control). Losing a subtree of the authored tree is in
+scope as a closed set of impairment states per limb slot, mirror-symmetric." Add to not in scope: "Weapons,
+ballistics, gore and wound presentation (Bad Day Simulator content)."
+
+This resolves the tension the MVP ruling names: severing changes topology only inside the authored tree, so
+the behaviour set compensates through a closed set of states (intact, impaired, disabled, severed per limb
+slot), as the r3 doc's open item proposed and `euphoria-stimulus-and-impairment` asks (hopping after losing a
+leg is a behaviour keyed on the state, not a re-learned controller).
+
+## Rationale
+
+- **Facts, not callbacks.** Ymir fills fixed-capacity fact buffers per step and the caller reads spans, like
+ lanes; no managed callback crosses the ABI, overflow is counted, never silent (bounded-tick).
+- **Tombstones, not compaction.** Lodur and the client cache lane indices (`HumanoidRagdoll._bodyLane`,
+ `HumanoidRagdoll.cs:44`). Swap-remove, as the planar session does (`ymir_box3d.c:1435-1436`), would move a
+ live body's lane under them. A removed lane keeps its last state and a `Removed` kind; reuse waits for a
+ completed step so end facts still name the old id.
+- **Grab is felt.** A motor joint is not a contact, so a grab produces no contact fact. The binding treats every
+ joint on a ragdoll body that the ragdoll does not own (grab, strap, grip, a player's weld) as a touch at its
+ anchor with the joint's constraint force: one rule for grabs, restraints and held tools.
+- **Poke is a body.** The poke and cut tools are small kinematic bodies on the grab anchor, so their touch
+ arrives through contacts and their damage through the material table, like a falling blade. The impulse
+ command stays for explosions, recoil and bullets.
+- **Physiology is drive state.** RimWorld's model (part tree, HP, pain sum, blood fraction, consciousness,
+ capacities; `rw-*` notes) is per-tick state with no per-wound behaviour lookup, which drive-is-state asks.
+ Numbers start from RimWorld and ATLS bands (`df-and-atls`) as content defaults.
+- **Grip and aim follow PuppetMaster's prop and IK split.** A held prop becomes part of the puppet through its
+ own joint, pick-up and drop are one assignment, and props drop when the puppet loses balance
+ (`mvp-prior-art-2.puppetmaster-prop-attachment`); aiming IK runs before the physics read so the muscles chase
+ the aimed pose and physics, pain and will degrade it (`mvp-prior-art-2.ik-after-physics-aiming`). Lodur's
+ grip is that model with the drop rule moved into drive state (pain in the hand, unconsciousness, overload
+ of the weld's threshold). Aim error is not a parameter: it is the gap between the aim IK goal and where the
+ will-weighted, tremoring, startled arm lands. Arma's suppression and fatigue sway
+ (`mvp-prior-art-2.suppression-aim-degradation`, `aim-physiology-numbers`) are the games that fake that gap
+ with a sway multiplier; here it emerges, which is what the ruling asks for.
+- **Building is props plus constraints plus signals.** Garry's Mod composes from props and a fixed set of
+ constraint tools and saves entities then constraints (`mvp-prior-art-2.gmod-constraint-duplicator`);
+ People Playground, Besiege and Algodoo add activation signals, sensors, timers and logic
+ (`mvp-prior-art-2.algodoo-ppg-besiege-signals`). BDS levels are that triple as CultCache: objects (with
+ behaviours as content), joints (Ymir kinds, `ymir-joint-kinds`), wires; load creates objects before
+ joints, as the duplicator's paste does. No source reached says how those games' shipped levels were built;
+ the ruling's "arenas with the player's tools" is ours.
+- **Startle moves up.** The new ruling makes distraction a will drain, so `lodur:follow_up:startle-reflex`
+ becomes cut `lodur-startle-attention`. It did not land right after rung 4: `lodur-will-mix` landed first (it needs only the `Will` slots, which read 1), so startle now depends on it.
+
+## Cut order
+
+Agent pace: S is one Hands session plus Soul, about 1-2 h; M about 3-4 h; L about 6 h. Ymir runs in parallel
+with the Lodur rungs (different repo); Lodur cuts serialise on `Actor.cs`; BDS waits on the client pass.
+
+| # | Cut | Repo | One line | Depends on | Size |
+|---|---|---|---|---|---|
+| 1 | `ymir-contact-facts` | Ymir | contact/hit facts, contact-force lane, material ids | ymir-shape-lanes (parallel client pass, ABI 3) | M | landed |
+| 1' | `ymir-grab-anchor` | Ymir | kinematic anchor, motor joint, impulse, raycast | ymir-shape-lanes (sibling of 1) | S-M | landed |
+| 2 | `ymir-break-and-remove` | Ymir | thresholds, overload facts, remove body/joint, tombstones, removal facts | 1 | M | open |
+| - | `rung3-sensory-load` Soul, `rung4-goal-flip`, `rung3-office-stress`, `rung4-office-flip` | Lodur/BDS | landed (rung 3 `a048827`, rung 4 the Brain `c26c15c`; the office arc and the chamber release in BDS) | as admitted | - |
+| - | `client-ready-sim`, `godot-client-v1` | BDS/Godot | landed (`BodyPainBoxSession`; the Godot client at `client/`) | its own | - |
+| 3 | `lodur-will-mix` | Lodur | voluntary layers weighted by will; PoseBehaviour demoted | rung4-goal-flip | M, landed (`afb8df3`, with the recurring break `74883f8`; goal entry effects `c93bdb7`) |
+| 4 | `lodur-physiology` | Lodur | part tree content, HP, wounds, blood, pain, shock, consciousness, capacities, death | 3 (landed) | L (split core/binding if over budget) |
+| 5 | `lodur-touch` | Lodur | per-part touch from contact facts, external-joint pull; insults from material table | 1, 2, 4 | M |
+| 6 | `lodur-startle-attention` | Lodur | startle reflex on onsets; attention scales will | 3 (it writes the Attention slot the will mix already reads) | M, open |
+| 7 | `lodur-ik-goals` | Lodur | IK goals in body interface; two-bone arm/leg, look, aim | 3 | M |
+| 8 | `lodur-reflex-set` | Lodur | flinch-from-touch, brace | 3, 5 | M |
+| 9 | `lodur-sever-impair` | Lodur | severing via binding, impairment states | 2, 4, 5; Q `bds-dismember-trigger`, `bds-reattach` | M |
+| 10 | `lodur-clips` | Lodur | pose-key clips as a voluntary layer | 3; Q `bds-mvp-clips` | S |
+| 11 | `lodur-assist-pin` | Lodur | upright assist as a voluntary layer | 3; Q `bds-upright` | S |
+| 12 | `lodur-grip` | Lodur | grip weld, drop rules, tool frame for aim | 2, 7 | M |
+| 13 | `bds-sandbox-session` | BDS | session + command queue, grab/poke/cut | client-ready-sim, 1' | M |
+| 14 | `bds-damage-content` + `bds-gore-content` | BDS | materials to insults; gore data | 5, 9; Q `bds-gore-look`, `bds-death` | M |
+| 15 | `godot-runtime-bodies`, `godot-interaction`, `godot-blood` | Godot | lifecycle, input, blood | godot-client-v1, 2, 13, 14 | M each |
+| 16 | `ymir-joint-kinds`, `bds-level-content`, `bds-contraption-signals`, `godot-build-tools` | mixed | building and arenas | 13 | M-L each |
+| 17 | `bds-guns` | BDS | gun content aimed by IK | 7, 12, 1' | M |
+
+Rough total: about 26 cuts, roughly 70-90 agent-hours; with Ymir and BDS/Godot running beside the Lodur chain,
+the critical path is the Lodur chain 3 → 4 → 5 → 9 (and 3 → 7 → 12; startle, 6, is off it), about 30 agent-hours after rung 4 lands.
+The playable MVP (grab, poke, cut, bleed, sever, reflexes, will) is cuts 1-9, 13-15.
+
+Admitted 2026-11-20 (pass `bds-mvp-map`): specs `lodur:cut_spec:cut-ymir-contact-facts.r2`,
+`cut-ymir-grab-anchor.r2` (siblings, after the parallel pass's `ymir-shape-lanes`), `cut-ymir-break-and-remove.r2` (after contact facts); every
+later cut above is a `lodur:follow_up:` of the same name (22), owner nibu; questions
+`lodur:question:bds-*` (7); ideas `lodur:idea:bds-mvp-map.*` (22, seven rejected and resolved Recorded).
diff --git a/docs/connect-rungs-map.md b/docs/connect-rungs-map.md
new file mode 100644
index 0000000..b67859a
--- /dev/null
+++ b/docs/connect-rungs-map.md
@@ -0,0 +1,265 @@
+# Lodur: connect the rungs (map)
+
+Campaign `lodur` (Nibu's mind). Imagination pass `connect-rungs-map`, session `nibu-self-2026-11-17`,
+2026-11-19. Operator order: "A, connect the rungs" (`lodur:ruling:lodur-body-on-ymir`). This file is the prose
+map: body facts, the model page, rationale, the proposed target r3 text (committed as docs/lodur-target.md), and the
+Ymir cut draft. Committed here from the Imagination scratchpad so it is durable; the bases below are the pins it was probed at.
+
+## Bases
+
+| Repo | Base | Note |
+|---|---|---|
+| GameCult/Lodur | `18c4ffd0d598c34fc00f96c7f5d23aafdc003706` | main = origin/main |
+| GameCult/BadDaySimulator | `9f597647a608a6c6e44473cc9f1399983de14616` | main = origin/main |
+| GameCult/Ymir | `7ba31c30fc3329b84cc638646310259c663c1051` | origin/main. **`F:\Projects\Ymir` local `main` is 11 behind** (its last fetch was 2026-10-29; it has no SoA world at all). I ran `git fetch origin` only (refs, no checkout). Lodur's sibling default `..\Ymir` therefore builds against a tree without `Box3DSoaWorld` until that checkout is fast-forwarded; that is Self's call, not done. |
+
+## Body facts (probes)
+
+All probes in detached worktrees `F:\aeth-wt\connect\{Ymir,Lodur,BadDaySimulator}` at the bases above
+(Ymir submodule `extern/box3d` at pin `8441b4a`), Windows 11 workstation, 2026-11-19. Worktrees removed after.
+
+1. **Windows build of Ymir native works with MinGW, with one defect.** No MSVC/VS on the workstation
+ (`vswhere` finds nothing). `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc dotnet test tests/Lodur.Tests`
+ (gcc and ninja from StrawberryPerl, CMake 3.x in Program Files) configures "Box3D on MinGW", builds 53
+ objects, and links `bin\Debug\libymir_box3d.dll`. The build then fails MSB3030: `Ymir.Box3D.csproj`
+ expects `bin\$(Configuration)\ymir_box3d.dll` (MSVC naming; MinGW adds the `lib` prefix). After copying the
+ DLL to the unprefixed name: **Lodur.Tests 21/21 pass on Windows** (6 s), including same-seed-same-hash
+ within one process. The CultLib pin guard in Ymir's `Directory.Build.targets` did not fire for this graph.
+ Without `CMAKE_GENERATOR` set: not tried.
+2. **What Ymir's SoA world exposes for a hand in a box** (`src/Ymir.Box3D/Box3DSoaWorld.cs`, origin/main;
+ `docs/soa-world.md` "Not done"): body lanes (stable id, kind, parent, limb, position, rotation quaternion,
+ linear and angular velocity), write lanes (force, torque), joint lanes. **No contact facts, no sensor shapes,
+ no overlap or ray queries, no body removal.** Box3D compiles `sensor.c` but Ymir's SoA ABI does not
+ surface sensors. So the hand-in-box test is geometry over the body lanes: the ragdoll has no hand body; the
+ hand point is the right lower-arm capsule tip, centre + R * (0, -(halfLength + radius), 0) = (0, -0.14, 0).
+ The box is a game stimulus volume (layer 1 "named game stimuli"), not a physics body.
+3. **The SoA world is internal.** `Box3DSoaWorld`, `Box3DSoaView` and the kind enums are `internal`, visible to
+ `Ymir.Core`, `Ymir.Box3D.Soa.Tests`, `Lodur.Body.Ymir` and `Lodur.Tests` by `InternalsVisibleTo`
+ (`src/Ymir.Box3D/Properties/AssemblyInfo.cs:3-6`, commit 0227636 "until Ymir.Core has a public surface").
+ `HumanoidRagdoll`, `Muscle` and `Limb` are `internal` in Lodur.Body.Ymir. **Bad Day Simulator cannot name the
+ world today**, so it cannot own its one physics world without a Ymir change.
+4. **A pelvis weld to a static body holds the ragdoll upright for 20 s.** `AddJoint(Weld, staticBox, pelvis)`
+ is accepted (native refuses only out-of-range or equal indices). Full-strength ragdoll, pelvis welded to a
+ 5 cm static box behind it: head 1.739 m and pelvis 1.110 m at every 2 s checkpoint to 20 s. Unwelded it
+ topples at about 2 s (first-slice.md), and the pain box breaks at about 15 s.
+5. **Arm reach into a box, at strength 1.** Right shoulder target `FromAxisAngle(1,0,0,-1.0)` (joint frame),
+ elbow `FromAxisAngle(0,0,1,-0.6)`: hand tip settles at about (-0.21, 1.19, 0.46). Over 2-4 s of hold its
+ range is x [-0.233, -0.191], y [1.175, 1.220], z [0.448, 0.469] (natural wobble, no tremor). Shoulder
+ `-1.2`, elbow 0.3 gives (-0.21, 1.20, 0.48). Positive shoulder angles swing the arm back (+1.0 puts the hand
+ at z -0.25). Strength 0 leaves it hanging at y 0.96.
+6. **Strength above 1 is not safe on the arm.** Strength 3 with the same targets sagged the hand to y 1.03 and
+ let it drift in x to -0.35 (explicit PD past its stable damping). Keep strength in [0, 1].
+7. **Withdrawal is fast.** Switching the arm target to shoulder +0.3, elbow 2.0 (strength 1) takes the hand out
+ of a 0.12 m half-extent box centred at (-0.21, 1.19, 0.46) in 5-6 ticks at 120 Hz (about 50 ms).
+ Shoulder -0.3 / elbow 1.5 takes 18 ticks.
+8. **Visible strain needs low frequency.** A 9 Hz shoulder-target tremor of 0.08 rad leaves the hold range
+ unchanged to the millimetre (the PD at swing gains 20/1 filters it). 3 Hz at 0.15 rad widens y to
+ [1.162, 1.230]; 4 Hz at 0.3 rad to [1.161, 1.233] and z to [0.437, 0.477]. So strain shows as a shake of a
+ few Hz, not physiological tremor frequency.
+9. **Pain-box baseline at the BDS base** (Windows, git-bash, `dotnet run --project src/BadDay.Cli -- run
+ --seed N > file`; Summary uses `WriteLine`, so CRLF on Windows and the hashes are platform-bound):
+ 13/13 tests pass; seed 1 "will broke at 14730 ms, hand out at 14830 ms, 16 flinches". sha256 run-1
+ `973603f9…dd4cc`, run-2 `cf1a6060…a4af95`, run-3 `bafc5967…20e1`. PainSweep table (scratch csproj compiling
+ `tools/PainSweep/Program.cs` against BadDay.Core; stdout) sha256 `13424cd1…7bf`; cells e.g. 0.80 x 0.95 =
+ 14.9 s, 0.20 x 0.50 = 95.4(8/9), every suppression-0 cell "never". Hands recaptures at base with one method.
+10. **Where the model's arithmetic sits** (`src/BadDay.Core/PainBoxSimulation.cs` at base): traits 22-23; box
+ stimulus 59-61; nociceptor threshold, sensitisation, conduction ring 64-69; pain 72-73; reflex suppression,
+ leak, flinch, strain 77-86; resolve drain, recovery, break 89-101; sample 104; withdrawal 106-112. Order
+ inside a tick matters: suppression reads last tick's resolve (gain set ahead of time); the Flinch row is
+ logged after pain but before strain and resolve update (lines 83, 85, 94).
+
+## The model page (step 0b)
+
+No persistent content is introduced by these cuts: every parameter stays a code default or a CLI argument,
+so `content-is-cultcache` is not engaged yet (follow-up `lodur:follow_up:drive-profiles-as-content`).
+
+| Kind | What names it | Lifecycle | Who decides |
+|---|---|---|---|
+| Nerve, reflex and drive parameters (`NerveParameters`, `WithdrawalParameters`, `DriveParameters`) | Nothing persistent: C# records with defaults in Lodur.Core; a per-actor instance is a value | Built once when the consumer creates an actor (per-seed traits folded in as `Gain`, `DrainTrait`), immutable for the actor's life | Lodur owns the schema and defaults; the consumer (BDS scenario) owns per-actor values and the trait draw |
+| Actor (nervous state: afferent rings, drive state, goal) | The consumer's handle; no id inside Lodur | Created with the scenario, ticked once per physics step, never persisted, dies with the scenario | Lodur.Core alone writes it; nothing else writes drive state |
+| Puppet definition (the 13-body humanoid: shapes, joints, gains, regions) | Code in Lodur.Body.Ymir; world stable ids `firstStableId..+12` passed by the caller | Built into the caller's world once; no removal (Ymir has none) | Lodur.Body.Ymir owns geometry and gains; BDS owns placement and stable-id allocation |
+| Stimulus source (the pain box) | BDS object, scenario-local; not a world body | Placed by the scenario; intensity written every tick from its schedule (ramp, noise, disable time) | BDS writes intensity and on/off; Lodur perception only reads it and decides containment and transduction |
+| Restraint (stool weld) | BDS scene object: one static box + one weld joint in the world | Created with the scenario | BDS (a game object acting on the body through the world, like a grab; not a layer above Lodur) |
+| Scenario run | (seed, parameters) | One run, headless or on the body | BDS; the timeline is output, not content |
+
+## Rationale
+
+- **Wrong owner, now.** The pain box is perception, reflex and drive flattened into the consumer. Lodur.Core
+ holds only the PD law. The cut moves layers 1-3 and a layer-4 stand-in into Lodur.Core and leaves BDS with
+ the things a game owns: the box schedule, the seed and trait draw, the restraint, the world, the recorder.
+- **Move first, retune never in the same cut.** The layers keep the pain box's double arithmetic and the order
+ of operations, so seed 1 still breaks at 14730 ms and the sweep table is byte-identical. The only planned
+ difference: every timeline row becomes end-of-tick state, which changes the strain and resolve columns of
+ Flinch rows (they were logged mid-tick). Any retune (latencies, `[M]` figures) is a later, separately
+ falsifiable cut.
+- **The game owns the world** (`one-physics-world`, `lodur-body-on-ymir`): BDS creates the Ymir world and Lodur
+ adds its bodies to it. That needs Ymir's SoA world to be nameable outside Ymir, hence the Ymir cut. A Lodur
+ facade that creates and hides the world would make Lodur the world's owner, which is the split this invariant
+ forbids.
+- **Headless stays engine-free.** BadDay.Core references only Lodur.Core, so the sweep and the headless tests
+ build with `dotnet` alone; the body scenario lives in a new BadDay.Ymir project. One more csproj buys a
+ measure that does not need cmake.
+- **Posture.** The PD ragdoll cannot balance for 15 s; the puppet sits strapped at the pelvis (body fact 4).
+ The learned tracker (v2) is what lets it stand later.
+- **Visible strain** is a 3-4 Hz shake along the withdraw direction, scaled by strain (body fact 8), plus the
+ flinch blend. Sweat is a render concern; there is no renderer.
+
+## Cut order
+
+1. `ymir-soa-public` (GameCult/Ymir): **not admitted**, because Ymir is not in the lodur repo set (target r2:
+ Lodur, BadDaySimulator). Recommended: target r3 adds GameCult/Ymir; then admit the draft below. Tracked as
+ `lodur:follow_up:ymir-soa-public-surface`. Ymir is Nibu's stewardship (`nibu:stewardship:gamecult_-ymir.n1`).
+2. `nervous-layers` (GameCult/Lodur), `lodur:cut_spec:cut-nervous-layers.r1`. Its Core commits need nothing
+ from Ymir; its body-binding commit needs cut 1 on Ymir main.
+3. `pain-box-on-lodur` (GameCult/BadDaySimulator), `lodur:cut_spec:cut-pain-box-on-lodur.r1`, depends on 2;
+ blocked on `lodur:question:bds-consumes-lodur`.
+
+### Draft cut spec: ymir-soa-public (admit after target r3 names GameCult/Ymir)
+
+- repo GameCult/Ymir, branch `nibu/soa-public`, base `7ba31c30fc3329b84cc638646310259c663c1051`.
+- deletes: `src/Ymir.Box3D/Properties/AssemblyInfo.cs:5-6` (2 lines, the Lodur friend grants).
+- file_changes: `src/Ymir.Box3D/Box3DSoaWorld.cs:5` `Box3DSoaKind`, `:13` `Box3DSoaJointKind`, `:151`
+ `Box3DSoaView`, `:223` `Box3DSoaWorld` become `public`; the native desc/view structs and
+ `Box3DSoaNative` stay internal; the `Box3DSoaView` constructor stays internal. `native/Ymir.Box3D/CMakeLists.txt`
+ `:22` `set_target_properties(ymir_box3d ...)` gains `PREFIX ""` so MinGW emits `ymir_box3d.dll` (body fact 1).
+ `docs/soa-world.md` "Managed (... internal)" and "Not done ... public typed surface" lines: say the SoA world
+ is public in Ymir.Box3D. Ymir.Core keeps its own surface.
+- verification: `dotnet test tests/Ymir.Box3D.Soa.Tests` green; Lodur at 18c4ffd with `YMIR_ROOT` at the head
+ builds and its 21 tests pass with the friend grants gone; on Windows,
+ `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc` builds with no DLL rename. Negative: `InternalsVisibleTo\("Lodur`
+ in `src/` finds nothing.
+- estimate: about +10 / -4 lines, no targets.
+
+## Proposed target r3 text for `Lodur/docs/lodur-target.md`
+
+Hands commits this in `nervous-layers`; Self admits the typed `lodur:target:r3` (invariants as below, repos
+GameCult/Lodur, GameCult/BadDaySimulator, GameCult/Ymir; doc at that commit) with the superseding resolution
+of r2.
+
+```markdown
+# Lodur: target
+
+Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
+workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
+ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
+ruling disagree, the ruling wins and this file is stale.
+
+## What it is for
+
+A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
+back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
+objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
+
+The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
+characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
+follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
+nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
+latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
+`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
+`15d9a4e`).
+
+Named after the god in Voluspa who gives the first humans blood, warmth and good colour
+(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
+
+## Layers
+
+Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
+(`netstandard2.1`, no references); layer 5 is a body binding.
+
+1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`). Contacts, impulses, temperature,
+ proximity and named game stimuli become typed signals on body regions. Input: one point per body region
+ (from the body binding, read-only) and the game's stimulus sources. Today one channel (noxious) and one
+ source kind: a box volume with an intensity the game writes each tick. Output per region: the stimulus, and
+ the afferent signal after threshold, sensitisation and conduction delay. A poke that barely moves the body
+ is still a stimulus.
+2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
+ (withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
+ Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
+ (the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
+ Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
+ flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
+ (figures `[M]` in the research doc; verify before they become constants).
+3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
+ afferent input, strain from suppressed reflexes, resolve drained by both and scaled by the objective's pull;
+ later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
+ breaks the will, which releases every suppression. Static per-character values are this state with its
+ dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
+4. **Behaviour.** The drive selects and weights behaviours (hold against a reflex, withdraw, writhe, crawl to
+ the objective, pass out, get up) that emit targets and per-muscle strength into caller-owned arrays, and
+ nothing else. Today one stand-in: hold a pose against the withdrawal reflex, blended toward a withdraw pose
+ by the reflex leak, shaking with strain, and withdrawing once the will breaks.
+5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
+ PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
+ Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
+ the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
+ learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
+ policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
+
+`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
+caller-owned outputs, and reports its events (flinch, will broke, goal changed) as flags.
+
+## Invariants
+
+- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
+ core is a defect, not a convenience. The core's tests build without Ymir.
+- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
+ never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
+ no layer above.
+- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
+ world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
+ through that world.
+- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
+ never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
+ the pull of the objective) sets each reflex's gain, so a resolved character can hold its hand in the box.
+ Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
+ until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
+ (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
+- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
+ per-wound lookup.
+- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
+ inputs give the same outputs. A middleware that hitches is unusable in a game.
+- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
+ in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
+ Parameters that are only code defaults are not yet content.
+
+## First consumer
+
+Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
+not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
+behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
+`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
+separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
+the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
+`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
+
+## Not in scope
+
+- Adapting to arbitrary changes of body topology. The operator called it too ambitious; impairment is handled
+ through the drive and the behaviour set.
+- A Rust port of the core.
+- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
+- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
+ section 10.1).
+- Hand-tuned balance controllers of the SIMBICON family as the upright path.
+
+## Open
+
+- **Impairment states.** Self's proposal, not ruled: a closed set of named body states (intact, missing a leg,
+ missing an arm, both legs), with mirror symmetry; crawling as the first locomotion after any leg loss.
+- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
+- **The pain measure** (`lodur:question:pain-sweep-measure`).
+- **Ymir gaps Lodur needs next**: contact facts for pain from impacts, body removal, joint springs for stiff
+ ankles (`nibu-body:follow_up:ymir-soa-lodur-needs`).
+- **Renderer and rig** for Bad Day Simulator: nothing draws the puppet yet.
+- **Training host for v2.** Raven trains only when the household's GPU allows
+ (`motion-pipeline:ruling:raven-gpu-defers-to-household`).
+- **Trademark search** on "Bad Day Simulator" before anything public is announced.
+```
+
+Changes against r2: header names Nibu's mind; layer 5 binds to Ymir (Unity ArticulationBody wording gone, it
+was replaced by `lodur-body-on-ymir`); layers carry their first type names and the tick order; `one-physics-world`
+restated with the game as the world's owner; `core-engine-free` adds "core tests build without Ymir";
+`bounded-tick` adds same-inputs-same-outputs (it was implicit in every test); `content-is-cultcache` says code
+defaults are not content; the Rust-port line drops "until a first consumer outside Unity exists" (Unity is no
+longer the first host); Open drops the Unity version and UPM items (moot under Ymir) and the rig licence item
+becomes renderer and rig.
diff --git a/docs/first-slice.md b/docs/first-slice.md
index 361e474..ff4ff7e 100644
--- a/docs/first-slice.md
+++ b/docs/first-slice.md
@@ -33,7 +33,7 @@ Ymir's structure-of-arrays world. Nothing above layer 5 exists yet.
## Not measured, or limits found
-- Cross-platform bit-identity: unclaimed. Windows build and Unity consumption: unrun. One machine, Debug
+- Cross-platform bit-identity: unclaimed. Windows (2026-11-19, no MSVC): builds and passes with MinGW gcc, `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; Ymir 0b0321a emits `ymir_box3d.dll` under MinGW, so no rename is needed, and its world create/destroy lock makes test classes safe to run in parallel (before it, two live worlds crashed the host). Unity consumption: unrun. One machine, Debug
native build only; no Release run, no run in a second process.
- Explicit PD through torque lanes limits stiffness and damping: damping times the step must stay under the
inertia it acts on. Hips and spine went unstable at damping 15 and 20 and are set to 3 and 4; the gains
diff --git a/docs/lodur-target.md b/docs/lodur-target.md
index 06a5381..58ac288 100644
--- a/docs/lodur-target.md
+++ b/docs/lodur-target.md
@@ -1,123 +1,178 @@
# Lodur: target
-Campaign `lodur`. The operator's rulings live in the eureka-state mind under
-root `motion-pipeline` (the workshop ran there); this document holds the
-rationale and the design truths the campaign will produce. Where it and a
+Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
+workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
+ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
ruling disagree, the ruling wins and this file is stale.
## What it is for
-A character that reacts to forces and stimuli, and compensates for injury,
-the way a person would: it pulls back from something hot, jumps when poked,
-and crawls toward its objective on one leg if it wants that objective badly
-enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
+A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
+back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
+objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
-The field has the physics and the balance. NaturalMotion's Euphoria shipped
-active, physically simulated characters in GTA IV through Red Dead Redemption
-2, and learned trackers (DReCon, ProtoMotions, MaskedMimic) follow arbitrary
-motion while keeping their feet. What the field does not have, per the prior-art
-pass, is the nervous system on top: senses that are not forces, reflexes layered
-under deliberate behaviour with their own latencies, and a character whose will
-competes with its pain. Euphoria's reactions are whole-body behaviours a game
-starts; nothing in the record senses heat or a light touch, and nothing models
-the twenty seconds in which a wounded character crawls, slows, and passes out.
-That layer is Lodur. Evidence: `gamecult-ops/docs/research/euphoria-at-home-prior-art.md`
-(sections 1-9 at `8320c18`, section 10 at `15d9a4e`).
+The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
+characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
+follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
+nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
+latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
+`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
+`15d9a4e`).
-Named after the god in Voluspa who gives the first humans blood, warmth and
-good colour (`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
+Named after the god in Voluspa who gives the first humans blood, warmth and good colour
+(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
## Layers
-Signal flows one way per tick; each layer has one owner.
+Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
+(`netstandard2.1`, no references); layer 5 is a body binding.
-1. **Perception.** Contacts, impulses, temperature, proximity and named game
- stimuli become typed stimuli on body regions. A poke that barely moves the
- body is still a stimulus.
-2. **Reflex.** Fast, local responses to stimuli (withdrawal, startle,
- bracing), each with a latency, overlaid on whatever the body is doing.
- Their gain is set from above by the drive, the way descending pathways
- modulate spinal reflexes: the Gom Jabbar case. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary
- reaction about 200 ms (figures `[M]` in the research doc; verify before
- they become constants).
-3. **Drive.** Per-character state that evolves every tick: pain accumulates
- and decays, shock runs on a clock that blood loss speeds, adrenaline spikes
- on threat and fades; resolve is a trait, and the objective pulls. Static
- per-character values are this state with its dynamics frozen.
- (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
-4. **Behaviour.** The drive selects and weights behaviours (writhe, crawl to
- the objective, pass out, get up, the reflex overlay) that emit targets.
-5. **Body.** Follows targets (poses, IK goals) with per-muscle strength on the
- host engine's articulated physics. v1 is GameCult's own PD-tracking active
- ragdoll and ships the ground behaviours; v2 is a small learned tracker
- (DReCon scale: 340 us per character per frame measured, 60 us of it the
- policy) for upright states, behind the same interface.
- (`motion-pipeline:ruling:euphoria-body-layer-order`.)
+1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`, `Emitter`). Contacts, impulses, temperature,
+ proximity and named game stimuli become typed signals on body regions. Input: one point per body region
+ (from the body binding, read-only) and the game's stimulus sources. Two source kinds today: noxious box
+ volumes with an intensity the game writes each tick, and point emitters on the audio, visual and interrupt
+ channels (position, radius and intensity written each tick, falling off linearly to the radius), sensed at
+ one region and combined into one load, `1 - prod(1 - afferent)`. Output per region: the stimulus, and
+ the afferent signal after threshold, sensitisation and conduction delay; and the load. A poke that barely moves the body
+ is still a stimulus.
+2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
+ (withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
+ Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
+ (the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
+ Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
+ flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
+ (figures `[M]` in the research doc; verify before they become constants).
+3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
+ afferent input, strain from suppressed reflexes, arousal from sensory load; resolve drained by all three and
+ scaled by the active goal's pull, recovering only when pain and arousal are both low;
+ later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
+ breaks the will, which releases every suppression; the break is an event that counts (`Breaks`) and recurs:
+ the will mends when resolve climbs back to `WillMendsAt`. `Will` is what is available to hold a reflex down
+ and to power a voluntary layer: resolve times `Attention`, capped by `Consciousness` (both slots that read 1
+ until startle and physiology fill them). Static per-character values are this state with its
+ dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
+4. **The Brain.** The consumer's authored goals (a behaviour, a priority, a pull in [0, 1] that defaults to 0, no pull (the former objective pull
+ defaulted to 0.5), an optional minimum dwell, conditions over the drive
+ state), selected after a deliberate latency: the eligible goal of highest priority is wanted, and the
+ Actor commits it. Lodur has no flip rule of its own; every rule is Brain data
+ (`lodur:ruling:npc-brain-authors-goals`). One behaviour, `PoseBehaviour`: a pose held or a loop of pose keys,
+ blended toward a flinch pose by the reflex leak and shaking with strain, emitting targets and per-muscle
+ strength into caller-owned arrays and nothing else. Commitment is soft: a goal with a minimum dwell, counted
+ in ticks from the tick it took over, is left for a goal that ties or ranks below it only once the dwell has
+ passed, while a strictly higher-priority goal preempts during the dwell (after the deliberate latency); the
+ return trip from an entered goal is gated by that goal's own dwell, which is what bounds chatter at a threshold.
+ A goal also carries an entry effect on the drive (`EntryResolve`: the tick it takes over, resolve is set, which
+ is how rage resets the will), an `Effort` (resolve drained per second to sustain it) and `InvoluntarySeconds`
+ (an onset that runs without will and without paying the effort; +infinity is involuntary throughout)
+ (`lodur:ruling:rage-involuntary-onset-then-voluntary`). The will mix: a voluntary goal writes each muscle at
+ `HoldStrength x min(1, Will^WillCurve + leak x FlinchGain)` (the Actor passes `Will^WillCurve` as the weight), an involuntary one at `HoldStrength`, so a failing
+ will slackens the layer while a reflex that gets past it still moves the muscle
+ (`lodur:ruling:bds-sandbox-arenas-will-economy`).
+ A goal can also carry a sensory gain and an arousal target (`SensoryGain`, `EntryArousal`), reached linearly over `EntrySeconds`
+ from their values at takeover (0, the default, is at the takeover tick; the Start goal's apply at construction). The gain multiplies the sense
+ channels' afferents as they leave the conduction delay, so sensitisation still follows the world; `Load` is built from the gated afferents and
+ `ChannelStimulus` stays the world's. Sense reads the gain at the start of each tick, so a change of gain reaches `Load` one tick after the Actor sets it;
+ the ramp's last tick assigns the targets exactly. The nociceptive region afferents, the withdrawal reflex and its flinch are never gated. The Actor owns the gain
+ in force (`DriveState.SensoryGain`) and, through the ramp, arousal; after it the drive owns arousal again. Calm uses it to silence the office's
+ stressors and drain the stress bar, tailing off over a few seconds rather than cutting
+ (`lodur:ruling:stress-bar-shows-arousal-calm-silences`, `lodur:ruling:flinch-tail-after-stimulus`).
+ A built Brain owns copies of its data and reads back as read-only views. Considerations extend it.
+5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
+ PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
+ Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
+ the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
+ learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
+ policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
-Layers 1-4 are the core: C# with no engine references, testable without an
-engine. Layer 5 binds to the host: Unity `ArticulationBody` first; v2 inference
-through the engine's runner (Unity Inference Engine, ONNX Runtime).
-(`motion-pipeline:ruling:euphoria-first-consumer-sandbox-csharp-core`.)
+`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
+caller-owned outputs, and reports its events (flinch, will broke, goal changed) as flags.
+
+### Who writes what, per tick
+
+One order inside `Actor.Tick`: Perception senses (with the sensory gain in force) → each reflex steps on its
+afferent (gain from the previous tick's drive) → the drive steps (pain, strain, arousal, resolve, the break and
+the mend; the goal's effort is paid here) → the Brain decides (a decision is pending for the deliberate latency)
+and a due decision commits (entry resolve is set) → the entry ramp assigns gain and arousal → the goal's
+behaviour writes strengths and targets at the will's weight. The tick that commits a goal already writes under it.
+
+| Owner | Inputs | Outputs | Derived state | Forbidden writers |
+|---|---|---|---|---|
+| `Perception` | region points, the game's stimulus sources and emitters, the sensory gain passed in | per-region stimulus and afferent, per-channel stimulus and afferent, `Load` | sensitisation, the conduction rings; the channel afferents are gated, the stimuli are not | the drive or a goal writing an afferent; a gain outside [0, 1] (`Sense` refuses it, NaN and infinity included); gating a region (nociceptive) afferent |
+| Reflex (`WithdrawalReflex`) | its region's afferent and the drive's `Will` (the pull acts through resolve's drain, not here) | leak, strain load, flinch | none beyond its latency ring | the Brain or the behaviour setting a reflex gain |
+| Drive (`DriveState`) | afferent sum, strain load, `Load`, the goal's pull and effort | pain, strain, arousal, resolve, `Breaks`, `Will` (= min(resolve x attention, consciousness)), the break and mend events | `Will` is derived and never stored; the break recurs (it mends at `WillMendsAt`) | the Brain, a session or the body writing resolve, arousal or `Will`; the one sanctioned jumps are `Enter` (a goal's entry resolve) and the Actor's entry ramp (arousal) |
+| Attention, Consciousness slots | nothing yet: both read 1 (startle and physiology are the writers to come) | the two factors of `Will` | none | anything but the startle reflex (`lodur-startle-attention`) and physiology; the Actor's test seam `SetWillSlots` is internal |
+| Brain (`Brain`, `GoalSpec`) | the drive state it reads through conditions | the wanted goal; each goal's pull, priority, dwell, entry effects (`EntryResolve`, `EntryArousal`, `SensoryGain`, `EntrySeconds`), `Effort`, `InvoluntarySeconds` and behaviour | none: it is data, copied at build and read back read-only | a flip rule anywhere else (`lodur:ruling:npc-brain-authors-goals`) |
+| `Actor` | all of the above, one tick | the committed goal; `DriveState.SensoryGain`; arousal during a goal's `EntrySeconds`; the events | the pending decision and its tick, the dwell, the ramp's start values, the onset in whole ticks | a consumer setting the goal or the gain from outside |
+| Behaviour (`PoseBehaviour`) | the weight (the will's `Will^WillCurve` once the goal's involuntary onset is over, else 1), the leak, strain, time | strengths and targets into caller arrays: `HoldStrength x min(1, weight + leak x FlinchGain)` | none | writing a joint or a force (`body-one-interface`); any strength not under the will mix |
## Invariants
-- `core-engine-free`: the core assemblies reference no engine. A Unity type in
- the core is a defect, not a convenience.
-- `body-one-interface`: the body consumes only targets and per-muscle strength.
- Drive, behaviour and reflex never set a joint, force or physics property
- directly; swapping the PD ragdoll for a learned tracker changes no layer above.
-- `one-physics-world`: the body simulates in the host's physics world. No
- second world that the game's objects cannot touch.
-- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and
- overlays the running behaviour; it never waits for behaviour selection. Will
- acts on reflexes ahead of time, not after: drive state (resolve, the pull of
- the objective) sets each reflex's gain, so a resolved character can hold its
- hand in the box. Suppression is never free: the stimulus still feeds pain,
- and holding a reflex down shows as visible strain until resolve breaks.
- Deliberate behaviour takes over a fired reflex only after its own, longer
- latency. (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
-- `drive-is-state`: what a hurt character does is decided by drive state
- evolving over time, never by a per-wound lookup.
-- `bounded-tick`: per-character work per tick is bounded and allocates nothing
- in steady state. A middleware that hitches is unusable in a game.
-- `content-is-cultcache`: persistent content (puppet and object definitions,
- drive parameters, saved levels in Bad Day Simulator) is CultCache, per the
- GameCult substrate doctrine. JSON is schema publication only.
+- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
+ core is a defect, not a convenience. The core's tests build without Ymir.
+- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
+ never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
+ no layer above.
+- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
+ world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
+ through that world.
+- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
+ never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
+ the pull of the active goal) sets each reflex's gain, so a resolved character can hold its hand in the box.
+ Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
+ until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
+ (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
+- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
+ per-wound lookup.
+- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
+ inputs give the same outputs. A middleware that hitches is unusable in a game.
+- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
+ in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
+ Parameters that are only code defaults are not yet content.
+- `one-severance-owner`: a part is damaged, disabled or severed only by Lodur's physiology. Ymir reports
+ contacts and joint stress and removes a joint only on command; no physics threshold removes anything by
+ itself.
+- `will-is-the-budget`: every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
+ available will (resolve times attention, capped by consciousness); reflexes act against it with their own
+ gains; nothing writes targets outside that mix. A distraction such as a startle lowers attention, and so the
+ will every layer can spend (`lodur:ruling:bds-sandbox-arenas-will-economy`).
+- `sandbox-is-content`: in Bad Day Simulator an arena is a level built from the commands the player has; no
+ engine path exists only for an arena; levels are CultCache.
## First consumer
-Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of
-how People Playground plays, not its camera or UI. The player gets a level and
-places puppets of various sorts and objects with set behaviours and
-interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
-`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) It is a
-separate repo so that Lodur's boundary has a real consumer from the first cut.
+Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
+not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
+behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
+`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
+separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
+the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
+`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
## Not in scope
-- Adapting to arbitrary changes of body topology. The operator called it too
- ambitious; impairment is handled through the drive and the behaviour set.
-- A Rust port of the core, until a first consumer outside Unity exists.
+- Adapting to body topology outside the authored part tree (new limbs, re-rooted trees, morphology-agnostic
+ learned control). Losing a subtree of the authored tree is in scope as a closed set of impairment states per
+ limb slot (intact, impaired, disabled, severed), mirror-symmetric; the behaviour set compensates for each
+ (`lodur:ruling:bds-mvp-scope`).
+- Weapons, ballistics, gore and wound presentation: Bad Day Simulator content, not Lodur.
+- A Rust port of the core.
- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
-- Depending on RootMotion PuppetMaster (paid, not redistributable, and no
- balance control: research section 10.1).
-- Hand-tuned balance controllers of the SIMBICON family as the upright path.
+- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
+ section 10.1).
+- A hand-tuned balance controller of the SIMBICON family as the upright path. What holds the body up is the PD
+ muscles plus a will-scaled assist (and later a learned tracker). Stepping strategies that only re-plan targets
+ (capture-point foot placement after a shove, stumble, brace, get up) are in scope as behaviours.
-## Open before the first cut is mapped
+## Open
-The identity, lifecycle and authority table (one row per persistent kind) is
-written before any cut; these feed it.
-
-- **Impairment states.** Self's proposal, not ruled: impairment as a closed set
- of named body states (intact, missing a leg, missing an arm, both legs), with
- mirror symmetry; crawling as the first locomotion after any leg loss; one-leg
- hopping a stretch goal.
-- **Rig.** Which humanoid the sandbox ships with, and its licence for a public
- repo. The StreamPixels Little Heroes Mega Pack is a paid asset and cannot be
- committed to a public repo.
-- **Unity version** for Bad Day Simulator, and how Lodur's core is consumed
- (UPM package from the Lodur repo, or a built assembly).
+- **The MVP map** (`docs/bds-mvp-map.md`): systems by owner, authority map, model page and cut order for
+ grab, poke, physiology, dismemberment, will-weighted animation and IK, and sandbox levels.
+- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
+- **The pain measure** (`lodur:question:pain-sweep-measure`).
+- **Ymir gaps Lodur needs next**: contact facts, joint stress and removal, a grab anchor and impulses are
+ specced (`lodur:cut_spec:cut-ymir-contact-facts`, `cut-ymir-grab-anchor`, `cut-ymir-break-and-remove`);
+ joint springs for stiff ankles remain (`nibu-body:follow_up:ymir-soa-lodur-needs`).
+- **Renderer**: a Godot client (`lodur:ruling:bds-client-godot`), specced as `lodur:cut_spec:cut-godot-client-v1`.
- **Training host for v2.** Raven trains only when the household's GPU allows
(`motion-pipeline:ruling:raven-gpu-defers-to-household`).
-- **Trademark search** on "Bad Day Simulator" before anything public is
- announced.
+- **Trademark search** on "Bad Day Simulator" before anything public is announced.
diff --git a/docs/notes/motionbricks-fit.md b/docs/notes/motionbricks-fit.md
new file mode 100644
index 0000000..088ea84
--- /dev/null
+++ b/docs/notes/motionbricks-fit.md
@@ -0,0 +1,250 @@
+# MotionBricks fit survey
+
+Question: can NVIDIA MotionBricks (arXiv 2604.24833, `NVlabs/motionbricks`,
+Hugging Face weights) serve as an intent layer for Lodur: characters with
+nervous systems on Ymir, headless, state read as a structure-of-arrays view?
+
+Sources were read on 2026-11-06 at `NVlabs/motionbricks` commit `54fc563`
+(2026-10-23) unless stated. This is a survey; nothing was run. Items not
+established are listed in the last section.
+
+## Verdict
+
+**Optional tier, off by default, never core.** Keep the licence question out of
+the repo (weights are fetched by the user, not committed). Do not adopt now.
+
+- The licence is not the blocker. The NVIDIA Open Model Agreement carries no
+ field-of-use limit and no no-training clause (quoted below). One clause
+ (indemnity) needs a human to rule on it against the always-open-source rule.
+- The runtime is the blocker. The shipped runtime is Python plus TensorRT and
+ needs an NVIDIA GPU. Lodur's core is engine-free C# with a headless,
+ deterministic Ymir world. A CPU ONNX path is documented only as an example
+ snippet; its speed and determinism are unmeasured.
+- The output is a kinematic pose stream on a fixed human skeleton. It does not
+ claim to be physically feasible, which is the right shape for a *target*, and
+ the wrong shape for a body.
+
+Revisit when (a) a CPU ONNX run of the SOMA model is measured, and (b) Lodur has
+a body with a humanoid rig to track poses at all (Ymir's SoA world has spheres
+and static boxes only today).
+
+## 1. Licences
+
+| Part | Licence | Source |
+|---|---|---|
+| Code | Apache-2.0 | README "License" |
+| Docs and media | CC-BY-4.0 | README "License" |
+| Models (SOMA and G1 checkpoints, bundled ONNX) | NVIDIA Open Model Agreement (v. March 9, 2026; release date April 2, 2026) | README; `motionbricks/assets/onnx/LICENSE.md`; SOMA model card |
+| Sample BVH/CSV motions | NVIDIA Sample Data Evaluation License | `assets/motions/LICENSE.txt` |
+| Python runtime's TensorRT wheels | NVIDIA TensorRT Software License Agreement (proprietary, distributed with the packages) | README "License" |
+
+Agreement text: .
+Section numbers did not survive the page; clauses are cited by heading.
+
+### Open Model Agreement, against the questions asked
+
+- **Field of use.** None. The preamble: "Works are commercially usable. You are
+ free to create and distribute Derivative Works. NVIDIA does not claim
+ ownership to any outputs generated using the Works or Derivative Works."
+ No clause restricts a domain or use case.
+- **Training on outputs or on the model.** No clause restricts it. The only
+ termination trigger is: "If You institute patent or copyright litigation
+ against any entity ... alleging that the Work or an output from the Work
+ constitutes direct or contributory patent or copyright infringement, then any
+ licenses granted to You under this License for that Work shall terminate."
+- **Grant.** "a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+ irrevocable license to reproduce, prepare Derivative Works of, publicly
+ display, publicly perform, sublicense, and distribute the Work and such
+ Derivative Works in source or object form." (Irrevocable, subject to the
+ litigation clause above.)
+- **Derivatives.** "Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of, the
+ Work." Lodur calling the model through ONNX is therefore not a Derivative
+ Work of it. Fine-tuned or re-exported weights would be.
+- **Redistribution.** Allowed "with or without modifications, in source or
+ object form" on three conditions: give recipients a copy of the licence;
+ retain copyright, patent, trademark and attribution notices in the source
+ form of distributed Derivative Works; and, "If the Work includes a 'NOTICE'
+ text file", Derivative Works must carry "Licensed by NVIDIA Corporation under
+ the NVIDIA Open Model Agreement." (The repo has no `NOTICE` file at this
+ commit, so the attribution clause has nothing to trigger on in the code
+ repo; the Hugging Face checkpoint repos were not checked.) You may add
+ "additional or different license terms" to your own modifications.
+- **Other terms.** Trademarks not granted. As-is warranty and liability
+ disclaimers. Delaware law, Santa Clara County courts. Export and sanctions
+ compliance.
+- **Indemnity (the clause to rule on).** Under "Accepting Warranty or
+ Additional Liability": "You will indemnify and hold harmless NVIDIA from and
+ against any claim by any third party arising out of or related to your use or
+ distribution of the Works, Derivative Works thereof, or output from the Works
+ or Derivative Works." It sits in a section about offering warranties, but the
+ sentence is not limited to that case on its face. OSI-approved licences do not
+ carry an unconditional user indemnity. Whether that counts against "always
+ open source" is a legal and operator call, not an engineering one.
+
+### Fit with GameCult's always-open-source rule
+
+- Code (Apache-2.0): compatible.
+- Weights: permissive, redistributable and sublicensable, no field-of-use
+ limit. This is not an OSI licence and the indemnity sentence is unusual, so
+ "compatible" is not established until someone rules on it.
+- Cleanest posture, if ever adopted: Lodur's repo contains no weights. The
+ tier is a documented optional download that the user fetches themselves
+ under NVIDIA's terms. Lodur's own code stays open and separable (the
+ Derivative Works carve-out above). Do not commit the sample motions: they
+ are internal evaluation only and may not be redistributed.
+- Not a lawyer's reading. Nothing here is legal advice.
+
+## 2. Training data
+
+- Trained on Bones RigPlay 1 (RP1): 313,526 clips selected from about 350,000
+ clips / 700 hours, a 4,881-clip validation subset disjoint from training
+ (SOMA model card, "Training Dataset", "Testing Dataset").
+- Captured by Bones in a studio ("Automatic/Sensors"), processed by NVIDIA into
+ the 30-joint SOMA skeleton at 30 Hz. The corpus is not distributed with the
+ model: "Access to the dataset is governed separately from the model weights."
+- Bones' own page () describes RP01 as
+ "Enterprise-grade · IP-clean · Ready to license" and "full IP clearance",
+ optical Vicon mocap at 120 fps, 170+ performers. That is a commercial
+ product. **No public RP1 licence text was found**, so the terms binding
+ NVIDIA's weights to RP1 are unread.
+- The separate BONES-SEED dataset (HF `bones-studio/seed`, gated, licence at
+ ) is a different licence from RP1 and
+ is not what the weights were trained on, so it does not bind Lodur. It
+ matters only if Lodur wanted to fine-tune on it: SEED is restricted to
+ "Academic User" or "Qualifying Startup" (under $1,000,000 gross revenue),
+ forbids public mirrors, and forbids using it "to train, fine-tune, or
+ condition any generative model whose primary purpose ... is to generate
+ motion capture data", which excludes fine-tuning MotionBricks on it. (Models
+ that "consume the Dataset ... and produce non-data outputs", such as
+ control policies, are expressly allowed.) Closed data, so it fails the
+ open-source rule for anything Lodur ships.
+- The model's outputs are motion, not recordings; the model card says nothing
+ on whether generated motion can reproduce training clips. Unverified.
+
+## 3. Runtime
+
+- **Official runtime**: Python on NVIDIA Warp, Newton (viewer and scene) and
+ TensorRT. README: "The runtime uses TensorRT, which requires an NVIDIA GPU."
+ Tested on Windows and Linux x86-64 with an RTX 4090 only. `runtime_api.md`:
+ "Engines need a CUDA device." The first launch of each model builds a
+ TensorRT plan, which takes minutes, cached in `.trt-cache/`.
+- **Headless**: `runtime_api.md` ships "two short scripts in `examples` that
+ call the library without a viewer or the apps". Headless in the sense of
+ no window: yes by the doc. Headless in the sense of no GPU: no.
+- **Model**: SOMA is about 200M parameters (VQ-VAE 23.4M, pose predictor
+ 136.5M, root predictor 40.4M), ONNX opset 17, FP32 and mixed FP16 files,
+ variable batch N. Interface (`onnx_inference.md`): inputs `global_root_values`
+ [N,8,5], `local_root_values` [N,8,4], `local_poses` [N,8,267], three int32
+ masks [N,8] and `allowed_pred_num_tokens` [N,11]; outputs
+ `pred_global_motions` [N,64,366] and `pred_num_tokens` [N]. Files use Git LFS.
+- **Latency** (`onnx_inference.md`, TensorRT plan alone, RTX 4090, Windows,
+ inputs already on the GPU): SOMA FP32 2.50 ms at N=1 and 5.28 ms at N=32
+ (6,063 requests/s); mixed FP16 1.28 ms at N=1 and 3.93 ms at N=32. Input
+ preparation, decoding and endpoint correction are excluded. The 15,000 FPS /
+ 2 ms figures in the paper abstract are consistent with this. Starfire's GTX
+ 1070 (8 GB, shared) has no tensor-core FP16 path and is untested.
+- **CPU path**: `onnx_inference.md` shows an `onnxruntime` session with
+ `providers=["CPUExecutionProvider"]`, but the example loads the G1 model, not
+ SOMA. The SOMA card says "A CPU-versus-GPU inference comparison is not
+ provided." CPU speed for a 200M-parameter model is unmeasured here.
+- **ONNX leaves work undone**: the ONNX output "includes the boundary frames
+ and has no endpoint correction. The SOMA and G1 engines remove the boundary
+ frames and apply endpoint correction." The SOMA engine also decodes the
+ foot contacts packed in the output, and finds the model's 30 joints from the
+ input rig. A C# consumer would reimplement all of that against Python
+ reference code. Real cost, not estimated.
+- **Determinism**: not documented. The card warns "Mixed FP16 and FP32 can
+ produce different motion ... Differences can accumulate when generated
+ motion is fed back." Ymir's own stance is byte-equal lanes on the same
+ build, not across CPUs. A model whose output differs across precision and
+ backend, and which is fed its own output, cannot be replayed from a
+ command stream unless its outputs are recorded. Whether the graph itself is
+ free of sampling randomness is unverified.
+- **Platforms**: Windows and Linux x86-64 only; no macOS or ARM claim.
+
+## 4. Pose format and skeleton
+
+SOMA card ("Model Space", "Inference"):
+
+- 30-joint SOMA skeleton, 30 Hz, Y-up, metres. One output frame is 366 floats:
+ root position and heading (5), joint positions (87), 6D rotations (180),
+ joint velocities (90), foot contacts (4). 6D means the first two columns of
+ a rotation matrix.
+- One generation returns 18 to 58 valid frames (the ONNX tensor carries 24 to
+ 64 raw frames, between boundary frames), conditioned on 4 context poses and
+ 1 to 4 target poses; generations chain by feeding the last four poses back.
+ Conditioning is poses and constraints only: no text, no scene geometry.
+- The skeleton is fixed. Another rig needs retargeting (a SOMA Retargeter
+ exists; not read).
+- Stated limit, verbatim from the card: "Kinematic motion generation does not
+ establish dynamic feasibility, physical robot tracking, collision avoidance,
+ or safe contact. Physical execution requires a separate controller." And:
+ "Evaluate generated motion in the intended application. Physical execution
+ requires a separate tracking and safety system."
+
+## 5. How a tracker over Ymir's SoA world would follow it
+
+Today (`Ymir/docs/soa-world.md`): headless Box3D world, lanes for stable id,
+kind, position, rotation, linear and angular velocity, spheres and static boxes
+only. Its own "needed next" list is joints, capsule/box bodies, a torque write
+path, joint state lanes and contact facts. Lodur's `body-one-interface` says the
+body consumes only targets and per-muscle strength.
+
+Reading, not tested:
+
+1. A MotionBricks tier would sit under *behaviour*. Behaviour picks a target
+ pose set (a few SOMA poses placed ahead of the character) plus per-muscle
+ strength; the model fills the in-between frames at 30 Hz.
+2. The body maps SOMA joint rotations (6D to quaternion) onto the Ymir
+ ragdoll's joints, retargeted if the ragdoll is not the SOMA 30-joint rig,
+ and drives each joint's PD or motor target toward the frame for the current
+ tick. Strength scales the torque limit. A limb with strength loss lags or
+ misses the target; that is the "motor system that may fail".
+3. The measured ragdoll state (the SoA lanes plus joint state) feeds back as
+ perception, and, once the character is no longer on the kinematic path (fall,
+ impairment), the context poses for the next generation come from the *real*
+ body, not the previous output (the runtime's `MotionRecorder` / history
+ already takes context from "the last four played frames"). A body that is
+ on the floor is out of distribution for a model trained on upright studio
+ mocap; expect garbage targets then and fall back to Lodur's own ground
+ behaviours (design target: v1 ships those).
+4. The model runs per character, not per physics tick: 30 Hz targets,
+ one generation per 18 to 58 frames. It is intent, below the nervous system
+ and above the tracker; reflexes overlay it and never wait for it.
+
+Missing for this to run at all: a jointed humanoid in Ymir's SoA world, a
+joint motor write path, and a SOMA-to-ragdoll rig mapping. All three are Ymir
+or Lodur work that exists whether or not MotionBricks is used.
+
+## 6. Fit
+
+- Fit: target poses for a motor system that may fail. Kinematic, human-only,
+ upright-trained, poses in and poses out. Not a replacement for the physical
+ body, and the card says as much.
+- Competing options already in the design target: Lodur's own
+ behaviours emit targets directly (crawl, writhe); a small learned tracker
+ (DReCon scale) is v2. MotionBricks is the only one that supplies natural
+ locomotion and transitions between authored pose targets, and it is the
+ heaviest by orders of magnitude.
+- Lodur's characters are meant to be hurt, not graceful. Whether upright
+ mocap-derived targets help the interesting 20 seconds (crawl, shock, pass
+ out) is doubtful. They would help locomotion before injury.
+
+## Unverified
+
+- Whether the Open Model Agreement's indemnity sentence is acceptable under
+ GameCult's open-source rule (needs a ruling, and likely a lawyer).
+- RP1 licence text and what it says, if anything, about models trained on it.
+- Whether the Hugging Face checkpoint repos ship a `NOTICE` file (none in the
+ GitHub repo at `54fc563`), which would trigger the attribution clause.
+- SOMA ONNX on CPU: speed, memory, and agreement with TensorRT output.
+- Bit determinism of one backend across runs; any sampling randomness inside
+ the graph.
+- Behaviour on a GTX 1070 (no tensor-core FP16) and under GPU sharing.
+- Quality of targets when the body is off the training distribution (prone,
+ one-legged).
+- SOMA Retargeter licence and fit for Lodur's rig; Lodur has no rig yet.
+- Effort to port boundary-frame trimming, endpoint correction and foot-contact
+ decoding to C#.
+- The paper (arXiv 2604.24833) was read at abstract level only.
diff --git a/src/Lodur.Body.Ymir/AssemblyInfo.cs b/src/Lodur.Body.Ymir/AssemblyInfo.cs
deleted file mode 100644
index 4b4cdac..0000000
--- a/src/Lodur.Body.Ymir/AssemblyInfo.cs
+++ /dev/null
@@ -1 +0,0 @@
-[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Lodur.Tests")]
diff --git a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs
index eaa28f0..6cd2316 100644
--- a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs
+++ b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs
@@ -4,13 +4,19 @@ using Ymir.Box3D;
namespace Lodur.Body.Ymir
{
/// The ragdoll's joints, in strength-array and target-array order.
- internal enum Muscle
+ public enum Muscle
{
Spine, Neck, ShoulderL, ShoulderR, ElbowL, ElbowR, HipL, HipR, KneeL, KneeR, AnkleL, AnkleR
}
+ /// The body regions perception senses at, in the order of the point arrays fills.
+ public enum Region
+ {
+ HandL, HandR, Head
+ }
+
/// The ragdoll's bodies, also the limb label written into the world's limb lane.
- internal enum Limb
+ public enum Limb
{
Pelvis, Torso, Head, UpperArmL, UpperArmR, LowerArmL, LowerArmR, ThighL, ThighR, ShinL, ShinR, FootL, FootR
}
@@ -19,16 +25,19 @@ namespace Lodur.Body.Ymir
/// A 13-body humanoid built in a caller-owned Ymir SoA world (invariant one-physics-world): capsule limbs,
/// box pelvis, torso and feet, a sphere head, spherical joints at spine, neck, shoulders and hips, hinges at
/// elbows, knees and ankles. Facing +z, left is +x, standing on y = 0 at the creation pose, which is also
- /// every joint's zero. is the muscle layer: it turns caller-owned strengths and target
+ /// every joint's zero. The game owns the physics world: Build adds bodies to the caller's world and Lodur never creates or steps one. is the muscle layer: it turns caller-owned strengths and target
/// rotations into torques on the world's torque lanes and does nothing else to the physics.
///
- internal sealed class HumanoidRagdoll
+ public sealed class HumanoidRagdoll
{
public const int MuscleCount = 12;
public const int LimbCount = 13;
+ public const int RegionCount = 3;
private const float Density = 1000f;
private const float Friction = 0.8f;
+ private const float LowerArmRadius = 0.04f;
+ private const float LowerArmHalf = 0.10f;
private const float HeadRolling = 0.1f; // a bare sphere on the ground rolls on, so the fallen head never settles
private readonly Box3DSoaWorld _world;
@@ -69,7 +78,7 @@ namespace Lodur.Body.Ymir
foreach (var (side, sx) in new[] { (0, 1f), (1, -1f) })
{
var upperArm = Capsule(Limb.UpperArmL + side, torso, sx * 0.21f, 1.395f, 0.045f, 0.11f);
- var lowerArm = Capsule(Limb.LowerArmL + side, upperArm, sx * 0.21f, 1.10f, 0.04f, 0.10f);
+ var lowerArm = Capsule(Limb.LowerArmL + side, upperArm, sx * 0.21f, 1.10f, LowerArmRadius, LowerArmHalf);
var thigh = Capsule(Limb.ThighL + side, pelvis, sx * 0.09f, 0.79f, 0.07f, 0.18f);
var shin = Capsule(Limb.ShinL + side, thigh, sx * 0.09f, 0.31f, 0.06f, 0.17f);
Box(Limb.FootL + side, shin, sx * 0.09f, 0.04f, 0.05f, 0.05f, 0.04f, 0.12f);
@@ -135,5 +144,34 @@ namespace Lodur.Body.Ymir
v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
}
}
+
+ ///
+ /// Writes each 's world point into the caller's arrays, one entry per region: a hand is the
+ /// tip of its lower-arm capsule, the capsule's centre plus its rotation applied to (0, -(half length + radius), 0).
+ /// The ragdoll has no hand body, so perception senses at this point. The head is the head body's centre. Allocates nothing.
+ ///
+ public void ReadRegions(Span x, Span y, Span z)
+ {
+ if (x.Length != RegionCount || y.Length != RegionCount || z.Length != RegionCount)
+ {
+ throw new ArgumentException($"x, y and z need {RegionCount} entries, one per region.");
+ }
+
+ var v = _world.View;
+ for (var r = 0; r < (int)Region.Head; r++)
+ {
+ var i = _bodyLane[(int)(r == (int)Region.HandL ? Limb.LowerArmL : Limb.LowerArmR)];
+ new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i])
+ .Rotate(0f, -(LowerArmHalf + LowerArmRadius), 0f, out var dx, out var dy, out var dz);
+ x[r] = v.PositionX[i] + dx;
+ y[r] = v.PositionY[i] + dy;
+ z[r] = v.PositionZ[i] + dz;
+ }
+
+ var head = _bodyLane[(int)Limb.Head];
+ x[(int)Region.Head] = v.PositionX[head];
+ y[(int)Region.Head] = v.PositionY[head];
+ z[(int)Region.Head] = v.PositionZ[head];
+ }
}
}
diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
new file mode 100644
index 0000000..190080a
--- /dev/null
+++ b/src/Lodur.Core/Actor.cs
@@ -0,0 +1,215 @@
+using System;
+
+namespace Lodur
+{
+ /// What happened on one tick.
+ [Flags]
+ public enum TickEvents
+ {
+ None = 0,
+ /// A reflex leaked past the suppression the will still held. With no will nothing is suppressed, so there is no flinch.
+ Flinch = 1,
+ /// Resolve reached zero this tick: the will broke (again, if it had mended).
+ WillBroke = 2,
+ /// The Brain's chosen goal took over, its deliberate latency after the choice.
+ GoalChanged = 4,
+ }
+
+ ///
+ /// One character's nervous state and the per-tick order: perception, reflex, drive, the Brain's goal, 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 Brain _brain;
+ private readonly long _latency;
+ private readonly long[] _dwell;
+ private readonly long[] _onset;
+ private readonly long[] _entryTicks;
+ private readonly Perception _perception;
+ private readonly WithdrawalReflex[] _reflexes;
+ private DriveState _drive = DriveState.Fresh;
+ private long _tick;
+ private int _goal;
+ private int _pending = -1;
+ 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.
+ private long _rampTicks = -1;
+ private double _rampGain0;
+ private double _rampArousal0;
+
+ public Actor(
+ double tickSeconds, int regionCount,
+ NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, Brain brain,
+ NerveParameters? senses = null, int senseRegion = 0)
+ {
+ brain.Validate();
+ drive.Validate();
+
+ _dt = tickSeconds;
+ _driveP = drive;
+ _brain = brain;
+ _goal = brain.Start;
+ _drive.SensoryGain = brain.Goals[brain.Start].SensoryGain;
+ if (brain.Goals[brain.Start].EntryArousal is double startArousal)
+ {
+ _drive.Arousal = startArousal;
+ }
+ // The Start goal takes over at construction: its entry effect applies like any other goal's.
+ if (brain.Goals[brain.Start].EntryResolve is double startEntry)
+ {
+ _drive.Enter(drive, startEntry);
+ }
+ _latency = Math.Max(1, (long)Math.Round(brain.DeliberateLatencySeconds / tickSeconds));
+ _dwell = new long[brain.Goals.Count];
+ _onset = new long[brain.Goals.Count];
+ _entryTicks = new long[brain.Goals.Count];
+ for (var g = 0; g < _dwell.Length; g++)
+ {
+ _dwell[g] = (long)Math.Round(brain.Goals[g].MinDwellSeconds / tickSeconds);
+ // Rounded to whole ticks once, like the dwell, so the onset is the same number of ticks whatever the tick length does to a product.
+ // A quotient past the long range (+infinity included) is involuntary throughout: the cast of an out-of-range double is not defined across runtimes.
+ var onsetTicks = brain.Goals[g].InvoluntarySeconds / tickSeconds;
+ _onset[g] = onsetTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(onsetTicks);
+ // The entry ramp is rounded once as well; EntrySeconds is finite, but its quotient can still pass the long range.
+ var entryTicks = brain.Goals[g].EntrySeconds / tickSeconds;
+ _entryTicks[g] = entryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(entryTicks);
+ }
+
+ _perception = new Perception(nerve, tickSeconds, regionCount, senses, senseRegion);
+ _reflexes = new WithdrawalReflex[regionCount];
+ for (var r = 0; r < regionCount; r++)
+ {
+ _reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds);
+ }
+ }
+
+ 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;
+
+ /// Sets the drive's Attention and Consciousness slots; a seam for the tests until lodur-startle-attention and lodur-physiology drive them.
+ internal void SetWillSlots(double attention, double consciousness)
+ {
+ _drive.Attention = attention;
+ _drive.Consciousness = consciousness;
+ }
+
+ public Brain Brain => _brain;
+
+ /// The index in 's goals of the goal in force; it changes only on the tick that reports .
+ public int GoalIndex => _goal;
+
+ /// How long the goal in force will have been in force at the next tick; 0 on the tick it took over.
+ public double SecondsInGoal => (_tick - _goalSince) * _dt;
+
+ public double Stimulus(int region) => _perception.Stimulus(region);
+
+ public double Afferent(int region) => _perception.Afferent(region);
+
+ /// The sensory load this tick: the channels' afferents combined, 0..1.
+ public double Load => _perception.Load;
+
+ public double ChannelStimulus(Channel channel) => _perception.ChannelStimulus(channel);
+
+ public double ChannelAfferent(Channel channel) => _perception.ChannelAfferent(channel);
+
+ ///
+ /// 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
+ /// sources, sensed at the sense region's point.
+ ///
+ public TickEvents Tick(
+ ReadOnlySpan regionX, ReadOnlySpan regionY, ReadOnlySpan regionZ,
+ ReadOnlySpan sources, Span strengths, Span targets,
+ ReadOnlySpan emitters = default)
+ {
+ var events = TickEvents.None;
+ // A flinch is the leak of a suppressed reflex; with no will nothing is suppressed, so none is reported.
+ var holding = _drive.Will > 0.0;
+
+ _perception.Sense(regionX, regionY, regionZ, sources, emitters, _drive.SensoryGain);
+
+ 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;
+ }
+ }
+
+ // Effort is paid only once the goal is voluntary: the onset (InvoluntarySeconds) runs without will, and without cost.
+ var inForce = _brain.Goals[_goal];
+ var effort = _tick - _goalSince >= _onset[_goal] ? inForce.Effort : 0.0;
+ if (_drive.Step(_driveP, _dt, afferent, strainLoad, _perception.Load, inForce.Pull, effort))
+ {
+ events |= TickEvents.WillBroke;
+ }
+
+ // A decision in flight commits at its tick even if the condition that chose it has lapsed; none is made while one is
+ // 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))
+ {
+ _pending = wanted;
+ _switchTick = _tick + _latency;
+ }
+ }
+
+ if (_pending >= 0 && _tick == _switchTick)
+ {
+ _goal = _pending;
+ _pending = -1;
+ _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);
+ }
+ }
+
+ // For EntrySeconds after a takeover the Actor, not the drive, takes the gain (and the arousal, if the goal declares one) from their values at
+ // takeover to the goal's targets, linearly; its last tick assigns the targets themselves (a lerp need not land on a nonzero target), and after it the drive
+ // owns arousal again. Sense reads the gain at the start of the next tick, so a change of gain reaches Load one tick after the Actor sets it.
+ var sinceGoal = _tick - _goalSince;
+ if (sinceGoal <= _rampTicks)
+ {
+ var goal = _brain.Goals[_goal];
+ var last = sinceGoal == _rampTicks; // also the takeover tick of a zero-length ramp
+ var k = last ? 1.0 : (double)sinceGoal / _rampTicks;
+ _drive.SensoryGain = last ? goal.SensoryGain : _rampGain0 + (goal.SensoryGain - _rampGain0) * k;
+ if (goal.EntryArousal is double target)
+ {
+ _drive.Arousal = last ? target : _rampArousal0 + (target - _rampArousal0) * k;
+ }
+ }
+
+ // 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 = _tick - _goalSince >= _onset[_goal] ? 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/Brain.cs b/src/Lodur.Core/Brain.cs
new file mode 100644
index 0000000..c5610ab
--- /dev/null
+++ b/src/Lodur.Core/Brain.cs
@@ -0,0 +1,267 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// A number the drive carries, as a condition reads it.
+ public enum DriveQuantity
+ {
+ Pain,
+ Strain,
+ Arousal,
+ Resolve,
+ /// 1 while the will is broken now (it mends), else 0.
+ WillBroken,
+ /// How many times the will has broken: the one-way latch, for a goal that must hold after a mend.
+ Breaks,
+ }
+
+ public enum ConditionOp
+ {
+ AtLeast,
+ Below,
+ }
+
+ /// 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,
+ };
+ return Op == ConditionOp.AtLeast ? v >= Threshold : v < Threshold;
+ }
+ }
+
+ /// One thing the consumer wants a character to be doing, and when it is eligible to be.
+ public sealed record GoalSpec
+ {
+ /// The consumer's name for it; Lodur never reads it.
+ public string Id { get; init; } = "";
+
+ /// The eligible goal of the highest priority is wanted.
+ public double Priority { get; init; }
+
+ /// How hard the goal pulls, in [0, 1], default 0 (no pull): resolve drain is scaled by (1 - pull) while it is active. It is not a second resolve bar.
+ public double Pull { get; init; }
+
+ ///
+ /// Commitment, soft: until this goal has been active this long (rounded to whole ticks like the latency, counted
+ /// from the tick it took over), a goal that does not strictly outrank it cannot be decided on; a strictly
+ /// higher-priority goal preempts at once, after the deliberate latency. 0 (the default) never holds a goal. It keeps
+ /// a condition hovering at its threshold from making the Brain chatter: the return trip from an entered goal is
+ /// gated by that goal's own dwell. The dwell holds the decision to leave; a decision already in flight commits.
+ ///
+ public double MinDwellSeconds { get; init; }
+
+ ///
+ /// The resolve the character has the tick this goal takes over (for the Start goal, at construction), in [0, 1]; null leaves resolve as it is. Rage is what
+ /// the will breaking leads to, and it resets the will (lodur:ruling:rage-involuntary-onset-then-voluntary).
+ ///
+ public double? EntryResolve { get; init; }
+
+ /// Resolve drained per second to sustain this goal, finite and not negative, default 0; it is not paid during and is scaled by (1 - Pull) like the rest of the drain.
+ public double Effort { get; init; }
+
+ ///
+ /// The gain on the sense channels (not the nociceptive region afferents) while this goal is in force, in [0, 1], default 1; 0 is deaf and blind to the
+ /// world's stimuli, which keep sounding (lodur:ruling:stress-bar-shows-arousal-calm-silences). Applied like : at the tick the goal
+ /// takes over, and at construction for the Start goal. The sense reads the gain at the start of each tick, so a change reaches
+ /// one tick after the Actor sets it.
+ ///
+ public double SensoryGain { get; init; } = 1.0;
+
+ ///
+ /// The arousal this goal brings, in [0, 1]; null leaves arousal to the drive. Calm drops it so the stress bar drains
+ /// (lodur:ruling:stress-bar-shows-arousal-calm-silences). Reached over , then the drive owns arousal again.
+ ///
+ public double? EntryArousal { get; init; }
+
+ ///
+ /// How long after it takes over the goal's and are reached, finite and not negative, default 0 (at the
+ /// takeover tick): a linear ramp from their values at takeover, rounded to whole ticks once like the onset. The aftershock tail
+ /// of lodur:ruling:flinch-tail-after-stimulus. It does not ramp , which stays a snap. For the Start goal the targets apply at construction.
+ ///
+ public double EntrySeconds { get; init; }
+
+ ///
+ /// How long after it takes over the goal runs without will (rounded to whole ticks once, like the dwell), not negative, default 0 (voluntary from the first tick);
+ /// +infinity is involuntary throughout. While involuntary the behaviour writes at full weight and pays no Effort;
+ /// after it the goal is voluntary: sustained by like every other voluntary layer.
+ ///
+ public double InvoluntarySeconds { get; init; }
+
+ private Condition[] _when = Array.Empty();
+ private IReadOnlyList _whenView = Array.AsReadOnly(Array.Empty());
+
+ /// All must hold for the goal to be eligible; none means always eligible. Copied when set; read back as a read-only view.
+ public IReadOnlyList When
+ {
+ get => _whenView;
+ init
+ {
+ _when = new Condition[value.Count];
+ for (var c = 0; c < _when.Length; c++)
+ {
+ _when[c] = value[c];
+ }
+
+ _whenView = Array.AsReadOnly(_when);
+ }
+ }
+
+ internal bool Eligible(in DriveState drive)
+ {
+ for (var c = 0; c < _when.Length; c++)
+ {
+ if (!_when[c].Holds(drive))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public PoseBehaviour Behaviour { get; init; } = new PoseBehaviour();
+ }
+
+ ///
+ /// Layer 4: the consumer's goals, selected by conditions over the drive state. Lodur has no flip rule of its
+ /// own; every rule is this data. Data only: the Actor commits the choice, after the deliberate latency.
+ ///
+ public sealed record Brain
+ {
+ private IReadOnlyList _goals = Array.Empty();
+
+ /// The goals, copied when set: later changes to the caller's list or arrays do not reach a Brain, and the getter is a read-only view.
+ public IReadOnlyList Goals
+ {
+ get => _goals;
+ init
+ {
+ var copy = new GoalSpec[value.Count];
+ for (var i = 0; i < copy.Length; i++)
+ {
+ copy[i] = value[i];
+ }
+
+ _goals = Array.AsReadOnly(copy);
+ }
+ }
+
+ /// The index of the goal a character begins in.
+ public int Start { get; init; }
+
+ /// 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)
+ {
+ var best = -1;
+ var bestPriority = 0.0;
+ for (var i = 0; i < Goals.Count; i++)
+ {
+ var goal = Goals[i];
+ if (!goal.Eligible(drive))
+ {
+ continue;
+ }
+
+ if (best < 0 || goal.Priority > bestPriority || (goal.Priority == bestPriority && i == current))
+ {
+ best = i;
+ bestPriority = goal.Priority;
+ }
+ }
+
+ return best < 0 ? current : best;
+ }
+
+ internal void Validate()
+ {
+ if (Goals.Count == 0)
+ {
+ throw new ArgumentException("A brain needs at least one goal.");
+ }
+
+ if (Start < 0 || Start >= Goals.Count)
+ {
+ throw new ArgumentException("Start is not a goal index.");
+ }
+
+ if (!(DeliberateLatencySeconds >= 0.0 && double.IsFinite(DeliberateLatencySeconds)))
+ {
+ throw new ArgumentException("DeliberateLatencySeconds must be finite and not negative.");
+ }
+
+ var muscles = -1;
+ foreach (var goal in Goals)
+ {
+ 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].");
+ }
+
+ if (!(goal.MinDwellSeconds >= 0.0 && double.IsFinite(goal.MinDwellSeconds)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: MinDwellSeconds must be finite (not infinite) and not negative.");
+ }
+
+ if (goal.EntryResolve is double entry && !(entry >= 0.0 && entry <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntryResolve must be in [0, 1].");
+ }
+
+ if (!(goal.SensoryGain >= 0.0 && goal.SensoryGain <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: SensoryGain must be in [0, 1].");
+ }
+
+ if (goal.EntryArousal is double entryArousal && !(entryArousal >= 0.0 && entryArousal <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntryArousal must be in [0, 1].");
+ }
+
+ if (!(goal.EntrySeconds >= 0.0 && double.IsFinite(goal.EntrySeconds)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntrySeconds must be finite and not negative.");
+ }
+
+ if (!(goal.Effort >= 0.0 && double.IsFinite(goal.Effort)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Effort must be finite and not negative.");
+ }
+
+ if (!(goal.InvoluntarySeconds >= 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: InvoluntarySeconds must not be negative or NaN (infinity is allowed).");
+ }
+
+ foreach (var c in goal.When)
+ {
+ if (!double.IsFinite(c.Threshold))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a condition threshold is not finite.");
+ }
+ }
+
+ goal.Behaviour.Validate(goal.Id);
+ if (muscles >= 0 && goal.Behaviour.MuscleCount != muscles)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: every behaviour needs the same muscle count.");
+ }
+
+ muscles = goal.Behaviour.MuscleCount;
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs
new file mode 100644
index 0000000..0fe8cfe
--- /dev/null
+++ b/src/Lodur.Core/DriveState.cs
@@ -0,0 +1,146 @@
+using System;
+
+namespace Lodur
+{
+ /// The drive's tunables: how pain, strain and arousal 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;
+
+ /// Per-character multiplier on resolve drain (the consumer draws its trait spread).
+ public double DrainTrait { get; init; } = 1.0;
+
+ /// How fast arousal rises toward 1 under full sensory load.
+ public double ArousalRise { get; init; } = 0.5;
+
+ /// How fast arousal falls back once the load stops.
+ public double ArousalDecay { get; init; } = 0.1;
+
+ /// Resolve drained per second at full arousal, before the active goal's pull and the drain trait scale it.
+ public double ResolveDrainArousal { get; init; } = 0.1;
+
+ /// Resolve recovers only while arousal is below this, as well as pain being low.
+ public double ResolveRecoversBelowArousal { get; init; } = 0.1;
+
+ /// 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;
+
+ /// Refuses a value the drive cannot run on, at construction rather than as a NaN several ticks in: every rate, trait and threshold is finite and not negative; WillMendsAt is in (0, 1]; WillCurve is above 0.
+ internal void Validate()
+ {
+ var rates = new[]
+ {
+ (PainRise, nameof(PainRise)), (PainDecay, nameof(PainDecay)), (StrainRecover, nameof(StrainRecover)),
+ (ResolveDrainPain, nameof(ResolveDrainPain)), (ResolveDrainStrain, nameof(ResolveDrainStrain)),
+ (ResolveRecovery, nameof(ResolveRecovery)), (ResolveRecoversBelowPain, nameof(ResolveRecoversBelowPain)),
+ (DrainTrait, nameof(DrainTrait)), (ArousalRise, nameof(ArousalRise)), (ArousalDecay, nameof(ArousalDecay)),
+ (ResolveDrainArousal, nameof(ResolveDrainArousal)), (ResolveRecoversBelowArousal, nameof(ResolveRecoversBelowArousal)),
+ };
+ foreach (var (value, name) in rates)
+ {
+ if (!(value >= 0.0 && double.IsFinite(value)))
+ {
+ throw new ArgumentException($"{name} must be finite and not negative.");
+ }
+ }
+
+ if (!(WillMendsAt > 0.0 && WillMendsAt <= 1.0))
+ {
+ throw new ArgumentException("WillMendsAt must be in (0, 1].");
+ }
+
+ if (!(WillCurve > 0.0 && double.IsFinite(WillCurve)))
+ {
+ throw new ArgumentException("WillCurve must be finite and above 0.");
+ }
+ }
+ }
+
+ ///
+ /// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the
+ /// reflex held down, arousal with sensory load; resolve drains under all three and recovers when pain and
+ /// arousal are both low. Resolve reaching zero breaks the will (counted in ); the broken will
+ /// mends when resolve climbs back to and can break again. Resolve keeps
+ /// evolving through a break. Only the owning steps it.
+ ///
+ public struct DriveState
+ {
+ public double Pain { get; private set; }
+ public double Strain { get; private set; }
+
+ /// Sensory load carried over time, 0..1; it rises under load and decays when quiet.
+ public double Arousal { get; internal set; }
+ public double Resolve { get; private set; }
+
+ /// True from a break until the will mends: broken now, not "has ever broken" (see ).
+ public bool WillBroken { get; private set; }
+
+ /// How many times the will has broken.
+ public int Breaks { get; private set; }
+
+ /// The fraction of resolve that attention lets through, 0..1. A slot, 1 until lodur-startle-attention fills it.
+ public double Attention { get; internal set; }
+
+ /// The ceiling on the will that wakefulness sets, 0..1. A slot, 1 until lodur-physiology fills it.
+ public double Consciousness { get; internal set; }
+
+ /// The will that is available to hold reflexes down and to power voluntary behaviour: resolve through attention, capped by consciousness.
+ public double Will => Math.Min(Resolve * Attention, Consciousness);
+
+ /// The gain on the sense channels in force, 0..1: the goal in force's as the Actor has reached it. Written only by the Actor.
+ public double SensoryGain { get; internal set; }
+
+ internal static DriveState Fresh => new DriveState { Resolve = 1.0, Attention = 1.0, Consciousness = 1.0, SensoryGain = 1.0 };
+
+ /// A goal's entry effect: sets resolve, then the mend check runs (a break the entry lifts past is mended). It is not a break and counts none.
+ internal void Enter(DriveParameters p, double resolve)
+ {
+ Resolve = resolve;
+ if (WillBroken && Resolve >= p.WillMendsAt)
+ {
+ WillBroken = false;
+ }
+ }
+
+ /// Steps one tick; returns true on the tick the will breaks (each break, not only the first). is the active goal's: it scales resolve drain by (1 - pull). is the active goal's resolve drained per second to sustain it (0 while it is involuntary); it joins the drain sum, so pull scales it too.
+ internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad, double load, double pull, double effort)
+ {
+ Arousal = Math.Min(Math.Max(Arousal + dt * (p.ArousalRise * load * (1.0 - Arousal) - p.ArousalDecay * Arousal), 0.0), 1.0);
+ 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));
+ var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain + p.ResolveDrainArousal * Arousal + effort) * (1.0 - pull) * p.DrainTrait;
+ var recovery = Pain < p.ResolveRecoversBelowPain && Arousal < p.ResolveRecoversBelowArousal ? p.ResolveRecovery * (1.0 - Resolve) : 0.0;
+ Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0);
+ if (WillBroken)
+ {
+ if (Resolve >= p.WillMendsAt)
+ {
+ WillBroken = false;
+ }
+
+ return false;
+ }
+
+ if (Resolve <= 0.0)
+ {
+ WillBroken = true;
+ Breaks++;
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
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/Lodur.Core.csproj b/src/Lodur.Core/Lodur.Core.csproj
index 9588aab..b39e30e 100644
--- a/src/Lodur.Core/Lodur.Core.csproj
+++ b/src/Lodur.Core/Lodur.Core.csproj
@@ -7,4 +7,9 @@
Lodur
+
+
+
+
+
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..cdfc3ab
--- /dev/null
+++ b/src/Lodur.Core/Perception.cs
@@ -0,0 +1,252 @@
+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 sensory channels a point emitter can speak on. Each has its own stimulus, sensitisation and nerve.
+ public enum Channel
+ {
+ Audio = 0,
+ Visual = 1,
+ Interrupt = 2,
+ }
+
+ ///
+ /// A game stimulus at a point: sound, flicker, a notification. The game writes its position and intensity every
+ /// tick; Lodur decides what reaches the sense region. What arrives is the intensity falling off linearly to zero
+ /// at the radius.
+ ///
+ public struct Emitter
+ {
+ public Channel Channel;
+ public float X, Y, Z;
+ public float Radius;
+ public double Intensity;
+
+ public Emitter(Channel channel, float x, float y, float z, float radius, double intensity = 0.0)
+ {
+ Channel = channel;
+ X = x; Y = y; Z = z;
+ Radius = radius;
+ Intensity = intensity;
+ }
+
+ /// Intensity * max(0, 1 - distance / Radius) at the point; zero at and beyond the radius.
+ public double Received(float x, float y, float z)
+ {
+ double dx = x - X, dy = y - Y, dz = z - Z;
+ var distance = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+ return Radius > 0f && distance < Radius ? Intensity * (1.0 - distance / Radius) : 0.0;
+ }
+ }
+
+ /// The nerve's tunables, the transduction of any channel, noxious or sensory: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain.
+ public sealed record NerveParameters
+ {
+ public double Threshold { 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 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. With a sensory nerve it also senses point emitters at one
+ /// region on three channels and combines the channels into one load. 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 readonly NerveParameters? _senses;
+ private readonly int _senseRegion;
+ private readonly int _senseSlots;
+ private readonly double[] _senseRing; // afferent in flight per channel, channel-major
+ private readonly double[] _senseSens = new double[ChannelCount];
+ private readonly double[] _senseStimulus = new double[ChannelCount];
+ private readonly double[] _senseAfferent = new double[ChannelCount];
+ private long _tick;
+
+ private const int ChannelCount = 3;
+
+ /// The nerve of the sensory channels; null for a body with no senses (the load stays zero).
+ /// The region whose point the emitters are sensed at.
+ public Perception(NerveParameters parameters, double tickSeconds, int regionCount, NerveParameters? senses = null, int senseRegion = 0)
+ {
+ _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];
+ _senses = senses;
+ _senseRegion = senseRegion;
+ if (senses != null)
+ {
+ if ((uint)senseRegion >= (uint)regionCount)
+ {
+ throw new ArgumentOutOfRangeException(nameof(senseRegion), $"The sense region must be one of {regionCount} regions.");
+ }
+
+ _senseSlots = Math.Max(1, (int)Math.Round(senses.ConductionDelaySeconds / tickSeconds));
+ _senseRing = new double[ChannelCount * _senseSlots];
+ Array.Fill(_senseSens, 1.0);
+ }
+ else
+ {
+ _senseRing = Array.Empty();
+ }
+ }
+
+ 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];
+
+ /// The sensory signals combined: 1 - the product over channels of (1 - afferent, capped at 1), the afferents being the gated ones (see ). Zero with no senses or no emitters.
+ public double Load { get; private set; }
+
+ /// The largest intensity of the channel's emitters at the sense region's point this tick.
+ public double ChannelStimulus(Channel channel) => _senseStimulus[(int)channel];
+
+ ///
+ /// The channel's afferent arriving this tick, after threshold, sensitisation and conduction delay, times the sensory gain
+ /// was given (lodur:ruling:stress-bar-shows-arousal-calm-silences). stays the world's.
+ ///
+ public double ChannelAfferent(Channel channel) => _senseAfferent[(int)channel];
+
+ ///
+ /// Senses once per physics step. The spans are the caller's, one point per region. The sensory gain (default 1, the identity) multiplies the sense
+ /// channels' afferents as they leave the conduction delay, so a change of gain reaches on the next call it is passed to; the nociceptive region
+ /// afferents are never gated. A gain outside [0, 1] (NaN and infinity included) is refused.
+ ///
+ public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources,
+ ReadOnlySpan emitters = default, double sensoryGain = 1.0)
+ {
+ if (x.Length != _regions || y.Length != _regions || z.Length != _regions)
+ {
+ throw new ArgumentException($"x, y and z need {_regions} entries, one per region.");
+ }
+
+ if (!(sensoryGain >= 0.0 && sensoryGain <= 1.0))
+ {
+ throw new ArgumentException("The sensory gain must be in [0, 1].", nameof(sensoryGain));
+ }
+
+ if (_senses != null)
+ {
+ // Refused before any state steps, so a bad emitter leaves the tick unrun.
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ if ((uint)emitters[i].Channel >= ChannelCount)
+ {
+ throw new ArgumentException($"Emitter {i} has channel {(int)emitters[i].Channel}; the channels are Audio, Visual and Interrupt.", nameof(emitters));
+ }
+ }
+ }
+
+ 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.Threshold);
+ 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;
+ }
+
+ if (_senses != null)
+ {
+ SenseEmitters(x[_senseRegion], y[_senseRegion], z[_senseRegion], emitters, sensoryGain);
+ }
+
+ _tick++;
+ }
+
+ private void SenseEmitters(float x, float y, float z, ReadOnlySpan emitters, double gain)
+ {
+ var senses = _senses!;
+ var slot = (int)(_tick % _senseSlots);
+ Array.Clear(_senseStimulus, 0, ChannelCount);
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ var c = (int)emitters[i].Channel;
+ var received = emitters[i].Received(x, y, z);
+ if (received > _senseStimulus[c])
+ {
+ _senseStimulus[c] = received;
+ }
+ }
+
+ var quiet = 1.0;
+ for (var c = 0; c < ChannelCount; c++)
+ {
+ var above = Math.Max(0.0, _senseStimulus[c] - senses.Threshold);
+ var sens = _senseSens[c] + _dt * (senses.SensitisationGrowth * above - senses.SensitisationRecovery * (_senseSens[c] - 1.0));
+ sens = Math.Min(Math.Max(sens, 1.0), senses.SensitisationCap);
+ _senseSens[c] = sens;
+ var ring = c * _senseSlots + slot;
+ // Written one conduction delay ago; the gate sits after the ring, so sensitisation still follows the world.
+ _senseAfferent[c] = _senseRing[ring] * gain;
+ _senseRing[ring] = above * sens * senses.Gain;
+ quiet *= 1.0 - Math.Min(1.0, _senseAfferent[c]);
+ }
+
+ Load = 1.0 - quiet;
+ }
+ }
+}
diff --git a/src/Lodur.Core/PoseBehaviour.cs b/src/Lodur.Core/PoseBehaviour.cs
new file mode 100644
index 0000000..67f2135
--- /dev/null
+++ b/src/Lodur.Core/PoseBehaviour.cs
@@ -0,0 +1,164 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// The pose behaviour'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 its base toward the flinch pose, 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;
+ }
+
+ ///
+ /// The one behaviour a goal can have: a pose held, or a loop through pose keys, with the reflex leak and a
+ /// strain-scaled shake blending the base pose toward the flinch pose. One key is held as it is; k keys are
+ /// walked in a loop, from each to the next and the last back to the first.
+ /// It writes per-muscle strength and target rotation into the caller's spans and nothing else (invariant
+ /// body-one-interface). The poses are the consumer's data, one rotation per muscle. A release is the same
+ /// behaviour with a key and a flinch pose equal and the gains zero.
+ ///
+ public sealed record PoseBehaviour
+ {
+ private Quat[][] _keys = Array.Empty();
+ private Quat[] _flinch = Array.Empty();
+ private IReadOnlyList> _keysView = Array.AsReadOnly(Array.Empty>());
+ private IReadOnlyList _flinchView = Array.AsReadOnly(Array.Empty());
+
+ /// k keys of one rotation per muscle each. Copied when set; read back as a read-only view.
+ public IReadOnlyList> Keys
+ {
+ get => _keysView;
+ init
+ {
+ var copy = new Quat[value.Count][];
+ var views = new IReadOnlyList[copy.Length];
+ for (var k = 0; k < copy.Length; k++)
+ {
+ copy[k] = new Quat[value[k].Count];
+ for (var m = 0; m < copy[k].Length; m++)
+ {
+ copy[k][m] = value[k][m];
+ }
+
+ views[k] = Array.AsReadOnly(copy[k]);
+ }
+
+ _keys = copy;
+ _keysView = Array.AsReadOnly(views);
+ }
+ }
+
+ /// Seconds from one key to the next when there is more than one key.
+ public double SecondsPerKey { get; init; } = 1.0;
+
+ /// The pose the leak and the shake pull toward, one rotation per muscle. Copied when set; read back as a read-only view.
+ public IReadOnlyList FlinchPose
+ {
+ get => _flinchView;
+ init
+ {
+ _flinch = new Quat[value.Count];
+ for (var m = 0; m < _flinch.Length; m++)
+ {
+ _flinch[m] = value[m];
+ }
+
+ _flinchView = Array.AsReadOnly(_flinch);
+ }
+ }
+
+ public HoldParameters Hold { get; init; } = new HoldParameters();
+
+ public int MuscleCount => _keys.Length == 0 ? 0 : _keys[0].Length;
+
+ internal void Validate(string goal)
+ {
+ if (_keys.Length == 0 || _keys[0].Length == 0)
+ {
+ throw new ArgumentException($"Goal {goal}: a pose behaviour needs at least one key of at least one muscle.");
+ }
+
+ foreach (var key in _keys)
+ {
+ if (key.Length != _keys[0].Length)
+ {
+ throw new ArgumentException($"Goal {goal}: every key needs one rotation per muscle.");
+ }
+ }
+
+ if (_flinch.Length != _keys[0].Length)
+ {
+ throw new ArgumentException($"Goal {goal}: the flinch pose needs one rotation per muscle.");
+ }
+
+ if (_keys.Length > 1 && !(SecondsPerKey > 0.0 && double.IsFinite(SecondsPerKey)))
+ {
+ throw new ArgumentException($"Goal {goal}: SecondsPerKey must be positive and finite.");
+ }
+ }
+
+ /// The blend toward the flinch pose: the leak and the shake, clamped to [0, 1]. is the Actor's absolute time.
+ public double Blend(double leak, double strain, double seconds)
+ {
+ var w = leak * Hold.FlinchGain + Hold.StrainShake * strain * Math.Sin(2.0 * Math.PI * Hold.ShakeHz * seconds);
+ return Math.Min(Math.Max(w, 0.0), 1.0);
+ }
+
+ ///
+ /// 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)
+ {
+ 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;
+ var phase = 0f;
+ if (k > 1)
+ {
+ var p = secondsInGoal / SecondsPerKey;
+ var whole = Math.Floor(p);
+ from = (int)(whole % k);
+ to = (from + 1) % k;
+ phase = (float)(p - whole);
+ }
+
+ for (var m = 0; m < count; m++)
+ {
+ var a = _keys[from][m];
+ if (phase > 0f)
+ {
+ a = Quat.Nlerp(_keys[from][m], _keys[to][m], phase);
+ }
+
+ strengths[m] = strength;
+ targets[m] = Quat.Nlerp(a, _flinch[m], w);
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/WithdrawalReflex.cs b/src/Lodur.Core/WithdrawalReflex.cs
new file mode 100644
index 0000000..f20c113
--- /dev/null
+++ b/src/Lodur.Core/WithdrawalReflex.cs
@@ -0,0 +1,54 @@
+using System;
+
+namespace Lodur
+{
+ /// The withdrawal reflex's tunables.
+ 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;
+ }
+
+ ///
+ /// 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 = _p.MaxSuppression * drive.Will;
+ Leak = afferent * (1.0 - suppression);
+ StrainLoad = afferent * suppression;
+ var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory;
+ if (flinch)
+ {
+ _lastFlinch = _tick;
+ }
+
+ _tick++;
+ return flinch;
+ }
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ActorTests.cs b/tests/Lodur.Core.Tests/ActorTests.cs
new file mode 100644
index 0000000..2223437
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ActorTests.cs
@@ -0,0 +1,189 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class ActorTests
+{
+ [Fact]
+ public void Parity_seed_1_breaks_at_14730_ms_switches_goal_at_14830_ms_with_16_flinches()
+ {
+ var (broke, withdrew, flinches) = new PainBoxReplay(1).Run(120.0);
+ Assert.Equal(1473, broke);
+ Assert.Equal(1483, withdrew);
+ Assert.Equal(16, flinches);
+ }
+
+ [Fact]
+ public void Reflex_gain_is_set_ahead_of_time_suppression_uses_the_previous_resolve()
+ {
+ // Drain hard so resolve moves a lot on every tick; then the previous and the current resolve differ visibly.
+ var drive = new DriveParameters { ResolveDrainPain = 8.0, ResolveDrainStrain = 8.0 };
+ var w = new WithdrawalParameters();
+ var r = new PainBoxReplay(1, drive: drive);
+ var checkedTicks = 0;
+ while (r.Actor.TickCount < 3000 && !r.Actor.Drive.WillBroken)
+ {
+ var before = r.Actor.Drive;
+ r.Tick();
+ var after = r.Actor.Drive;
+ var afferent = r.Actor.Afferent(0);
+ if (before.Resolve < 0.9 && afferent > 0.2 && before.Resolve - after.Resolve > 1e-4 && !after.WillBroken)
+ {
+ var load = afferent * (w.MaxSuppression * before.Resolve);
+ var viaPrevious = before.Strain + PainBoxReplay.Dt * (load - 0.1 * before.Strain);
+ var viaCurrent = before.Strain + PainBoxReplay.Dt * (afferent * (w.MaxSuppression * after.Resolve) - 0.1 * before.Strain);
+ Assert.Equal(viaPrevious, after.Strain, 12);
+ Assert.True(Math.Abs(viaCurrent - after.Strain) > 1e-7);
+ checkedTicks++;
+ }
+ }
+ Assert.True(checkedTicks > 10);
+ }
+
+ [Fact]
+ public void Suppression_is_never_free_pain_is_identical_and_only_the_suppressed_run_accumulates_strain()
+ {
+ var held = new PainBoxReplay(2);
+ var free = new PainBoxReplay(2, withdrawal: new WithdrawalParameters { MaxSuppression = 0.0 });
+ for (var i = 0; i < 1000; i++)
+ {
+ held.Tick();
+ free.Tick();
+ Assert.Equal(free.Actor.Drive.Pain, held.Actor.Drive.Pain);
+ Assert.Equal(0.0, free.Actor.Drive.Strain);
+ }
+ Assert.True(held.Actor.Drive.Strain > 0.5);
+ Assert.True(held.Actor.Drive.Pain > 0.1);
+ }
+
+ [Fact]
+ public void A_broken_will_releases_suppression_and_the_deliberate_goal_switch_follows_its_latency()
+ {
+ var r = new PainBoxReplay(1);
+ long broke = -1, withdrew = -1;
+ var strain = 0.0;
+ for (long i = 0; i < 1600; i++)
+ {
+ var e = r.Tick();
+ if (broke >= 0)
+ {
+ // Nothing is held down any more: strain only decays, and a broken will stays broken.
+ Assert.True(r.Actor.Drive.WillBroken);
+ Assert.True(r.Actor.Drive.Strain < strain);
+ }
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ Assert.Equal(withdrew >= 0 ? 1 : 0, r.Actor.GoalIndex); // 0 until GoalChanged, 1 from it
+ strain = r.Actor.Drive.Strain;
+ if (withdrew >= 0) break;
+ }
+ Assert.Equal(broke + 10, withdrew); // round(0.1 s / 10 ms)
+ // From GoalChanged the behaviour is the release behaviour's: the withdraw pose whatever the leak.
+ Assert.Equal(PainBoxReplay.Withdraw[0].X, r.Targets[0].X, 5);
+ Assert.Equal(PainBoxReplay.Withdraw[1].Z, r.Targets[1].Z, 5);
+ Assert.Equal(PainBoxReplay.Withdraw[0].W, r.Targets[0].W, 5);
+ }
+
+ [Fact]
+ public void Resolve_recovers_when_the_box_goes_quiet_and_not_when_recovery_is_off()
+ {
+ static double Resolve(double recovery)
+ {
+ var r = new PainBoxReplay(1, drive: new DriveParameters { ResolveRecovery = recovery });
+ for (var i = 0; i < 400; i++) r.Tick(); // 4 s in the box: resolve is down a little, will intact
+ var low = r.Actor.Drive.Resolve;
+ Assert.InRange(low, 0.85, 0.97);
+ for (var i = 0; i < 20000; i++) r.Tick(boxOn: false); // 200 s quiet: pain falls under the recovery line
+ Assert.False(r.Actor.Drive.WillBroken);
+ return r.Actor.Drive.Resolve - low;
+ }
+ Assert.True(Resolve(0.02) > 0.04); // recovers what it lost
+ Assert.True(Resolve(0.0) <= 0.0); // with recovery off it never rises (lingering pain still drains it)
+ }
+
+ [Fact]
+ public void A_flinch_is_a_suppressed_reflex_leaking_so_none_is_reported_after_the_will_breaks()
+ {
+ // Across seeds, some runs have a leak over the threshold, outside the refractory window, in the ticks
+ // between WillBroke and Withdrew (BDS counts none there). The golden table pins the totals; this pins the rule.
+ var sawLeakAfterBreak = 0;
+ for (ulong seed = 1; seed <= 60; seed++)
+ {
+ var r = new PainBoxReplay(seed);
+ var broke = false;
+ for (var i = 0; i < 4000; i++)
+ {
+ var e = r.Tick();
+ if (broke) Assert.Equal(0, (int)(e & TickEvents.Flinch));
+ broke |= (e & TickEvents.WillBroke) != 0;
+ if ((e & TickEvents.GoalChanged) != 0) break;
+ }
+ sawLeakAfterBreak += broke ? 1 : 0;
+ }
+ Assert.Equal(60, sawLeakAfterBreak);
+ }
+
+ private static long BreakTick(double intensity, double pull)
+ {
+ var (broke, _, _) = new PainBoxReplay(1, intensity, pull).Run(3000.0);
+ return broke;
+ }
+
+ [Fact]
+ public void Break_time_is_ordered_by_intensity_and_by_pull_and_no_stimulus_never_breaks()
+ {
+ long a = BreakTick(1.0, 0.5), b = BreakTick(0.8, 0.5), c = BreakTick(0.6, 0.5);
+ Assert.True(a > 0 && a < b && b < c, $"intensity: {a} {b} {c}");
+
+ long p0 = BreakTick(0.8, 0.0), p5 = BreakTick(0.8, 0.5), p8 = BreakTick(0.8, 0.8);
+ Assert.True(p0 > 0 && p0 < p5 && p5 < p8, $"pull: {p0} {p5} {p8}");
+
+ var quiet = new PainBoxReplay(1, intensity: 0.0);
+ for (var i = 0; i < 60000; i++) Assert.Equal(TickEvents.None, quiet.Tick());
+ Assert.Equal(0.0, quiet.Actor.Drive.Pain);
+ Assert.Equal(0.0, quiet.Actor.Drive.Strain);
+ Assert.Equal(1.0, quiet.Actor.Drive.Resolve);
+ Assert.False(quiet.Actor.Drive.WillBroken);
+ }
+
+ [Fact]
+ public void Tick_allocates_nothing_in_steady_state()
+ {
+ var r = new PainBoxReplay(1);
+ r.Tick(); // warm
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) r.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ }
+
+ [Fact]
+ public void Two_actors_ticked_interleaved_equal_the_same_actors_ticked_alone()
+ {
+ const int n = 2500;
+ var a1 = new PainBoxReplay(1);
+ var b1 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
+ var a2 = new PainBoxReplay(1);
+ var b2 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+
+ static void Same(PainBoxReplay x, PainBoxReplay y)
+ {
+ Assert.Equal(x.Actor.Drive.Pain, y.Actor.Drive.Pain);
+ Assert.Equal(x.Actor.Drive.Strain, y.Actor.Drive.Strain);
+ Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
+ Assert.Equal(x.Actor.Drive.WillBroken, y.Actor.Drive.WillBroken);
+ Assert.Equal(x.Actor.Afferent(0), y.Actor.Afferent(0));
+ Assert.Equal(x.Actor.Stimulus(0), y.Actor.Stimulus(0));
+ Assert.Equal(x.Actor.GoalIndex, y.Actor.GoalIndex);
+ Assert.Equal(x.Actor.TickCount, y.Actor.TickCount);
+ Assert.Equal(x.Strengths, y.Strengths);
+ Assert.Equal(x.Targets, y.Targets);
+ }
+ Same(a1, a2);
+ Same(b1, b2);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ArousalTests.cs b/tests/Lodur.Core.Tests/ArousalTests.cs
new file mode 100644
index 0000000..16ee754
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ArousalTests.cs
@@ -0,0 +1,204 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// An Actor with one region at the origin, a sensory nerve with sensitisation off, and a settable emitter list.
+internal sealed class SensoryRig
+{
+ public const double Dt = 0.01;
+
+ public readonly Actor Actor;
+ public readonly Emitter[] Emitters;
+ public readonly float[] Strengths = new float[2];
+ public readonly Quat[] Targets = new Quat[2];
+ private readonly float[] _p = { 0f };
+
+ /// False builds the Actor without senses, so the emitters have no one to reach.
+ public SensoryRig(Emitter[] emitters, double pull = 0.5, double drainTrait = 1.0, DriveParameters? drive = null, bool heard = true, Brain? brain = null)
+ {
+ Emitters = emitters;
+ Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(),
+ (drive ?? new DriveParameters()) with { DrainTrait = drainTrait }, brain ?? PainBoxBrain.Make(pull),
+ heard ? new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 } : null, 0);
+ }
+
+ /// One audio emitter on the sense region whose afferent settles at (intensity - 0.05).
+ public static Emitter[] One(double intensity) => new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, intensity) };
+
+ public TickEvents Tick() => Actor.Tick(_p, _p, _p, ReadOnlySpan.Empty, Strengths, Targets, Emitters);
+
+ public long TicksToBreak(double maxSeconds)
+ {
+ var max = (long)Math.Round(maxSeconds / Dt);
+ for (long i = 0; i < max; i++)
+ {
+ if ((Tick() & TickEvents.WillBroke) != 0) return i;
+ }
+
+ return -1;
+ }
+}
+
+public sealed class ArousalTests
+{
+ private const double Load = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
+
+ [Fact]
+ public void Arousal_rises_under_constant_load_toward_its_equilibrium_and_decays_at_the_decay_rate_after_it_stops()
+ {
+ var p = new DriveParameters();
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 1.0); // pull 1: no drain, so only arousal is watched
+ double last = 0;
+ for (var i = 0; i < 20000; i++)
+ {
+ rig.Tick();
+ Assert.True(rig.Actor.Drive.Arousal >= last - 1e-15, "arousal never falls under constant load");
+ last = rig.Actor.Drive.Arousal;
+ }
+
+ Assert.Equal(Load, rig.Actor.Load, 12);
+ var equilibrium = p.ArousalRise * Load / (p.ArousalRise * Load + p.ArousalDecay);
+ Assert.Equal(equilibrium, rig.Actor.Drive.Arousal, 9);
+
+ rig.Emitters[0].Intensity = 0.0;
+ while (rig.Actor.Load > 0.0) rig.Tick(); // the last of the signal in flight arrives
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(a0 > 0.5 * equilibrium);
+ for (var i = 0; i < 1000; i++) rig.Tick();
+ Assert.Equal(a0 * Math.Pow(1.0 - SensoryRig.Dt * p.ArousalDecay, 1000), rig.Actor.Drive.Arousal, 12);
+ }
+
+ [Fact]
+ public void Under_the_same_load_a_weaker_pull_breaks_first_pull_one_never_drains_and_the_trait_scales_the_drain()
+ {
+ long Break(double pull, double trait = 1.0) => new SensoryRig(SensoryRig.One(0.55), pull, trait).TicksToBreak(3000.0);
+
+ long p3 = Break(0.3), p6 = Break(0.6);
+ Assert.True(p3 > 0 && p3 < p6, $"pull: {p3} {p6}");
+
+ var held = new SensoryRig(SensoryRig.One(0.55), pull: 1.0);
+ Assert.Equal(-1, held.TicksToBreak(3000.0));
+ Assert.Equal(1.0, held.Actor.Drive.Resolve);
+
+ long t2 = Break(0.6, 2.0);
+ Assert.True(t2 > 0 && t2 < p6, $"trait: {t2} {p6}");
+ Assert.InRange((double)t2 / p6, 0.35, 0.6); // double the drain, about half the time (arousal needs a moment to rise)
+ }
+
+ [Fact]
+ public void Resolve_does_not_recover_while_arousal_is_at_the_recovery_ceiling_or_above_and_does_after()
+ {
+ var drive = new DriveParameters { ResolveRecovery = 0.5 }; // strong enough that a gate on pain alone would show at once
+ var ceiling = drive.ResolveRecoversBelowArousal;
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5, drive: drive);
+ double minResolve = 1.0;
+ for (var i = 0; i < 2000; i++) { rig.Tick(); minResolve = Math.Min(minResolve, rig.Actor.Drive.Resolve); }
+ Assert.True(minResolve < 0.95 && !rig.Actor.Drive.WillBroken);
+
+ rig.Emitters[0].Intensity = 0.0;
+ var rosePastCeiling = false;
+ var settled = false;
+ var last = rig.Actor.Drive.Resolve;
+ for (var i = 0; i < 20000; i++)
+ {
+ rig.Tick();
+ var a = rig.Actor.Drive.Arousal;
+ var r = rig.Actor.Drive.Resolve;
+ if (a >= ceiling)
+ {
+ Assert.True(r <= last, $"resolve rose at arousal {a}");
+ settled = true;
+ }
+ else if (settled && r > last)
+ {
+ rosePastCeiling = true;
+ }
+
+ last = r;
+ }
+
+ Assert.True(settled && rosePastCeiling, "resolve recovers once arousal is below the ceiling");
+ Assert.True(rig.Actor.Drive.Resolve > minResolve);
+ }
+
+ [Fact]
+ public void Arousal_updates_before_it_drains_resolve_on_the_same_tick()
+ {
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5);
+ for (var i = 0; i < 100; i++)
+ {
+ rig.Tick();
+ if (rig.Actor.Load > 0.0) break;
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(1.0, rig.Actor.Drive.Resolve);
+ }
+
+ Assert.True(rig.Actor.Load > 0.0, "the load arrives within the conduction delay");
+ // On the tick the load first arrives, arousal has already risen and already drained: read a tick late, resolve would still be 1.
+ Assert.True(rig.Actor.Drive.Arousal > 0.0);
+ Assert.True(rig.Actor.Drive.Resolve < 1.0);
+ }
+
+ [Fact]
+ public void Without_emitters_or_without_senses_arousal_and_load_stay_exactly_zero()
+ {
+ var silent = new SensoryRig(Array.Empty());
+ var deaf = new SensoryRig(SensoryRig.One(1.0), heard: false);
+ for (var i = 0; i < 10000; i++)
+ {
+ Assert.Equal(TickEvents.None, silent.Tick());
+ Assert.Equal(TickEvents.None, deaf.Tick());
+ Assert.Equal(0.0, silent.Actor.Drive.Arousal);
+ Assert.Equal(0.0, deaf.Actor.Drive.Arousal);
+ Assert.Equal(0.0, silent.Actor.Load);
+ Assert.Equal(0.0, deaf.Actor.Load);
+ }
+
+ Assert.Equal(1.0, silent.Actor.Drive.Resolve);
+ Assert.Equal(1.0, deaf.Actor.Drive.Resolve);
+ }
+
+ private static Emitter[] Three() => new[]
+ {
+ new Emitter(Channel.Audio, 0.2f, 0f, 0f, 1f, 0.5),
+ new Emitter(Channel.Visual, 0f, 0.3f, 0f, 1f, 0.4),
+ new Emitter(Channel.Interrupt, 0f, 0f, 0f, 1f, 0.6),
+ };
+
+ [Fact]
+ public void Tick_with_three_emitters_allocates_nothing_in_steady_state_and_actors_do_not_share_state()
+ {
+ var r = new SensoryRig(Three());
+ r.Tick();
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) r.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+
+ const int n = 2500;
+ var a1 = new SensoryRig(Three());
+ var b1 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
+ var a2 = new SensoryRig(Three());
+ var b2 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+
+ static void Same(SensoryRig x, SensoryRig y)
+ {
+ Assert.Equal(x.Actor.Drive.Arousal, y.Actor.Drive.Arousal);
+ Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
+ Assert.Equal(x.Actor.Load, y.Actor.Load);
+ foreach (var c in new[] { Channel.Audio, Channel.Visual, Channel.Interrupt })
+ {
+ Assert.Equal(x.Actor.ChannelStimulus(c), y.Actor.ChannelStimulus(c));
+ Assert.Equal(x.Actor.ChannelAfferent(c), y.Actor.ChannelAfferent(c));
+ }
+ }
+
+ Same(a1, a2);
+ Same(b1, b2);
+ Assert.True(a1.Actor.Drive.Arousal > 0.0);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/BrainTests.cs b/tests/Lodur.Core.Tests/BrainTests.cs
new file mode 100644
index 0000000..84a9a29
--- /dev/null
+++ b/tests/Lodur.Core.Tests/BrainTests.cs
@@ -0,0 +1,634 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class BrainTests
+{
+ private const long Latency = 10; // round(0.1 s / 10 ms)
+
+ private static GoalSpec Goal(string id, double priority, double pull = 0.5, params Condition[] when) => new()
+ {
+ Id = id, Priority = priority, Pull = pull, When = when,
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ };
+
+ 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);
+
+ /// Ticks the pain box; reports the GoalChanged ticks and goals, the WillBroke tick, and per probe the first tick its predicate held after the tick.
+ private static Run Go(PainBoxReplay r, long ticks, params Func[] probes)
+ {
+ var run = new Run(new List(), new List(), -1, Enumerable.Repeat(-1L, probes.Length).ToArray());
+ for (long i = 0; i < ticks; i++)
+ {
+ var e = r.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) { run.Changes.Add(i); run.Goals.Add(r.Actor.GoalIndex); }
+ if ((e & TickEvents.WillBroke) != 0 && run.Broke < 0) run = run with { Broke = i };
+ for (var p = 0; p < probes.Length; p++)
+ {
+ if (run.Held[p] < 0 && probes[p](r.Actor.Drive)) run.Held[p] = i;
+ }
+ }
+ return run;
+ }
+
+ [Fact]
+ public void A_brain_with_no_rule_about_the_will_never_changes_goal_when_the_will_breaks()
+ {
+ var one = new Brain { Goals = new[] { Goal("only", 0.0) } };
+ var r = new PainBoxReplay(1, brain: one);
+ var run = Go(r, 2500);
+ Assert.True(run.Broke > 0, "the will never broke");
+ Assert.Empty(run.Changes);
+ Assert.Equal(0, r.Actor.GoalIndex);
+ }
+
+ [Fact]
+ public void A_release_that_enters_on_pain_switches_long_before_the_will_breaks_exactly_the_latency_after_pain_first_reached_it()
+ {
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("objective", 0.0), Goal("release", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)) },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 2500, d => d.Pain >= 0.6);
+ Assert.True(run.Held[0] > 0);
+ Assert.Equal(new[] { run.Held[0] + Latency }, run.Changes);
+ Assert.Equal(new[] { 1 }, run.Goals);
+ Assert.True(run.Broke > run.Changes[0] + 500, $"will broke at {run.Broke}, the switch was at {run.Changes[0]}");
+ }
+
+ [Fact]
+ public void Of_several_eligible_goals_the_highest_priority_is_taken_ties_stay_put_or_go_to_the_lowest_index()
+ {
+ var calm = default(DriveState); // all zero, will intact
+ Condition Always = Pain(ConditionOp.Below, 1.0);
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 2.0, 0.5, Always), Goal("b", 5.0, 0.5, Always), Goal("c", 5.0, 0.5, Always),
+ 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
+ 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));
+ }
+
+ [Fact]
+ public void A_three_goal_brain_passes_through_the_goals_as_their_conditions_come_true_each_a_latency_after_its_own()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("calm", 0.0),
+ Goal("wary", 3.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
+ Goal("hurt", 5.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)),
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 2500, d => d.Pain >= 0.3, d => d.Pain >= 0.6);
+ Assert.Equal(new[] { 1, 2 }, run.Goals);
+ Assert.Equal(new[] { run.Held[0] + Latency, run.Held[1] + Latency }, run.Changes);
+ }
+
+ [Fact]
+ public void A_revert_brain_switches_back_when_the_arousal_that_chose_the_rage_falls_and_each_switch_fires_once()
+ {
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("calm", 1.0, 1.0), Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5)) },
+ };
+ var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
+ long rose = -1, fell = -1;
+ var changes = new List<(long Tick, int Goal)>();
+ for (long i = 0; i < 20000; i++)
+ {
+ if (i == 6000) rig.Emitters[0].Intensity = 0.0;
+ var e = rig.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
+ if (rose < 0 && rig.Actor.Drive.Arousal >= 0.5) rose = i;
+ if (rose >= 0 && fell < 0 && i >= 6000 && rig.Actor.Drive.Arousal < 0.5) fell = i;
+ }
+ Assert.True(rose > 0 && fell > rose);
+ Assert.Equal(new[] { (rose + Latency, 1), (fell + Latency, 0) }, changes);
+ }
+
+ [Fact]
+ public void Resolve_drain_follows_the_pull_of_the_goal_in_force_slower_after_a_switch_to_a_goal_that_pulls_harder()
+ {
+ Brain Of(double secondPull) => new()
+ {
+ Goals = new[] { Goal("a", 0.0, 0.0), Goal("b", 1.0, secondPull, Pain(ConditionOp.AtLeast, 0.3)) },
+ };
+ var plain = new PainBoxReplay(1, brain: Of(0.0));
+ var pulled = new PainBoxReplay(1, brain: Of(0.9));
+ long switched = -1;
+ double before = 0.0, plainLoss = 0.0, pulledLoss = 0.0;
+ for (long i = 0; i < 1200; i++)
+ {
+ var ea = plain.Tick();
+ var eb = pulled.Tick();
+ if (switched < 0) Assert.Equal(ea, eb);
+ if ((eb & TickEvents.GoalChanged) != 0) { switched = i; before = plain.Actor.Drive.Resolve - pulled.Actor.Drive.Resolve; }
+ if (switched < 0) Assert.Equal(plain.Actor.Drive.Resolve, pulled.Actor.Drive.Resolve); // same pull until the switch
+ if (switched >= 0 && i == switched + 600)
+ {
+ plainLoss = 1.0 - plain.Actor.Drive.Resolve;
+ pulledLoss = 1.0 - pulled.Actor.Drive.Resolve;
+ }
+ }
+ Assert.True(switched > 0);
+ Assert.Equal(0.0, before);
+ Assert.True(pulled.Actor.Drive.Resolve > plain.Actor.Drive.Resolve);
+ Assert.True(pulledLoss < 0.25 * plainLoss, $"pull 0.9 lost {pulledLoss}, pull 0 lost {plainLoss}");
+ }
+
+ [Fact]
+ public void A_decision_in_flight_commits_at_its_tick_even_if_its_condition_has_lapsed()
+ {
+ // The band is a tick or two wide while pain rises through it; the latency is ten.
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long inBand = -1, lapsed = -1;
+ var changes = new List<(long Tick, int Goal)>();
+ for (long i = 0; i < 600; i++)
+ {
+ var e = r.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, r.Actor.GoalIndex));
+ var p = r.Actor.Drive.Pain;
+ if (inBand < 0 && p >= 0.3) inBand = i;
+ if (inBand >= 0 && lapsed < 0 && p >= 0.305) lapsed = i;
+ }
+ Assert.True(inBand > 0 && lapsed > inBand && lapsed < inBand + Latency, $"band {inBand}..{lapsed}");
+ Assert.Equal(new[] { (inBand + Latency, 1), (inBand + Latency + 1 + Latency, 0) }, changes); // committed, then the lapse is acted on once
+ }
+
+ [Fact]
+ public void While_a_decision_is_in_flight_no_second_one_is_made_the_later_goal_waits_for_the_first_to_commit()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)), Goal("c", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.31)),
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 600, d => d.Pain >= 0.3, d => d.Pain >= 0.31);
+ Assert.True(run.Held[1] > run.Held[0] && run.Held[1] < run.Held[0] + Latency, $"{run.Held[0]} {run.Held[1]}");
+ Assert.Equal(new[] { 1, 2 }, run.Goals);
+ Assert.Equal(new[] { run.Held[0] + Latency, run.Held[0] + Latency + 1 + Latency }, run.Changes);
+ }
+
+ [Fact]
+ public void The_brain_is_checked_when_the_actor_is_built()
+ {
+ Actor Build(Brain b) => new(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), b);
+ var g = Goal("g", 0.0);
+ Assert.Throws(() => Build(new Brain()));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g }, Start = 1 }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g }, DeliberateLatencySeconds = double.NaN }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g with { Pull = 1.5 } } }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g with { When = new[] { Pain(ConditionOp.AtLeast, double.NaN) } } } }));
+ Assert.Throws(() => Build(new Brain
+ {
+ Goals = new[] { g, g with { Behaviour = g.Behaviour with { Keys = new[] { new[] { Quat.Identity } }, FlinchPose = new[] { Quat.Identity } } } },
+ }));
+ Assert.Equal(1, Build(new Brain { Goals = new[] { g, g }, Start = 1 }).GoalIndex);
+ }
+
+ [Fact]
+ public void A_goal_in_force_writes_its_behaviour_and_seconds_in_goal_count_from_the_tick_it_took_over()
+ {
+ var spin = new[]
+ {
+ new[] { Quat.Identity, Quat.Identity },
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.8f), Quat.Identity },
+ };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0),
+ Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour
+ {
+ Keys = spin, SecondsPerKey = 0.2, FlinchPose = spin[0],
+ Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
+ },
+ },
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long changed = -1;
+ for (long i = 0; i < 600 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ }
+ Assert.True(changed > 0);
+ Assert.Equal(0.01, r.Actor.SecondsInGoal, 12); // the next tick sees one tick in the goal
+ for (var k = 0; k < 10; k++) r.Tick();
+ Assert.Equal(0.11, r.Actor.SecondsInGoal, 9);
+ Assert.NotEqual(0f, r.Targets[0].Z); // partway from key 0 to key 1: the loop is walking
+ }
+
+ [Fact]
+ public void Tick_with_a_three_goal_brain_and_a_four_key_behaviour_allocates_nothing_and_interleaved_actors_equal_each_alone()
+ {
+ Brain Make()
+ {
+ var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
+ return new Brain
+ {
+ Goals = new[]
+ {
+ Goal("calm", 0.0),
+ Goal("wary", 1.0, 0.4, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ Goal("hurt", 2.0, 0.8, Pain(ConditionOp.AtLeast, 0.6)),
+ },
+ };
+ }
+
+ var solo = new PainBoxReplay(1, brain: Make());
+ for (var i = 0; i < 300; i++) solo.Tick(); // warm, and through the first switches
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) solo.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+
+ const int n = 2500;
+ var a1 = new PainBoxReplay(1, brain: Make());
+ var b1 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
+ var a2 = new PainBoxReplay(1, brain: Make());
+ var b2 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+ Assert.Equal(a1.Actor.GoalIndex, a2.Actor.GoalIndex);
+ Assert.Equal(b1.Actor.GoalIndex, b2.Actor.GoalIndex);
+ Assert.Equal(a1.Targets, a2.Targets);
+ Assert.Equal(b1.Targets, b2.Targets);
+ Assert.Contains(ea, e => (e & TickEvents.GoalChanged) != 0);
+ }
+
+ private static double Read(DriveState d, DriveQuantity q) => q switch
+ {
+ DriveQuantity.Pain => d.Pain,
+ DriveQuantity.Strain => d.Strain,
+ DriveQuantity.Arousal => d.Arousal,
+ DriveQuantity.Resolve => d.Resolve,
+ DriveQuantity.Breaks => d.Breaks,
+ _ => d.WillBroken ? 1.0 : 0.0,
+ };
+
+ private static Brain Gated(Condition when, double dwell = 0.0, double pull = 0.5) => new()
+ {
+ Goals = new[] { Goal("calm", 0.0, pull), Goal("gated", 1.0, pull, when) with { MinDwellSeconds = dwell } },
+ };
+
+ ///
+ /// Runs a rig whose Brain has one goal gated on the condition; the switch must land the latency after the tick the
+ /// quantity itself first crossed, and no other quantity read the same way may cross on that tick (or the scenario
+ /// could not tell a misread from the right read).
+ ///
+ private static void GateFollowsOnly(Func Tick, Func Drive)> rig, DriveQuantity q, ConditionOp op, double threshold, long ticks, DriveQuantity? sameTickOk = null)
+ {
+ var (tick, drive) = rig(Gated(new Condition(q, op, threshold)));
+ bool Crossed(DriveState d, DriveQuantity of) => op == ConditionOp.AtLeast ? Read(d, of) >= threshold : Read(d, of) < threshold;
+ var firstOf = new Dictionary();
+ long changed = -1;
+ for (long i = 0; i < ticks; i++)
+ {
+ var e = tick();
+ if ((e & TickEvents.GoalChanged) != 0 && changed < 0) changed = i;
+ foreach (var of in Enum.GetValues())
+ {
+ if (!firstOf.ContainsKey(of) && Crossed(drive(), of)) firstOf[of] = i;
+ }
+ }
+ Assert.True(firstOf.TryGetValue(q, out var own), $"{q} never crossed {threshold}");
+ Assert.Equal(own + Latency, changed);
+ foreach (var of in Enum.GetValues())
+ {
+ if (of != q && of != sameTickOk) Assert.False(firstOf.TryGetValue(of, out var other) && other == own, $"{of} crosses on the same tick as {q}: the scenario cannot tell them apart");
+ }
+ }
+
+ private static (Func, Func) PainRig(Brain b) { var r = new PainBoxReplay(1, brain: b); return (() => r.Tick(), () => r.Actor.Drive); }
+
+ private static (Func, Func) SenseRig(Brain b)
+ {
+ var r = new SensoryRig(SensoryRig.One(0.55), brain: b);
+ return (() => r.Tick(), () => r.Actor.Drive);
+ }
+
+ [Theory]
+ [InlineData(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)]
+ [InlineData(DriveQuantity.Strain, ConditionOp.AtLeast, 1.0)]
+ [InlineData(DriveQuantity.Resolve, ConditionOp.Below, 0.9)]
+ [InlineData(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0)]
+ public void Each_drive_quantity_a_condition_reads_is_that_quantity_in_the_pain_box(DriveQuantity q, ConditionOp op, double threshold) =>
+ // The first break moves Breaks and WillBroken on one tick; WillTests reads Breaks at its second break, where they part.
+ GateFollowsOnly(PainRig, q, op, threshold, 1700, DriveQuantity.Breaks);
+
+ [Fact]
+ public void Arousal_a_condition_reads_is_arousal_where_pain_strain_and_resolve_do_not_move_with_it()
+ {
+ GateFollowsOnly(SenseRig, DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5, 3000);
+ }
+
+ [Fact]
+ public void Below_is_strict_and_at_least_is_inclusive_at_the_threshold()
+ {
+ var zero = default(DriveState); // pain exactly 0
+ Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.0).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.Below, 0.0).Holds(zero));
+ Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.Below, 1e-300).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 1e-300).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 0.0).Holds(zero)); // unbroken reads 0
+ Assert.True(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 1.0).Holds(zero));
+ }
+
+ private static long ChangeTickAfterPain(double latencySeconds)
+ {
+ var brain = Gated(Pain(ConditionOp.AtLeast, 0.3)) with { DeliberateLatencySeconds = latencySeconds };
+ var run = Go(new PainBoxReplay(1, brain: brain), 600, d => d.Pain >= 0.3);
+ Assert.Single(run.Changes);
+ return run.Changes[0] - run.Held[0];
+ }
+
+ [Fact]
+ public void The_deliberate_latency_is_rounded_to_ticks_never_less_than_one_and_a_negative_latency_is_refused()
+ {
+ Assert.Equal(1, ChangeTickAfterPain(0.0)); // a switch never lands on the tick it was decided
+ Assert.Equal(1, ChangeTickAfterPain(0.001));
+ Assert.Equal(1, ChangeTickAfterPain(0.014));
+ Assert.Equal(2, ChangeTickAfterPain(0.016));
+ Assert.Equal(10, ChangeTickAfterPain(0.1));
+ var g = Goal("g", 0.0);
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { g }, DeliberateLatencySeconds = -0.01 }));
+ }
+
+ [Fact]
+ public void The_pending_goals_behaviour_is_not_written_during_the_latency_only_from_the_tick_it_takes_over()
+ {
+ var loud = Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.25f } },
+ };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loud } });
+ long decided = -1;
+ var landed = false;
+ for (long i = 0; i < 600 && !landed; i++)
+ {
+ var e = r.Tick();
+ if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
+ if (decided < 0) continue;
+ if (i < decided + Latency)
+ {
+ Assert.Equal(1f, r.Strengths[0]);
+ Assert.Equal((i + 1) * 0.01, r.Actor.SecondsInGoal, 9); // the goal in force keeps its own clock through the decision and the latency
+ Assert.Equal(0, (int)(e & TickEvents.GoalChanged));
+ }
+ else
+ {
+ Assert.Equal(TickEvents.GoalChanged, e & TickEvents.GoalChanged);
+ Assert.Equal(0.25f, r.Strengths[0]);
+ landed = true;
+ }
+ }
+ Assert.True(landed);
+ }
+
+ [Fact]
+ public void A_behaviours_phase_restarts_from_the_time_in_the_goal_not_the_clock()
+ {
+ var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
+ var loop = Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = keys[0], Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 } },
+ };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loop } });
+ long changed = -1;
+ for (long i = 0; i < 600 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ }
+ Assert.True(changed > 0 && changed % 40 != 0, $"changed at {changed}: the loop is 40 ticks, a clock-driven phase would be hidden");
+ Assert.Equal(Quat.Nlerp(keys[0][0], keys[0][0], 0f).Z, r.Targets[0].Z); // key 0 exactly, the tick it takes over
+ for (var k = 0; k < 5; k++) r.Tick();
+ Assert.Equal(Quat.Nlerp(keys[0][0], keys[1][0], 0.5f).Z, r.Targets[0].Z, 5); // half way to key 1 after half a key
+ }
+
+ private static List<(long Tick, int Goal)> Hover(double dwell, double threshold)
+ {
+ var rage = Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, threshold)) with { MinDwellSeconds = dwell };
+ var brain = new Brain { Goals = new[] { Goal("calm", 1.0, 1.0) with { MinDwellSeconds = dwell }, rage } };
+ var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
+ var changes = new List<(long, int)>();
+ for (long i = 0; i < 6000; i++)
+ {
+ rig.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0; // on 1 s, off 1 s: arousal saws around its middle
+ if ((rig.Tick() & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
+ }
+ return changes;
+ }
+
+ [Fact]
+ public void A_condition_hovering_at_its_threshold_chatters_without_a_dwell_and_with_one_the_entered_goal_is_not_left_for_a_lower_one_inside_its_window()
+ {
+ double lo = 1, hi = 0;
+ var probe = new SensoryRig(SensoryRig.One(0.55), brain: new Brain { Goals = new[] { Goal("only", 0.0, 1.0) } });
+ for (long i = 0; i < 6000; i++)
+ {
+ probe.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0;
+ probe.Tick();
+ if (i >= 3000) { lo = Math.Min(lo, probe.Actor.Drive.Arousal); hi = Math.Max(hi, probe.Actor.Drive.Arousal); }
+ }
+ var mid = 0.5 * (lo + hi);
+
+ var free = Hover(0.0, mid);
+ Assert.True(free.Count >= 15, $"{free.Count} changes with no dwell: the scenario does not chatter");
+
+ const double dwell = 3.0;
+ const long dwellTicks = 300;
+ var held = Hover(dwell, mid);
+ Assert.True(held.Count >= 2 && held.Count * 2 <= free.Count, $"{held.Count} changes with a dwell of {dwell} s against {free.Count}");
+ var leaves = 0;
+ for (var i = 1; i < held.Count; i++)
+ {
+ if (held[i].Goal != 0) continue; // only the return trip (rage to the lower calm) is gated by rage's dwell
+ leaves++;
+ Assert.True(held[i].Tick - held[i - 1].Tick >= dwellTicks + Latency, $"rage taken at {held[i - 1].Tick} and left at {held[i].Tick}");
+ }
+ Assert.True(leaves >= 2);
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = -1.0 } } }));
+ foreach (var bad in new[] { double.PositiveInfinity, double.NaN })
+ {
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = bad } } }));
+ }
+ }
+
+ ///
+ /// Goal 1 is the start goal, eligible while pain is below 0.3, with the dwell; goal 0 (no dwell) is the lower-priority
+ /// goal always eligible. Pain passes 0.3 early, so the decision to leave goal 1 is held to its dwell and lands exactly then.
+ ///
+ private static (long Dwell, long Changed, long PainLapsed) LeaveHeldGoal(double dwellSeconds, double priorityOfTarget = 1.0)
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("target", priorityOfTarget, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
+ Goal("held", 2.0, 0.5, Pain(ConditionOp.Below, 0.3)) with { MinDwellSeconds = dwellSeconds },
+ },
+ Start = 1,
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long lapsed = -1, changed = -1;
+ for (long i = 0; i < 800 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ if (lapsed < 0 && r.Actor.Drive.Pain >= 0.3) lapsed = i;
+ }
+ return (0, changed, lapsed);
+ }
+
+ [Fact]
+ public void A_goal_not_outranked_is_left_exactly_a_dwell_after_it_took_over_the_decision_held_on_the_dwells_last_tick()
+ {
+ // 3.0 s is 300 ticks from tick 0 (the start goal is active from there): the decision is taken on tick 300 and lands 10 later.
+ var (_, changed, lapsed) = LeaveHeldGoal(3.0);
+ Assert.True(lapsed > 0 && lapsed < 290, $"pain lapsed the condition on tick {lapsed}");
+ Assert.Equal(300 + Latency, changed);
+ // The dwell is the held goal's own (goal 1), not goal 0's, which has none.
+ var free = LeaveHeldGoal(0.0);
+ Assert.Equal(free.PainLapsed + Latency, free.Changed);
+ }
+
+ [Fact]
+ public void A_dwell_is_rounded_to_the_nearest_tick_as_the_latency_is()
+ {
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.004).Changed); // 300.4 ticks: a ceiling would make it 301
+ Assert.Equal(301 + Latency, LeaveHeldGoal(3.006).Changed); // 300.6 ticks: a floor would make it 300
+ }
+
+ [Fact]
+ public void A_strictly_higher_priority_goal_preempts_during_the_dwell_after_the_latency_and_a_goal_that_ties_or_ranks_below_is_held()
+ {
+ // Same scene, but the goal it would move to outranks the held one: no wait for the dwell.
+ var (_, preempted, lapsed) = LeaveHeldGoal(3.0, priorityOfTarget: 3.0);
+ Assert.Equal(lapsed + Latency, preempted);
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 2.0).Changed); // a tie is not strictly higher
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 1.99).Changed);
+ }
+
+ [Fact]
+ public void The_dwell_of_an_entered_goal_counts_from_the_tick_it_took_over_not_from_the_decision()
+ {
+ // Held goal b is entered on pain at least 0.3 and its condition lapses at once (a band); its dwell of 2 s runs from the takeover.
+ var band = Goal("b", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) with { MinDwellSeconds = 2.0 };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 1.0), band } });
+ long decided = -1, entered = -1, left = -1;
+ for (long i = 0; i < 800 && left < 0; i++)
+ {
+ var e = r.Tick();
+ if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
+ if ((e & TickEvents.GoalChanged) != 0) { if (entered < 0) entered = i; else left = i; }
+ }
+ Assert.Equal(decided + Latency, entered);
+ Assert.Equal(entered + 200 + Latency, left);
+ }
+
+ [Fact]
+ public void A_built_brains_getters_hand_out_read_only_views_and_writing_through_them_changes_nothing()
+ {
+ var keys = new[] { new[] { Quat.Identity, Quat.Identity } };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0),
+ Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+ static void Sealed(IReadOnlyList view, T poison)
+ {
+ Assert.False(view is T[]);
+ if (view is IList list)
+ {
+ Assert.True(list.IsReadOnly);
+ Assert.Throws(() => list[0] = poison);
+ }
+ }
+ Sealed(brain.Goals, Goal("poison", 9.0));
+ Sealed(brain.Goals[1].When, Pain(ConditionOp.AtLeast, double.NaN));
+ Sealed(brain.Goals[1].Behaviour.Keys, (IReadOnlyList)new Quat[1]);
+ Sealed(brain.Goals[1].Behaviour.Keys[0], new Quat(7f, 7f, 7f, 7f));
+ Sealed(brain.Goals[1].Behaviour.FlinchPose, new Quat(7f, 7f, 7f, 7f));
+
+ var a = new PainBoxReplay(1, brain: brain);
+ var b = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with { Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw } } } });
+ for (var i = 0; i < 1000; i++)
+ {
+ Assert.Equal(b.Tick(), a.Tick());
+ Assert.Equal(b.Targets, a.Targets);
+ }
+ }
+
+ [Fact]
+ public void A_validated_brain_does_not_follow_later_changes_to_the_lists_and_arrays_it_was_built_from()
+ {
+ Brain Build(out List goals, out Condition[] when, out Quat[][] keys, out Quat[] flinch)
+ {
+ when = new[] { Pain(ConditionOp.AtLeast, 0.3) };
+ keys = new[] { (Quat[])PainBoxBrain.Hold.Clone() };
+ flinch = (Quat[])PainBoxBrain.Withdraw.Clone();
+ goals = new List
+ {
+ Goal("a", 0.0),
+ Goal("b", 1.0, 0.5) with { When = when, Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = flinch } },
+ };
+ return new Brain { Goals = goals };
+ }
+
+ var brain = Build(out var goals, out var when, out var keys, out var flinch);
+ var twin = Build(out _, out _, out _, out _);
+ goals.Clear();
+ when[0] = Pain(ConditionOp.AtLeast, double.NaN);
+ keys[0][0] = new Quat(9f, 9f, 9f, 9f);
+ keys[0] = new Quat[1];
+ flinch[0] = new Quat(5f, 5f, 5f, 5f);
+
+ var a = new PainBoxReplay(1, brain: brain);
+ var b = new PainBoxReplay(1, brain: twin);
+ for (var i = 0; i < 1500; i++)
+ {
+ Assert.Equal(b.Tick(), a.Tick());
+ Assert.Equal(b.Targets, a.Targets);
+ }
+ Assert.Equal(2, brain.Goals.Count);
+ Assert.Equal(1, a.Actor.GoalIndex);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/CalmSensesTests.cs b/tests/Lodur.Core.Tests/CalmSensesTests.cs
new file mode 100644
index 0000000..9fc359b
--- /dev/null
+++ b/tests/Lodur.Core.Tests/CalmSensesTests.cs
@@ -0,0 +1,202 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// A goal's sensory gain (lodur:ruling:stress-bar-shows-arousal-calm-silences) gates the sense channels' afferents after the conduction delay,
+/// builds Load from the gated values, and never touches the world's stimulus or the nociceptive region afferents.
+///
+public sealed class SensoryGainTests
+{
+ private const double Dt = 0.01;
+ private static readonly float[] Zero = { 0f };
+ private static readonly BoxStimulus[] NoBoxes = System.Array.Empty();
+ private static readonly Emitter[] Loud = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.6), new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.4) };
+
+ private static Perception Senses(NerveParameters senses, double delay = 0.0) =>
+ new Perception(new NerveParameters(), Dt, 1, senses with { ConductionDelaySeconds = delay }, 0);
+
+ [Fact]
+ public void Gain_one_leaves_every_afferent_and_the_load_bit_identical_to_no_gain()
+ {
+ var a = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
+ var b = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
+ for (var i = 0; i < 300; i++)
+ {
+ a.Sense(Zero, Zero, Zero, NoBoxes, Loud);
+ b.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(a.Load, b.Load);
+ Assert.Equal(a.ChannelAfferent(Channel.Audio), b.ChannelAfferent(Channel.Audio));
+ Assert.Equal(a.ChannelAfferent(Channel.Visual), b.ChannelAfferent(Channel.Visual));
+ }
+
+ Assert.True(a.Load > 0.0);
+ }
+
+ [Fact]
+ public void Gain_scales_each_channels_afferent_and_builds_the_load_from_the_scaled_afferents_while_the_stimulus_is_the_worlds()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
+ double audio = (0.6 - 0.05) * 0.5, visual = (0.4 - 0.05) * 0.5;
+ Assert.Equal(audio, p.ChannelAfferent(Channel.Audio), 12);
+ Assert.Equal(visual, p.ChannelAfferent(Channel.Visual), 12);
+ Assert.Equal(1.0 - (1.0 - audio) * (1.0 - visual), p.Load, 12);
+ Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
+
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Visual));
+ Assert.Equal(0.0, p.Load);
+ Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
+ Assert.Equal(0.4, p.ChannelStimulus(Channel.Visual), 12);
+ }
+
+ [Fact]
+ public void The_gain_in_force_when_the_afferent_leaves_the_delay_applies_not_the_gain_when_the_stimulus_entered()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0.05); // 5 ticks in flight
+ for (var i = 0; i < 20; i++) p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.True(p.ChannelAfferent(Channel.Audio) > 0.5);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0); // the same signal, gated as it arrives
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
+ }
+
+ [Fact]
+ public void Sensitisation_follows_the_world_not_the_gain()
+ {
+ var nerve = new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0, SensitisationCap = 4.0 };
+ var deaf = Senses(nerve);
+ var hearing = Senses(nerve);
+ for (var i = 0; i < 200; i++)
+ {
+ deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ }
+
+ deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(hearing.ChannelAfferent(Channel.Audio), deaf.ChannelAfferent(Channel.Audio));
+ Assert.True(deaf.ChannelAfferent(Channel.Audio) > 0.55, "the channel sensitised while it was gated");
+ }
+
+ [Fact]
+ public void Sense_refuses_a_gain_outside_zero_to_one_and_leaves_its_state_alone()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ foreach (var bad in new[] { double.NaN, -0.01, 1.01, double.PositiveInfinity, double.NegativeInfinity })
+ {
+ var ex = Assert.Throws(() => p.Sense(Zero, Zero, Zero, NoBoxes, Loud, bad));
+ Assert.Contains("gain", ex.Message);
+ }
+
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
+ }
+
+ private static Brain GainGoal(double gain, string id = "g") => new()
+ {
+ Goals = new[] { new GoalSpec { Id = id, SensoryGain = gain, Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw } } },
+ };
+
+ [Fact]
+ public void A_goal_with_gain_zero_silences_load_and_channel_afferents_but_not_the_pain_path_or_the_world_stimulus()
+ {
+ var events = new List[2] { new(), new() };
+ var afferent = new List[2] { new(), new() };
+ var flinches = new int[2];
+ var gains = new[] { 1.0, 0.0 };
+ var p = new[] { 0f };
+ for (var k = 0; k < 2; k++)
+ {
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters() with { ResolveDrainPain = 0.0, ResolveDrainStrain = 0.0, ResolveDrainArousal = 0.0 },
+ GainGoal(gains[k]), new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
+ actor.SetWillSlots(0.4, 1.0); // a will that holds only part of the reflex down, so flinches leak
+ Assert.Equal(gains[k], actor.Drive.SensoryGain);
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.8 } };
+ for (var i = 0; i < 600; i++)
+ {
+ var e = actor.Tick(p, p, p, box, strengths, targets, Loud);
+ events[k].Add(e);
+ afferent[k].Add(actor.Afferent(0));
+ if ((e & TickEvents.Flinch) != 0) flinches[k]++;
+ if (i >= 10)
+ {
+ Assert.Equal(0.6, actor.ChannelStimulus(Channel.Audio), 12);
+ if (k == 1)
+ {
+ Assert.Equal(0.0, actor.Load);
+ Assert.Equal(0.0, actor.ChannelAfferent(Channel.Audio));
+ }
+ else
+ {
+ Assert.True(actor.Load > 0.0);
+ }
+ }
+ }
+ }
+
+ Assert.True(flinches[1] > 0, "the fixture flinches");
+ Assert.Equal(events[0], events[1]);
+ Assert.Equal(afferent[0], afferent[1]);
+ }
+
+ [Fact]
+ public void The_start_goals_gain_holds_at_construction_and_a_later_goal_sets_it_the_tick_it_takes_over()
+ {
+ var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
+ var brain = new Brain
+ {
+ Start = 0,
+ Goals = new[]
+ {
+ new GoalSpec { Id = "a", SensoryGain = 0.25, Behaviour = pose },
+ new GoalSpec { Id = "b", Priority = 1.0, SensoryGain = 0.75, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = pose },
+ },
+ };
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain);
+ Assert.Equal(0.25, actor.Drive.SensoryGain);
+ var p = new[] { 0f };
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.9 } };
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ for (var i = 0; i < 2000; i++)
+ {
+ var e = actor.Tick(p, p, p, box, strengths, targets);
+ if ((e & TickEvents.GoalChanged) != 0)
+ {
+ Assert.Equal(1, actor.GoalIndex);
+ Assert.Equal(0.75, actor.Drive.SensoryGain);
+ return;
+ }
+
+ Assert.Equal(0.25, actor.Drive.SensoryGain);
+ }
+
+ Assert.Fail("the second goal never took over");
+ }
+
+ [Fact]
+ public void SensoryGain_outside_zero_to_one_or_not_a_number_is_refused_naming_the_goal()
+ {
+ void Refused(double gain)
+ {
+ var ex = Assert.Throws(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(gain, "bad")));
+ Assert.Contains("bad", ex.Message);
+ }
+
+ Refused(-0.01);
+ Refused(1.01);
+ Refused(double.NaN);
+ Refused(double.PositiveInfinity);
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(0.0));
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(1.0));
+ }
+}
diff --git a/tests/Lodur.Core.Tests/EntryRampTests.cs b/tests/Lodur.Core.Tests/EntryRampTests.cs
new file mode 100644
index 0000000..a5a5d64
--- /dev/null
+++ b/tests/Lodur.Core.Tests/EntryRampTests.cs
@@ -0,0 +1,249 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// The entry ramp (lodur:ruling:flinch-tail-after-stimulus): a goal's arousal and sensory-gain targets are reached linearly over EntrySeconds from
+/// their values at takeover, so the stress bar and the flinch drive tail off rather than cut; after it the drive owns arousal.
+///
+public sealed class EntryRampTests
+{
+ private const double Dt = 0.01;
+ private const double Afferent = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
+ private static readonly PoseBehaviour Pose = new() { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
+
+ /// Stress is the Start goal; calm takes over once arousal reaches 0.2 and holds (its dwell outlasts every test).
+ private static Brain StressThenCalm(double entrySeconds, double gain = 0.0, double? arousal = 0.0) => new()
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "stress", Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = gain, EntryArousal = arousal, EntrySeconds = entrySeconds,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ },
+ };
+
+ private sealed class Rig
+ {
+ public readonly Actor Actor;
+ private readonly Emitter[] _emitters = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.55) };
+ private readonly BoxStimulus[] _box = { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) };
+ private readonly float[] _p = { 0f };
+ private readonly float[] _strengths = new float[2];
+ private readonly Quat[] _targets = new Quat[2];
+
+ public Rig(Brain brain) =>
+ Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
+
+ public double Pain { set => _box[0].Intensity = value; }
+
+ public TickEvents Tick() => Actor.Tick(_p, _p, _p, _box, _strengths, _targets, _emitters);
+
+ /// Ticks until the goal at takes over; the takeover tick has just run.
+ public void UntilTakeover(int goal)
+ {
+ for (var i = 0; i < 20000; i++)
+ {
+ if ((Tick() & TickEvents.GoalChanged) != 0 && Actor.GoalIndex == goal) return;
+ }
+
+ Assert.Fail("the goal never took over");
+ }
+ }
+
+ [Fact]
+ public void A_three_second_ramp_takes_arousal_and_load_linearly_to_exactly_zero_on_its_last_tick_and_not_before_and_they_stay_zero_under_steady_emitters()
+ {
+ var rig = new Rig(StressThenCalm(3.0));
+ rig.UntilTakeover(1);
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(a0 >= 0.2);
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
+ const int ticks = 300;
+ for (var k = 1; k <= ticks + 500; k++)
+ {
+ rig.Tick();
+ var ramp = Math.Max(0.0, 1.0 - (double)k / ticks);
+ // Sense reads the gain the ramp left at the end of the previous tick.
+ var senseGain = Math.Max(0.0, 1.0 - (double)(k - 1) / ticks);
+ Assert.Equal(a0 * ramp, rig.Actor.Drive.Arousal, 12);
+ Assert.Equal(ramp, rig.Actor.Drive.SensoryGain, 12);
+ Assert.Equal(Afferent * senseGain, rig.Actor.Load, 12);
+ Assert.Equal(0.55, rig.Actor.ChannelStimulus(Channel.Audio), 12); // the world keeps sounding
+ if (k < ticks) Assert.True(rig.Actor.Drive.Arousal > 0.0 && rig.Actor.Drive.SensoryGain > 0.0, $"still above zero at {k * Dt:0.00} s");
+ if (k >= ticks)
+ {
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ }
+
+ if (k > ticks) Assert.Equal(0.0, rig.Actor.Load);
+ }
+ }
+
+ [Fact]
+ public void A_ramp_of_zero_seconds_reaches_the_targets_on_the_takeover_tick()
+ {
+ var rig = new Rig(StressThenCalm(0.0));
+ rig.UntilTakeover(1);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ for (var i = 0; i < 300; i++)
+ {
+ rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Load);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+ }
+
+ [Fact]
+ public void A_ramp_ends_exactly_on_a_nonzero_target_not_a_float_step_away_from_it()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "a", SensoryGain = 0.8, Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "b", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.15, EntryArousal = 0.05, EntrySeconds = 0.5,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ },
+ };
+ var rig = new Rig(brain);
+ Assert.Equal(0.8, rig.Actor.Drive.SensoryGain);
+ rig.UntilTakeover(1);
+ for (var k = 1; k < 50; k++) rig.Tick();
+ Assert.NotEqual(0.15, rig.Actor.Drive.SensoryGain);
+ rig.Tick(); // the ramp's last tick
+ Assert.Equal(0.15, rig.Actor.Drive.SensoryGain); // 0.8 + (0.15 - 0.8) * 1 is not 0.15 in a double
+ Assert.Equal(0.05, rig.Actor.Drive.Arousal); // from the arousal at takeover, 0.2142..., a lerp lands a step off 0.05 too
+ }
+
+ [Fact]
+ public void A_huge_finite_EntrySeconds_is_an_unending_ramp_not_a_snap_or_a_wrap()
+ {
+ // 1e300 / 0.01 is past the long range. On .NET 10 the cast of such a double saturates, so the guard in the Actor is not observable here
+ // (its mutant is equivalent on this runtime); the behaviour it protects on runtimes where the cast is undefined is pinned.
+ var rig = new Rig(StressThenCalm(1e300));
+ rig.UntilTakeover(1);
+ for (var i = 0; i < 2000; i++) rig.Tick();
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain, 12);
+ Assert.True(rig.Actor.Drive.Arousal > 0.0);
+ Assert.True(rig.Actor.Load > 0.0);
+ }
+
+ [Fact]
+ public void The_ramp_length_is_rounded_to_whole_ticks_so_a_quotient_just_under_an_integer_gets_that_integer()
+ {
+ var rig = new Rig(StressThenCalm(0.29)); // 0.29 / 0.01 is 28.999999999999996 ticks, not 28
+ rig.UntilTakeover(1);
+ for (var k = 1; k <= 29; k++)
+ {
+ rig.Tick();
+ if (k < 29) Assert.True(rig.Actor.Drive.SensoryGain > 0.0, $"still ramping at tick {k}");
+ }
+
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+
+ [Fact]
+ public void A_goal_without_an_entry_arousal_ramps_only_the_gain_and_the_drive_keeps_arousal()
+ {
+ var rig = new Rig(StressThenCalm(2.0, gain: 0.0, arousal: null));
+ rig.UntilTakeover(1);
+ var before = rig.Actor.Drive.Arousal;
+ rig.Tick();
+ // One tick of the drive's own law under the gate (the sense still reads gain 1 on the first tick after takeover): arousal moves by it, not by any ramp.
+ var p = new DriveParameters();
+ var expected = Math.Min(Math.Max(before + Dt * (p.ArousalRise * Afferent * (1.0 - before) - p.ArousalDecay * before), 0.0), 1.0);
+ Assert.Equal(expected, rig.Actor.Drive.Arousal, 12);
+ for (var i = 0; i < 6000; i++) rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.True(rig.Actor.Drive.Arousal < 0.01, "with the gain at zero the drive decays arousal on its own");
+ }
+
+ [Fact]
+ public void A_goal_that_takes_over_mid_ramp_ramps_from_where_the_last_ramp_had_got_to()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "stress", Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ new GoalSpec
+ {
+ Id = "alert", Priority = 2.0, SensoryGain = 1.0, EntryArousal = 0.9, EntrySeconds = 2.0,
+ When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = Pose,
+ },
+ },
+ };
+ var rig = new Rig(brain);
+ rig.UntilTakeover(1);
+ for (var i = 0; i < 100; i++) rig.Tick(); // 1 s into the 3 s ramp
+ Assert.True(rig.Actor.Drive.SensoryGain is > 0.0 and < 1.0);
+ rig.Pain = 0.8;
+ rig.UntilTakeover(2);
+ var g0 = rig.Actor.Drive.SensoryGain;
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(g0 is > 0.0 and < 0.7, "alert took over partway down calm's ramp");
+ for (var k = 1; k <= 200; k++)
+ {
+ rig.Tick();
+ var f = k / 200.0;
+ Assert.Equal(g0 + (1.0 - g0) * f, rig.Actor.Drive.SensoryGain, 12);
+ Assert.Equal(a0 + (0.9 - a0) * f, rig.Actor.Drive.Arousal, 12);
+ }
+
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
+ }
+
+ [Fact]
+ public void The_start_goals_targets_hold_from_construction_and_under_steady_emitters()
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "calm", SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0, Behaviour = Pose } } };
+ var rig = new Rig(brain);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ for (var i = 0; i < 600; i++)
+ {
+ rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Load);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+
+ var warm = new Rig(new Brain { Goals = new[] { new GoalSpec { Id = "wound", EntryArousal = 0.6, Behaviour = Pose } } });
+ Assert.Equal(0.6, warm.Actor.Drive.Arousal);
+ }
+
+ [Fact]
+ public void EntryArousal_outside_zero_to_one_and_a_negative_NaN_or_infinite_EntrySeconds_are_refused_naming_the_goal()
+ {
+ void Refused(GoalSpec g)
+ {
+ var ex = Assert.Throws(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { g } }));
+ Assert.Contains("bad", ex.Message);
+ }
+
+ GoalSpec Base() => new() { Id = "bad", Behaviour = Pose };
+ Refused(Base() with { EntryArousal = -0.01 });
+ Refused(Base() with { EntryArousal = 1.01 });
+ Refused(Base() with { EntryArousal = double.NaN });
+ Refused(Base() with { EntrySeconds = -0.01 });
+ Refused(Base() with { EntrySeconds = double.NaN });
+ Refused(Base() with { EntrySeconds = double.PositiveInfinity });
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 0.0, EntrySeconds = 5.0 } } });
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 1.0 } } });
+ }
+}
diff --git a/tests/Lodur.Core.Tests/GoldenParityTests.cs b/tests/Lodur.Core.Tests/GoldenParityTests.cs
new file mode 100644
index 0000000..6caf144
--- /dev/null
+++ b/tests/Lodur.Core.Tests/GoldenParityTests.cs
@@ -0,0 +1,65 @@
+using System.Globalization;
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// The Actor against Bad Day Simulator's pain box at 9f59764, which that repo deletes in its next cut:
+/// pain-box-golden.tsv holds, for 7 intensity/pull settings x seeds 1-60, the outcome and a hash of the
+/// per-tick stimulus, pain, strain, resolve and goal stream. Regenerate with tools/pain-box-golden/generate.sh.
+///
+public sealed class GoldenParityTests
+{
+ private sealed record Row(ulong Seed, double Intensity, double Pull, string Outcome, long BreakMs, long EndMs, int Flinches, long Ticks, ulong Hash);
+
+ private static IEnumerable Rows()
+ {
+ foreach (var line in File.ReadLines(Path.Combine(AppContext.BaseDirectory, "pain-box-golden.tsv")))
+ {
+ if (line.StartsWith('#') || string.IsNullOrWhiteSpace(line)) continue;
+ var f = line.Trim().Split(' ');
+ yield return new Row(ulong.Parse(f[0]), double.Parse(f[1], CultureInfo.InvariantCulture), double.Parse(f[2], CultureInfo.InvariantCulture),
+ f[3], long.Parse(f[4]), long.Parse(f[5]), int.Parse(f[6]), long.Parse(f[7]), Convert.ToUInt64(f[8], 16));
+ }
+ }
+
+ [Fact]
+ public void The_actor_reproduces_the_pain_box_golden_table_exactly()
+ {
+ var rows = Rows().ToList();
+ Assert.Equal(420, rows.Count);
+ Assert.Contains(rows, r => r.Outcome == "Endured");
+ Assert.Contains(rows, r => r.Outcome == "WillBroke");
+
+ var bad = new List();
+ foreach (var row in rows)
+ {
+ var replay = new PainBoxReplay(row.Seed, row.Intensity, row.Pull);
+ var h = 14695981039346656037ul;
+ void Byte(byte b) { h ^= b; h *= 1099511628211ul; }
+ void Double(double d) { foreach (var b in BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(d))) Byte(b); }
+
+ long ticks = 0, broke = -1, withdrew = -1;
+ var flinches = 0;
+ var max = (long)Math.Round(120.0 / PainBoxReplay.Dt);
+ for (long i = 0; i <= max && withdrew < 0; i++)
+ {
+ var e = replay.Tick();
+ ticks++;
+ if ((e & TickEvents.Flinch) != 0) flinches++;
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ var d = replay.Actor.Drive;
+ Double(replay.Actor.Stimulus(0)); Double(d.Pain); Double(d.Strain); Double(d.Resolve);
+ Byte((byte)(replay.Actor.Drive.WillBroken ? 1 : 0));
+ }
+
+ var ms = (long)Math.Round(withdrew >= 0 ? withdrew * 10.0 : max * 10.0);
+ var got = $"{(broke >= 0 ? "WillBroke" : "Endured")} {(broke >= 0 ? broke * 10 : -1)} {ms} {flinches} {ticks} {h:x16}";
+ var want = $"{row.Outcome} {row.BreakMs} {row.EndMs} {row.Flinches} {row.Ticks} {row.Hash:x16}";
+ if (got != want) bad.Add($"seed {row.Seed} i={row.Intensity} p={row.Pull}: got [{got}] want [{want}]");
+ }
+
+ Assert.True(bad.Count == 0, $"{bad.Count} of {rows.Count} runs differ; first: {bad.FirstOrDefault()}");
+ }
+}
diff --git a/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj
new file mode 100644
index 0000000..617d2d1
--- /dev/null
+++ b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+
+ net10.0
+ enable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Lodur.Core.Tests/PainBoxReplay.cs b/tests/Lodur.Core.Tests/PainBoxReplay.cs
new file mode 100644
index 0000000..d7a4695
--- /dev/null
+++ b/tests/Lodur.Core.Tests/PainBoxReplay.cs
@@ -0,0 +1,108 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// SplitMix64, as the pain box in Bad Day Simulator draws its seeded stream.
+internal struct SplitMix64
+{
+ private ulong _s;
+ public SplitMix64(ulong seed) => _s = seed;
+
+ public double NextSigned()
+ {
+ var z = _s += 0x9E3779B97F4A7C15ul;
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;
+ z ^= z >> 31;
+ return (z >> 11) * (1.0 / 9007199254740992.0) * 2.0 - 1.0;
+ }
+}
+
+///
+/// The pain box as a Brain: the objective holds the hold pose against the reflex; the release, entered once the
+/// will breaks, is a pose behaviour with the withdraw pose as its key and no gains.
+///
+internal static class PainBoxBrain
+{
+ public static readonly Quat[] Hold = { Quat.Identity, Quat.Identity };
+ public static readonly Quat[] Withdraw = { Quat.FromAxisAngle(1f, 0f, 0f, 1f), Quat.FromAxisAngle(0f, 0f, 1f, -1f) };
+
+ public static Brain Make(double pull, HoldParameters? hold = null) => new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec
+ {
+ Id = "objective", Priority = 0.0, Pull = pull,
+ Behaviour = new PoseBehaviour { Keys = new[] { Hold }, FlinchPose = Withdraw, Hold = hold ?? new HoldParameters() },
+ },
+ new GoalSpec
+ {
+ Id = "release", Priority = 1.0, Pull = pull, InvoluntarySeconds = double.PositiveInfinity,
+ When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
+ Behaviour = new PoseBehaviour
+ {
+ Keys = new[] { Withdraw }, FlinchPose = Withdraw,
+ Hold = (hold ?? new HoldParameters()) with { FlinchGain = 0.0, StrainShake = 0.0 },
+ },
+ },
+ },
+ };
+}
+
+///
+/// Replays the pain box's stimulus for a seed (traits gain then drain, then per tick jitter, ramp, noise) into an
+/// Actor whose one region sits inside the box. A small fixture, not a model: all the arithmetic is the core's.
+///
+internal sealed class PainBoxReplay
+{
+ public const double Dt = 0.01;
+
+ public readonly Actor Actor;
+ public readonly BoxStimulus[] Sources = { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) };
+ public readonly float[] Strengths = new float[2];
+ public readonly Quat[] Targets = new Quat[2];
+ public static Quat[] Hold => PainBoxBrain.Hold;
+ public static Quat[] Withdraw => PainBoxBrain.Withdraw;
+
+ private readonly float[] _p = { 0f };
+ private SplitMix64 _rng;
+ private readonly double _intensity;
+
+ public PainBoxReplay(ulong seed, double intensity = 0.8, double pull = 0.5, WithdrawalParameters? withdrawal = null,
+ DriveParameters? drive = null, double jitter = 0.2, Brain? brain = null)
+ {
+ _rng = new SplitMix64(seed);
+ _intensity = intensity;
+ var gainTrait = 1.0 + jitter * _rng.NextSigned();
+ var drainTrait = 1.0 + jitter * _rng.NextSigned();
+ Actor = new Actor(Dt, 1, new NerveParameters { Gain = gainTrait }, withdrawal ?? new WithdrawalParameters(),
+ (drive ?? new DriveParameters()) with { DrainTrait = drainTrait }, brain ?? PainBoxBrain.Make(pull));
+ }
+
+ /// One tick of the replayed stimulus; the tick index is Actor.TickCount before the call.
+ public TickEvents Tick(bool boxOn = true)
+ {
+ var tick = Actor.TickCount;
+ var noise = _rng.NextSigned();
+ var ramp = Math.Min(1.0, tick * Dt / 2.0);
+ Sources[0].Intensity = boxOn ? Math.Max(0.0, _intensity * ramp * (1.0 + 0.1 * noise)) : 0.0;
+ return Actor.Tick(_p, _p, _p, Sources, Strengths, Targets);
+ }
+
+ /// Runs to GoalChanged or the cap; returns the tick of WillBroke and GoalChanged (-1 if never) and the flinch count.
+ public (long Broke, long Withdrew, int Flinches) Run(double maxSeconds)
+ {
+ long broke = -1, withdrew = -1;
+ var flinches = 0;
+ var max = (long)Math.Round(maxSeconds / Dt);
+ for (long i = 0; i <= max && withdrew < 0; i++)
+ {
+ var e = Tick();
+ if ((e & TickEvents.Flinch) != 0) flinches++;
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ }
+ return (broke, withdrew, flinches);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/PerceptionTests.cs b/tests/Lodur.Core.Tests/PerceptionTests.cs
new file mode 100644
index 0000000..4c47f47
--- /dev/null
+++ b/tests/Lodur.Core.Tests/PerceptionTests.cs
@@ -0,0 +1,82 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class PerceptionTests
+{
+ private static readonly float[] Zero = { 0f };
+
+ private static double AfferentAt(Perception p, BoxStimulus[] src)
+ {
+ p.Sense(Zero, Zero, Zero, src);
+ return p.Afferent(0);
+ }
+
+ [Theory]
+ [InlineData(0.01, 0.06, 6)]
+ [InlineData(0.005, 0.06, 12)]
+ [InlineData(0.01, 0.0, 1)]
+ public void Afferent_arrives_exactly_the_conduction_delay_after_a_step_stimulus(double dt, double delay, int ticks)
+ {
+ var p = new Perception(new NerveParameters { ConductionDelaySeconds = delay }, dt, 1);
+ var src = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.05) }; // below the 0.1 threshold: nothing
+ for (var i = 0; i < 20; i++) Assert.Equal(0.0, AfferentAt(p, src));
+
+ src[0].Intensity = 0.8;
+ for (var i = 0; i < ticks; i++) Assert.Equal(0.0, AfferentAt(p, src)); // still in flight
+ Assert.True(AfferentAt(p, src) > 0.0); // arrives on tick `ticks`
+ }
+
+ [Fact]
+ public void A_sustained_stimulus_drives_sensitisation_to_its_cap_and_it_recovers_after()
+ {
+ var p = new Perception(new NerveParameters(), 0.01, 1);
+ var src = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.8) };
+ double a = 0;
+ for (var i = 0; i < 20000; i++) a = AfferentAt(p, src);
+ Assert.Equal(0.7 * 2.0, a, 9); // (stimulus - threshold) * SensitisationCap
+
+ // Gone for 300 s: sensitisation is back near 1, so the same weak stimulus reads as weak.
+ src[0].Intensity = 0.0;
+ for (var i = 0; i < 30000; i++) AfferentAt(p, src);
+ src[0].Intensity = 0.15;
+ double first = 0;
+ for (var i = 0; i < 7; i++) first = AfferentAt(p, src);
+ Assert.InRange(first, 0.05, 0.0502);
+
+ // Gone for one second only: still sensitised.
+ var q = new Perception(new NerveParameters(), 0.01, 1);
+ src[0].Intensity = 0.8;
+ for (var i = 0; i < 20000; i++) AfferentAt(q, src);
+ src[0].Intensity = 0.0;
+ for (var i = 0; i < 100; i++) AfferentAt(q, src);
+ src[0].Intensity = 0.15;
+ for (var i = 0; i < 7; i++) first = AfferentAt(q, src);
+ Assert.True(first > 0.09);
+ }
+
+ [Fact]
+ public void A_point_outside_every_box_senses_zero_on_a_face_the_intensity_inside_two_the_larger()
+ {
+ var p = new Perception(new NerveParameters { ConductionDelaySeconds = 0.0 }, 0.01, 3);
+ var src = new[]
+ {
+ new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.4),
+ new BoxStimulus(0.5f, 0f, 0f, 1f, 1f, 1f, 0.9),
+ };
+ // outside both; on the face x = 1 of the first (inside the second); inside both
+ float[] x = { 5f, 1f, 0.2f }, y = { 0f, 0f, 0f }, z = { 0f, 0f, 0f };
+ p.Sense(x, y, z, src);
+ Assert.Equal(0.0, p.Stimulus(0));
+ Assert.Equal(0.9, p.Stimulus(1));
+ Assert.Equal(0.9, p.Stimulus(2));
+
+ src[1].Intensity = 0.0; // isolate the first box
+ p.Sense(x, y, z, src);
+ Assert.Equal(0.4, p.Stimulus(1)); // exactly on a face: inclusive
+ Assert.Equal(0.4, p.Stimulus(2));
+ x[1] = 1.0001f;
+ p.Sense(x, y, z, src);
+ Assert.Equal(0.0, p.Stimulus(1));
+ }
+}
diff --git a/tests/Lodur.Core.Tests/PoseBehaviourTests.cs b/tests/Lodur.Core.Tests/PoseBehaviourTests.cs
new file mode 100644
index 0000000..a81dc31
--- /dev/null
+++ b/tests/Lodur.Core.Tests/PoseBehaviourTests.cs
@@ -0,0 +1,181 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class PoseBehaviourTests
+{
+ private static readonly Quat[] Hold = { Quat.Identity, Quat.FromAxisAngle(1f, 0f, 0f, -1f) };
+ private static readonly Quat[] Withdraw = { Quat.Identity, Quat.FromAxisAngle(1f, 0f, 0f, 0.3f) };
+
+ 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, double weight = 1.0)
+ {
+ var s = new float[2];
+ var q = new Quat[2];
+ b.Write(weight, leak, strain, t, inGoal, s, q);
+ return (s, q);
+ }
+
+ private static float AngleAboutX(Quat q) => 2f * MathF.Atan2(q.X, q.W);
+
+ private static void SameBits(Quat want, Quat got)
+ {
+ Assert.Equal(BitConverter.SingleToInt32Bits(want.X), BitConverter.SingleToInt32Bits(got.X));
+ Assert.Equal(BitConverter.SingleToInt32Bits(want.Y), BitConverter.SingleToInt32Bits(got.Y));
+ Assert.Equal(BitConverter.SingleToInt32Bits(want.Z), BitConverter.SingleToInt32Bits(got.Z));
+ Assert.Equal(BitConverter.SingleToInt32Bits(want.W), BitConverter.SingleToInt32Bits(got.W));
+ }
+
+ [Fact]
+ public void One_key_is_held_and_the_leak_and_shake_blend_it_toward_the_flinch_pose_exactly_as_the_old_reflex_did()
+ {
+ var b = Held();
+ var (s, q) = Write(b, 0.0, 0.0, 0.123);
+ Assert.Equal(-1f, AngleAboutX(q[1]), 4);
+ Assert.All(s, x => Assert.Equal(1f, x));
+
+ foreach (var (leak, strain, t) in new[] { (0.4, 0.0, 0.0), (0.1, 2.5, 0.07), (0.0, 3.0, 1.234), (50.0, 50.0, 0.1) })
+ {
+ var w = Math.Min(Math.Max(leak * 0.3 + 0.03 * strain * Math.Sin(2.0 * Math.PI * 3.5 * t), 0.0), 1.0);
+ (s, q) = Write(b, leak, strain, t, inGoal: 9.9);
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Hold[m], Withdraw[m], (float)w), q[m]);
+ Assert.All(s, x => Assert.InRange(x, 0f, 1f));
+ }
+ }
+
+ [Fact]
+ public void The_release_form_a_key_equal_to_the_flinch_pose_with_gains_zero_writes_the_old_withdraw_pose_bit_for_bit()
+ {
+ var release = new PoseBehaviour
+ {
+ Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw,
+ Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
+ };
+ foreach (var (leak, strain, t) in new[] { (0.0, 0.0, 0.0), (0.9, 4.0, 3.3), (50.0, 50.0, 7.7) })
+ {
+ var (s, q) = Write(release, leak, strain, t, inGoal: 1.0);
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(PainBoxBrain.Hold[m], PainBoxBrain.Withdraw[m], 1f), q[m]);
+ Assert.All(s, x => Assert.Equal(1f, x));
+ }
+ }
+
+ [Fact]
+ public void A_shipped_hold_strength_is_what_every_muscle_is_written_at()
+ {
+ var (s, _) = Write(Held(new HoldParameters { HoldStrength = 0.6f }), 0.0, 0.0, 0.0);
+ 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()
+ {
+ var b = Held();
+ double Peak(double strain)
+ {
+ var peak = 0.0;
+ for (var i = 0; i < 400; i++) peak = Math.Max(peak, b.Blend(0.0, strain, i * 0.005));
+ return peak;
+ }
+ Assert.Equal(0.0, Peak(0.0));
+ Assert.True(Peak(1.0) > 0.0);
+ Assert.True(Peak(2.0) > Peak(1.0) * 1.9);
+ Assert.True(Peak(4.0) > Peak(2.0) * 1.9);
+ }
+
+ [Fact]
+ public void Keys_are_walked_in_a_loop_key_zero_exactly_at_phase_zero_the_nlerp_midpoint_half_way_and_back_to_key_zero_after_k()
+ {
+ var keys = new[]
+ {
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.0f), Quat.FromAxisAngle(0f, 1f, 0f, 0.1f) },
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.5f), Quat.FromAxisAngle(0f, 1f, 0f, 0.7f) },
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 1.0f), Quat.FromAxisAngle(0f, 1f, 0f, 0.2f) },
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 1.5f), Quat.FromAxisAngle(0f, 1f, 0f, -0.4f) },
+ };
+ var b = new PoseBehaviour
+ {
+ Keys = keys, SecondsPerKey = 0.5, FlinchPose = keys[0], // flinch = key 0 and w = 0: only the base shows
+ Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
+ };
+
+ var (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.0);
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(keys[0][m], keys[0][m], 0f), q[m]);
+
+ (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.25); // half way from key 0 to key 1
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Quat.Nlerp(keys[0][m], keys[1][m], 0.5f), keys[0][m], 0f), q[m]);
+
+ (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 1.0); // key 2 exactly
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(keys[2][m], keys[0][m], 0f), q[m]);
+
+ (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 1.75); // half way from the last key back to key 0
+ for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Quat.Nlerp(keys[3][m], keys[0][m], 0.5f), keys[0][m], 0f), q[m]);
+
+ (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 2.0); // after k keys, key 0 again
+ var (_, start) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.0);
+ for (var m = 0; m < 2; m++) SameBits(start[m], q[m]);
+ (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 4.25); // and the second lap is the first
+ var (_, first) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.25);
+ for (var m = 0; m < 2; m++) SameBits(first[m], q[m]);
+ }
+
+ [Fact]
+ public void A_behaviour_is_checked_against_its_own_shape_and_writes_into_spans_of_its_muscle_count_only()
+ {
+ var b = Held();
+ Assert.Equal(2, b.MuscleCount);
+ 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())));
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ Of(b with { FlinchPose = new Quat[1] })));
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ Of(b with { Keys = new[] { Hold, new Quat[1] } })));
+ }
+
+ [Fact]
+ public void Nlerp_takes_the_shorter_arc_and_returns_a_unit_quaternion()
+ {
+ var a = Quat.FromAxisAngle(0f, 0f, 1f, 0.2f);
+ var b = Quat.FromAxisAngle(0f, 0f, 1f, 0.6f);
+ var negB = new Quat(-b.X, -b.Y, -b.Z, -b.W); // same rotation, opposite sign
+ var m = Quat.Nlerp(a, negB, 0.5f);
+ Assert.Equal(0.4f, 2f * MathF.Atan2(m.Z, m.W), 3);
+ Assert.Equal(1f, m.X * m.X + m.Y * m.Y + m.Z * m.Z + m.W * m.W, 5);
+ Assert.Equal(a.Z, Quat.Nlerp(a, b, 0f).Z, 6);
+ Assert.Equal(b.Z, Quat.Nlerp(a, b, 1f).Z, 6);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/SensoryTests.cs b/tests/Lodur.Core.Tests/SensoryTests.cs
new file mode 100644
index 0000000..59624a2
--- /dev/null
+++ b/tests/Lodur.Core.Tests/SensoryTests.cs
@@ -0,0 +1,179 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class SensoryPerceptionTests
+{
+ private const double Dt = 0.01;
+ private static readonly float[] Zero = { 0f };
+ private static readonly BoxStimulus[] NoBoxes = System.Array.Empty();
+
+ /// A sensory nerve with sensitisation off, so afferent = (stimulus - threshold) * gain.
+ private static NerveParameters Plain(double threshold = 0.05, double delay = 0.0, double gain = 1.0) =>
+ new NerveParameters { Threshold = threshold, SensitisationGrowth = 0.0, ConductionDelaySeconds = delay, Gain = gain };
+
+ private static Perception Senses(NerveParameters senses, int regions = 1, int senseRegion = 0) =>
+ new Perception(new NerveParameters(), Dt, regions, senses, senseRegion);
+
+ private static void Sense(Perception p, Emitter[] emitters) => p.Sense(Zero, Zero, Zero, NoBoxes, emitters);
+
+ [Fact]
+ public void An_emitter_is_full_at_its_position_half_at_half_its_radius_and_zero_at_and_beyond_the_radius()
+ {
+ var e = new Emitter(Channel.Audio, 1f, 2f, 3f, 4f, 0.8);
+ Assert.Equal(0.8, e.Received(1f, 2f, 3f), 12);
+ Assert.Equal(0.4, e.Received(3f, 2f, 3f), 12); // 2 m along x: half the radius
+ Assert.Equal(0.4, e.Received(1f, 2f, 5f), 12); // distance is Euclidean, not per axis
+ Assert.Equal(0.0, e.Received(5f, 2f, 3f)); // exactly at the radius
+ Assert.Equal(0.0, e.Received(9f, 2f, 3f));
+ Assert.Equal(0.0, new Emitter(Channel.Audio, 0f, 0f, 0f, 0f, 0.8).Received(0f, 0f, 0f)); // no radius, no reach
+ }
+
+ [Fact]
+ public void Within_a_channel_the_larger_emitter_wins_and_across_channels_the_signals_saturate()
+ {
+ var p = Senses(Plain());
+ Sense(p, new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.3), new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5) });
+ Sense(p, new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.3), new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5) });
+ Assert.Equal(0.5, p.ChannelStimulus(Channel.Audio), 12);
+ Assert.Equal(0.45, p.ChannelAfferent(Channel.Audio), 12); // not 0.3 + 0.5, not the sum of two afferents
+
+ var q = Senses(Plain());
+ var both = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5), new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.35) };
+ Sense(q, both);
+ Sense(q, both);
+ double a = 0.45, b = 0.30;
+ Assert.Equal(a, q.ChannelAfferent(Channel.Audio), 12);
+ Assert.Equal(b, q.ChannelAfferent(Channel.Visual), 12);
+ Assert.Equal(0.0, q.ChannelAfferent(Channel.Interrupt));
+ Assert.Equal(1.0 - (1.0 - a) * (1.0 - b), q.Load, 12);
+ Assert.True(q.Load < a + b);
+
+ // One afferent past 1 is capped before combining, so the load never leaves 0..1.
+ var r = Senses(Plain(gain: 5.0));
+ var loud = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5), new Emitter(Channel.Interrupt, 0f, 0f, 0f, 1f, 0.2) };
+ Sense(r, loud);
+ Sense(r, loud);
+ Assert.Equal(1.0, r.Load);
+ }
+
+ [Theory]
+ [InlineData(0.01, 0.06, 6)]
+ [InlineData(0.005, 0.06, 12)]
+ [InlineData(0.01, 0.0, 1)]
+ public void A_step_emitters_afferent_arrives_exactly_the_conduction_delay_later(double dt, double delay, int ticks)
+ {
+ var p = new Perception(new NerveParameters(), dt, 1, Plain(delay: delay), 0);
+ var quiet = new[] { new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.01) }; // under the threshold
+ for (var i = 0; i < 20; i++) { Sense(p, quiet); Assert.Equal(0.0, p.Load); }
+
+ var loud = new[] { new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.8) };
+ for (var i = 0; i < ticks; i++) { Sense(p, loud); Assert.Equal(0.0, p.Load); } // still in flight
+ Sense(p, loud);
+ Assert.True(p.Load > 0.0);
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
+ }
+
+ [Fact]
+ public void A_sustained_emitter_sensitises_its_channel_as_a_noxious_stimulus_does()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.1 });
+ var e = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
+ for (var i = 0; i < 20000; i++) Sense(p, e);
+ Assert.Equal(0.7 * 2.0, p.ChannelAfferent(Channel.Audio), 9); // (stimulus - threshold) * SensitisationCap
+ }
+
+ [Fact]
+ public void Only_the_sense_regions_point_decides_what_the_emitters_reach()
+ {
+ float[] x = { 0f, 0f }, y = { 0f, 0f }, z = { 0f, 0f };
+ var emitters = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
+ Perception Make() => Senses(Plain(), regions: 2, senseRegion: 1);
+
+ // The sense region (1) is far from the emitter; region 0 sitting on it changes nothing.
+ var far = Make();
+ x[0] = 0f; x[1] = 5f;
+ for (var i = 0; i < 5; i++) far.Sense(x, y, z, NoBoxes, emitters);
+ Assert.Equal(0.0, far.ChannelStimulus(Channel.Audio));
+ Assert.Equal(0.0, far.Load);
+
+ // Moving the sense region next to it does.
+ x[1] = 0f;
+ for (var i = 0; i < 5; i++) far.Sense(x, y, z, NoBoxes, emitters);
+ Assert.Equal(0.8, far.ChannelStimulus(Channel.Audio), 12);
+ Assert.True(far.Load > 0.0);
+
+ // And with region 0 far away and region 1 on it, it still reaches.
+ var near = Make();
+ x[0] = 5f; x[1] = 0f;
+ for (var i = 0; i < 5; i++) near.Sense(x, y, z, NoBoxes, emitters);
+ Assert.Equal(0.8, near.ChannelStimulus(Channel.Audio), 12);
+ }
+
+ [Fact]
+ public void Without_senses_or_without_emitters_the_load_and_every_channel_stay_zero()
+ {
+ var deaf = new Perception(new NerveParameters(), Dt, 1);
+ var loud = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 1.0) };
+ var hearing = Senses(Plain());
+ for (var i = 0; i < 10000; i++)
+ {
+ deaf.Sense(Zero, Zero, Zero, NoBoxes, loud);
+ hearing.Sense(Zero, Zero, Zero, NoBoxes);
+ Assert.Equal(0.0, deaf.Load);
+ Assert.Equal(0.0, hearing.Load);
+ }
+
+ foreach (var c in new[] { Channel.Audio, Channel.Visual, Channel.Interrupt })
+ {
+ Assert.Equal(0.0, deaf.ChannelStimulus(c));
+ Assert.Equal(0.0, deaf.ChannelAfferent(c));
+ Assert.Equal(0.0, hearing.ChannelAfferent(c));
+ }
+ }
+
+ [Fact]
+ public void A_sense_region_outside_the_body_is_refused()
+ {
+ Assert.Throws(() => Senses(Plain(), regions: 2, senseRegion: 2));
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ public void The_sense_point_is_the_sense_regions_and_the_distance_counts_every_axis(int axis)
+ {
+ // Three regions; the sense region is the middle one. The first and last sit exactly on the emitter, the middle one half a radius away along one axis.
+ float[] x = { 0f, 0f, 0f }, y = { 0f, 0f, 0f }, z = { 0f, 0f, 0f };
+ var offset = new[] { x, y, z }[axis];
+ offset[1] = 0.5f;
+ var p = Senses(Plain(), regions: 3, senseRegion: 1);
+ var emitters = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
+ p.Sense(x, y, z, NoBoxes, emitters);
+ Assert.Equal(0.4, p.ChannelStimulus(Channel.Audio), 12);
+ }
+
+ [Fact]
+ public void An_emitter_with_a_channel_outside_the_three_is_refused_up_front_and_leaves_the_tick_unrun()
+ {
+ var p = Senses(Plain());
+ var good = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
+ for (var i = 0; i < 3; i++) Sense(p, good);
+ var stimulus = p.ChannelStimulus(Channel.Audio);
+ var afferent = p.ChannelAfferent(Channel.Audio);
+ var load = p.Load;
+
+ var bad = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8), new Emitter((Channel)7, 0f, 0f, 0f, 1f, 0.8) };
+ var e = Assert.Throws(() => Sense(p, bad));
+ Assert.Contains("Emitter 1", e.Message);
+ Assert.Equal(stimulus, p.ChannelStimulus(Channel.Audio));
+ Assert.Equal(afferent, p.ChannelAfferent(Channel.Audio));
+ Assert.Equal(load, p.Load);
+
+ // The tick did not advance: a twin that never saw the bad call stays identical from here on.
+ var twin = Senses(Plain());
+ for (var i = 0; i < 3; i++) Sense(twin, good);
+ for (var i = 0; i < 20; i++) { Sense(p, good); Sense(twin, good); Assert.Equal(twin.Load, p.Load); }
+ }
+}
diff --git a/tests/Lodur.Core.Tests/WillTests.cs b/tests/Lodur.Core.Tests/WillTests.cs
new file mode 100644
index 0000000..4a559f5
--- /dev/null
+++ b/tests/Lodur.Core.Tests/WillTests.cs
@@ -0,0 +1,604 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// The will breaks when resolve reaches zero, mends when it climbs back to WillMendsAt, and can break again.
+public sealed class WillTests
+{
+ private static Brain Gate(DriveQuantity q, double threshold) => new()
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "objective", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw } },
+ new GoalSpec
+ {
+ Id = "release", Priority = 1.0,
+ When = new[] { new Condition(q, ConditionOp.AtLeast, threshold) },
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+
+ /// Ticks the box on (or off) until the predicate holds or the cap runs out; counts WillBroke events on the way.
+ private static long Until(PainBoxReplay r, bool boxOn, Func done, ref int breaks, long cap = 40000)
+ {
+ for (long i = 0; i < cap; i++)
+ {
+ if ((r.Tick(boxOn) & TickEvents.WillBroke) != 0) breaks++;
+ if (done(r.Actor.Drive)) return i;
+ }
+
+ Assert.Fail("the predicate never held");
+ return -1;
+ }
+
+ [Fact]
+ public void A_will_that_mends_can_break_again_and_each_break_is_reported_and_counted_but_resolve_parked_at_zero_breaks_once()
+ {
+ var r = new PainBoxReplay(1, brain: Gate(DriveQuantity.Breaks, 99.0));
+ var breaks = 0;
+ Until(r, true, d => d.WillBroken, ref breaks);
+ Assert.Equal(1, breaks);
+ Assert.Equal(1, r.Actor.Drive.Breaks);
+
+ for (var i = 0; i < 3000; i++) r.Tick(true); // held under the box, resolve parked at zero
+ Assert.Equal(0.0, r.Actor.Drive.Resolve);
+ Assert.True(r.Actor.Drive.WillBroken);
+
+ for (var i = 0; i < 3000; i++) if ((r.Tick(true) & TickEvents.WillBroke) != 0) breaks++;
+ Assert.Equal(1, breaks);
+
+ Until(r, false, d => !d.WillBroken, ref breaks);
+ Assert.True(r.Actor.Drive.Resolve >= new DriveParameters().WillMendsAt);
+ Assert.Equal(1, r.Actor.Drive.Breaks);
+
+ Until(r, true, d => d.WillBroken, ref breaks);
+ Assert.Equal(2, breaks);
+ Assert.Equal(2, r.Actor.Drive.Breaks);
+ }
+
+ [Fact]
+ public void A_mend_waits_for_resolve_to_reach_WillMendsAt_not_merely_to_leave_zero()
+ {
+ var mends = new DriveParameters { WillMendsAt = 0.6 };
+ var r = new PainBoxReplay(1, drive: mends, brain: Gate(DriveQuantity.Breaks, 99.0));
+ var breaks = 0;
+ Until(r, true, d => d.WillBroken, ref breaks);
+ Until(r, false, d => d.Resolve > 0.0, ref breaks);
+ var mended = Until(r, false, d => !d.WillBroken, ref breaks);
+ Assert.True(mended > 0, "the will mended the moment resolve left zero");
+ Assert.True(r.Actor.Drive.Resolve >= 0.6);
+ }
+
+ [Theory]
+ [InlineData(DriveQuantity.Breaks, true)]
+ [InlineData(DriveQuantity.WillBroken, false)]
+ public void A_release_gated_on_Breaks_holds_after_the_will_mends_and_one_gated_on_WillBroken_returns_to_the_objective(DriveQuantity q, bool holds)
+ {
+ var r = new PainBoxReplay(1, brain: Gate(q, 1.0));
+ var breaks = 0;
+ Until(r, true, d => d.WillBroken, ref breaks);
+ for (var i = 0; i < 50; i++) r.Tick(true);
+ Assert.Equal(1, r.Actor.GoalIndex);
+
+ Until(r, false, d => !d.WillBroken, ref breaks);
+ for (var i = 0; i < 100; i++) r.Tick(false);
+ Assert.Equal(holds ? 1 : 0, r.Actor.GoalIndex);
+ }
+
+ [Fact]
+ public void A_condition_on_Breaks_at_two_follows_the_second_break_by_the_latency_not_the_first()
+ {
+ var r = new PainBoxReplay(1, brain: Gate(DriveQuantity.Breaks, 2.0));
+ var breaks = 0;
+ Until(r, true, d => d.WillBroken, ref breaks);
+ for (var i = 0; i < 100; i++) r.Tick(true);
+ Assert.Equal(0, r.Actor.GoalIndex);
+
+ Until(r, false, d => !d.WillBroken, ref breaks);
+ Until(r, true, d => d.Breaks == 2, ref breaks);
+ var second = r.Actor.TickCount;
+ long changed = -1;
+ for (var i = 0; i < 30 && changed < 0; i++)
+ {
+ if ((r.Tick(true) & TickEvents.GoalChanged) != 0) changed = r.Actor.TickCount;
+ }
+
+ Assert.Equal(second + 10, changed);
+ }
+
+ [Fact]
+ public void Will_is_resolve_bit_for_bit_while_attention_and_consciousness_are_slots_that_read_one()
+ {
+ var r = new PainBoxReplay(3);
+ for (var i = 0; i < 2500; i++)
+ {
+ r.Tick(true);
+ var d = r.Actor.Drive;
+ Assert.Equal(1.0, d.Attention);
+ Assert.Equal(1.0, d.Consciousness);
+ Assert.Equal(BitConverter.DoubleToInt64Bits(d.Resolve), BitConverter.DoubleToInt64Bits(d.Will));
+ }
+ }
+
+ [Theory]
+ [InlineData(0.0)]
+ [InlineData(-0.1)]
+ [InlineData(1.01)]
+ [InlineData(double.NaN)]
+ public void A_WillMendsAt_outside_zero_exclusive_to_one_is_refused(double mendsAt) =>
+ Assert.Throws(() => new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = mendsAt }));
+
+ [Fact]
+ public void A_WillMendsAt_of_one_is_allowed() => _ = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 1.0 });
+
+ private static PoseBehaviour Pose => new() { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
+
+ private static Brain Rage(double? entry) => new()
+ {
+ 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,
+ },
+ },
+ };
+
+ [Theory]
+ [InlineData(1.0, false)]
+ [InlineData(0.1, true)]
+ public void A_goals_entry_resolve_is_set_on_the_tick_it_takes_over_and_mends_the_will_only_if_it_reaches_WillMendsAt(double entry, bool stillBroken)
+ {
+ var r = new PainBoxReplay(1, brain: Rage(entry));
+ TickEvents e;
+ do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
+ Assert.NotEqual(0, (int)(e & TickEvents.GoalChanged));
+ Assert.Equal(1, r.Actor.GoalIndex);
+ Assert.Equal(entry, r.Actor.Drive.Resolve);
+ Assert.Equal(stillBroken, r.Actor.Drive.WillBroken);
+ Assert.Equal(1, r.Actor.Drive.Breaks);
+ }
+
+ [Fact]
+ public void A_goal_with_no_entry_resolve_leaves_resolve_alone()
+ {
+ var r = new PainBoxReplay(1, brain: Rage(null));
+ 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.Drive.WillBroken);
+ }
+
+ [Theory]
+ [InlineData(1.0, 0.0, 0.5)]
+ [InlineData(1.0, 0.4, 2.0)]
+ [InlineData(0.0, 0.0, 0.5)]
+ public void Effort_drains_resolve_only_after_the_involuntary_onset_by_effort_times_one_minus_pull_times_the_trait(double onset, double pull, double effort)
+ {
+ var drive = new DriveParameters { ResolveRecovery = 0.0, DrainTrait = 1.0 };
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Pull = pull, Effort = effort, InvoluntarySeconds = onset, Behaviour = Pose } } };
+ var r = new PainBoxReplay(1, drive: drive, brain: brain, jitter: 0.0);
+ var first = -1L;
+ var last = 1.0;
+ var steps = 0;
+ for (long i = 0; i < 400; i++)
+ {
+ r.Tick(false);
+ var now = r.Actor.Drive.Resolve;
+ if (now <= 0.0) break; // the floor clips the last step
+ if (now < 1.0 && first < 0)
+ {
+ first = i;
+ last = 1.0;
+ }
+
+ if (first >= 0)
+ {
+ Assert.Equal(0.01 * effort * (1.0 - pull), last - now, 12);
+ steps++;
+ }
+
+ last = now;
+ }
+
+ Assert.Equal((long)Math.Round(onset / 0.01), first);
+ Assert.True(steps > 20);
+ }
+
+ [Fact]
+ public void An_infinitely_involuntary_goal_never_pays_its_effort()
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 5.0, InvoluntarySeconds = double.PositiveInfinity, Behaviour = Pose } } };
+ var r = new PainBoxReplay(1, brain: brain);
+ for (var i = 0; i < 500; i++) r.Tick(false);
+ Assert.Equal(1.0, r.Actor.Drive.Resolve);
+ }
+
+ [Fact]
+ public void Onset_is_counted_from_the_tick_the_goal_takes_over_not_from_the_start()
+ {
+ var late = new GoalSpec { Id = "late", Priority = 1.0, Effort = 1.0, InvoluntarySeconds = 0.5, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.3) }, Behaviour = Pose };
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "calm", Behaviour = Pose }, late } };
+ var r = new PainBoxReplay(1, brain: brain, drive: new DriveParameters { ResolveRecovery = 0.0 });
+ long took = -1;
+ long firstEffort = -1;
+ for (long i = 0; i < 3000 && firstEffort < 0; i++)
+ {
+ var before = r.Actor.Drive;
+ var e = r.Tick(true);
+ if ((e & TickEvents.GoalChanged) != 0) took = i;
+ var drainedWithoutEffort = before.Resolve - r.Actor.Drive.Resolve;
+ if (took >= 0 && drainedWithoutEffort > 0.01 * 1.0 * 0.5 * 0.99) firstEffort = i;
+ }
+
+ Assert.True(took > 0);
+ Assert.True(firstEffort - took >= 50, $"effort began {firstEffort - took} ticks after the goal took over, under the 50 of the onset");
+ }
+
+ [Fact]
+ public void Goal_values_outside_their_ranges_are_refused_naming_the_goal()
+ {
+ Brain Of(GoalSpec g) => new() { Goals = new[] { g } };
+ GoalSpec Base() => new() { Id = "bad", Behaviour = Pose };
+ void Refused(GoalSpec g)
+ {
+ var ex = Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(g)));
+ Assert.Contains("bad", ex.Message);
+ }
+
+ Refused(Base() with { EntryResolve = -0.01 });
+ Refused(Base() with { EntryResolve = 1.01 });
+ Refused(Base() with { EntryResolve = double.NaN });
+ Refused(Base() with { Effort = -1.0 });
+ Refused(Base() with { Effort = double.PositiveInfinity });
+ Refused(Base() with { Effort = double.NaN });
+ Refused(Base() with { InvoluntarySeconds = -0.1 });
+ Refused(Base() with { InvoluntarySeconds = double.NaN });
+
+ _ = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ 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 }));
+
+ public static IEnumerable BadDrives() => new[]
+ {
+ new object[] { new DriveParameters { DrainTrait = double.NaN } },
+ new object[] { new DriveParameters { DrainTrait = -1.0 } },
+ new object[] { new DriveParameters { PainRise = double.PositiveInfinity } },
+ new object[] { new DriveParameters { PainDecay = double.NaN } },
+ new object[] { new DriveParameters { StrainRecover = -0.1 } },
+ new object[] { new DriveParameters { ResolveDrainPain = double.NaN } },
+ new object[] { new DriveParameters { ResolveDrainStrain = double.NegativeInfinity } },
+ new object[] { new DriveParameters { ResolveRecovery = double.NaN } },
+ new object[] { new DriveParameters { ResolveRecoversBelowPain = double.NaN } },
+ new object[] { new DriveParameters { ArousalRise = -1.0 } },
+ new object[] { new DriveParameters { ArousalDecay = double.NaN } },
+ new object[] { new DriveParameters { ResolveDrainArousal = double.PositiveInfinity } },
+ new object[] { new DriveParameters { ResolveRecoversBelowArousal = double.NaN } },
+ };
+
+ [Theory]
+ [MemberData(nameof(BadDrives))]
+ public void A_drive_value_the_drive_cannot_run_on_is_refused_at_construction_before_any_tick(DriveParameters bad) =>
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), bad, PainBoxBrain.Make(0.5)));
+
+ [Theory]
+ [InlineData(1.0 / 120.0, 1.85, 222)] // 222 x (1/120) is just under 1.85 in floating point
+ [InlineData(1.0 / 60.0, 0.9, 54)]
+ [InlineData(0.01, 0.5, 50)]
+ [InlineData(0.01, 0.29, 29)] // 0.29 / 0.01 is 28.999999999999996: rounds to 29, floors to 28
+ public void The_involuntary_onset_is_the_requested_seconds_in_whole_ticks_whatever_the_tick_length(double dt, double onset, long ticks)
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 1.0, InvoluntarySeconds = onset, Behaviour = Pose } } };
+ var actor = new Actor(dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters { ResolveRecovery = 0.0 }, brain);
+ float[] p = { 0f }, strengths = new float[2];
+ var targets = new Quat[2];
+ long firstDrain = -1, firstWeighted = -1;
+ for (long i = 0; i < ticks + 20; i++)
+ {
+ var before = actor.Drive.Resolve;
+ actor.Tick(p, p, p, System.Array.Empty(), strengths, targets);
+ if (firstDrain < 0 && actor.Drive.Resolve < before) firstDrain = i;
+ if (firstWeighted < 0 && strengths[0] < 1f) firstWeighted = i;
+ }
+
+ Assert.Equal(ticks, firstDrain);
+ Assert.Equal(ticks, firstWeighted);
+ }
+
+ [Theory]
+ [InlineData(1e300)]
+ [InlineData(1e19)]
+ [InlineData(double.PositiveInfinity)]
+ public void An_onset_past_the_range_of_a_tick_count_is_involuntary_throughout_not_a_wrapped_negative(double onset)
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 1.0, InvoluntarySeconds = onset, Behaviour = Pose } } };
+ var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters { ResolveRecovery = 0.0 }, brain);
+ float[] p = { 0f }, strengths = new float[2];
+ var targets = new Quat[2];
+ for (var i = 0; i < 500; i++)
+ {
+ actor.Tick(p, p, p, System.Array.Empty(), strengths, targets);
+ Assert.Equal(1.0, actor.Drive.Resolve);
+ Assert.Equal(1f, strengths[0]);
+ }
+ }
+
+ [Fact]
+ public void A_puppet_that_starts_in_a_goal_with_an_entry_resolve_begins_at_it()
+ {
+ var brain = new Brain { Start = 1, Goals = new[] { new GoalSpec { Id = "calm", Behaviour = Pose }, new GoalSpec { Id = "rage", EntryResolve = 0.6, Behaviour = Pose } } };
+ var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain);
+ Assert.Equal(0.6, actor.Drive.Resolve);
+
+ var calm = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain with { Start = 0 });
+ Assert.Equal(1.0, calm.Drive.Resolve);
+ }
+
+ // The slots read 1 in the core today; these tests lower them through the internal seam and watch every consumer of Will move.
+
+ private static Actor Hold(double attention, double consciousness, DriveParameters? drive = null)
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 } } } };
+ var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), drive ?? new DriveParameters(), brain);
+ actor.SetWillSlots(attention, consciousness);
+ return actor;
+ }
+
+ private static readonly float[] NoPoint = { 0f };
+
+ private static TickEvents Step(Actor a, double boxIntensity, float[] strengths, Quat[] targets)
+ {
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = boxIntensity } };
+ return a.Tick(NoPoint, NoPoint, NoPoint, box, strengths, targets);
+ }
+
+ [Theory]
+ [InlineData(1.0, 1.0)]
+ [InlineData(0.5, 1.0)]
+ [InlineData(1.0, 0.3)]
+ [InlineData(0.5, 0.3)]
+ [InlineData(0.5, 0.9)]
+ [InlineData(0.0, 1.0)]
+ public void Will_is_resolve_times_attention_capped_by_consciousness(double attention, double consciousness)
+ {
+ var a = Hold(attention, consciousness);
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 300; i++)
+ {
+ Step(a, 0.6, s, q);
+ var d = a.Drive;
+ Assert.Equal(Math.Min(d.Resolve * attention, consciousness), d.Will);
+ }
+ }
+
+ [Fact]
+ public void Reflex_suppression_reads_Will_so_a_lowered_slot_releases_it_though_resolve_is_full()
+ {
+ // A held reflex accrues strain; with attention gone nothing is held, whatever resolve says.
+ double StrainAfter(double attention, double consciousness)
+ {
+ var a = Hold(attention, consciousness);
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 100; i++) Step(a, 0.8, s, q);
+ Assert.True(a.Drive.Resolve > 0.9);
+ return a.Drive.Strain;
+ }
+
+ var full = StrainAfter(1.0, 1.0);
+ Assert.True(full > 0.1);
+ Assert.Equal(0.0, StrainAfter(0.0, 1.0));
+ Assert.Equal(0.0, StrainAfter(1.0, 0.0));
+ var half = StrainAfter(0.5, 1.0);
+ Assert.True(half > 0.0 && half < full);
+ var capped = StrainAfter(1.0, 0.5);
+ Assert.True(capped > 0.0 && capped < full);
+ }
+
+ [Fact]
+ public void The_flinch_gate_reads_Will_so_no_flinch_is_reported_when_there_is_no_will_to_leak_from()
+ {
+ int Flinches(double attention)
+ {
+ var a = Hold(attention, 1.0);
+ var s = new float[2];
+ var q = new Quat[2];
+ var n = 0;
+ for (var i = 0; i < 400; i++) if ((Step(a, 0.9, s, q) & TickEvents.Flinch) != 0) n++;
+ Assert.True(a.Drive.Resolve > 0.5);
+ return n;
+ }
+
+ Assert.True(Flinches(0.3) > 0);
+ Assert.Equal(0, Flinches(0.0));
+ }
+
+ [Theory]
+ [InlineData(0.5, 1.0)]
+ [InlineData(1.0, 0.2)]
+ [InlineData(0.5, 0.4)]
+ public void The_voluntary_weight_reads_Will_so_a_lowered_slot_slackens_the_hold(double attention, double consciousness)
+ {
+ var a = Hold(attention, consciousness, new DriveParameters { WillCurve = 0.5 });
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 20; i++)
+ {
+ Step(a, 0.0, s, q); // no stimulus, no leak
+ Assert.Equal(0.7f * (float)Math.Sqrt(Math.Min(a.Drive.Resolve * attention, consciousness)), s[0]);
+ }
+ }
+
+ [Fact]
+ public void An_entered_goals_resolve_is_set_once_on_the_takeover_so_a_rage_with_effort_drains_the_will_it_was_given()
+ {
+ var rage = new GoalSpec
+ {
+ Id = "rage", Priority = 1.0, EntryResolve = 1.0, Effort = 0.5, InvoluntarySeconds = 0.3,
+ When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = Pose,
+ };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { new GoalSpec { Id = "composure", Behaviour = Pose }, rage } });
+ TickEvents e;
+ do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
+ Assert.Equal(1.0, r.Actor.Drive.Resolve);
+
+ var onsetTicks = 30;
+ for (var i = 0; i < onsetTicks - 1; i++)
+ {
+ r.Tick(false);
+ Assert.True(r.Actor.Drive.Resolve > 0.95); // the onset runs on the refilled will without paying its effort
+ }
+
+ for (var i = 0; i < 170; i++) r.Tick(false);
+ Assert.Equal(1, r.Actor.GoalIndex);
+ Assert.True(r.Actor.Drive.Resolve < 0.3, $"resolve is {r.Actor.Drive.Resolve}: the entry effect ran again, or the effort never drained it");
+ }
+
+ [Fact]
+ public void Each_entry_to_a_goal_sets_resolve_once_and_a_re_entry_sets_it_again()
+ {
+ var calm = new GoalSpec { Id = "calm", Behaviour = Pose };
+ var rage = new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = 0.5, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5) }, Behaviour = Pose };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { calm, rage } });
+ var entries = 0;
+ long sinceEntry = -1;
+ var checkedInside = 0;
+ for (var i = 0; i < 8000; i++)
+ {
+ var on = i < 800 || (i >= 4500 && i < 5300);
+ var e = r.Tick(on);
+ if ((e & TickEvents.GoalChanged) != 0 && r.Actor.GoalIndex == 1)
+ {
+ entries++;
+ sinceEntry = 0;
+ Assert.Equal(0.5, r.Actor.Drive.Resolve);
+ }
+ else if (sinceEntry >= 0 && r.Actor.GoalIndex == 1 && ++sinceEntry == 100)
+ {
+ Assert.True(r.Actor.Drive.Resolve < 0.499, $"resolve is {r.Actor.Drive.Resolve} 100 ticks into the goal: it was set again");
+ checkedInside++;
+ }
+ }
+
+ Assert.Equal(2, entries);
+ Assert.Equal(2, checkedInside);
+ }
+
+ [Fact]
+ public void A_goal_whose_entry_resolve_is_exactly_WillMendsAt_mends_the_will()
+ {
+ var rage = new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = 0.5, When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = Pose };
+ var r = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 0.5 }, brain: new Brain { Goals = new[] { new GoalSpec { Id = "composure", Behaviour = Pose }, rage } });
+ TickEvents e;
+ do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
+ Assert.Equal(0.5, r.Actor.Drive.Resolve);
+ Assert.False(r.Actor.Drive.WillBroken);
+ }
+
+ [Fact]
+ public void Recovery_that_lands_exactly_on_WillMendsAt_mends_the_will_on_that_tick()
+ {
+ // Run once with a will that never mends to record resolve; then set WillMendsAt to a value that trace reaches exactly.
+ var trace = new List();
+ var first = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 1.0 }, brain: Gate(DriveQuantity.Breaks, 99.0));
+ while (!first.Actor.Drive.WillBroken) first.Tick(true);
+ for (var i = 0; i < 7000; i++) { first.Tick(false); trace.Add(first.Actor.Drive.Resolve); }
+ var j = 6500;
+ var at = trace[j];
+ Assert.True(at > trace[j - 1] && at > 0.0 && at < 1.0, "the trace is not recovering at the probe tick");
+ var k = trace.FindIndex(x => x >= at);
+ Assert.Equal(j, k);
+
+ var second = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = at }, brain: Gate(DriveQuantity.Breaks, 99.0));
+ while (!second.Actor.Drive.WillBroken) second.Tick(true);
+ for (var i = 0; i < 7000; i++)
+ {
+ second.Tick(false);
+ Assert.Equal(i < k, second.Actor.Drive.WillBroken);
+ }
+ }
+}
diff --git a/tests/Lodur.Core.Tests/pain-box-golden.tsv b/tests/Lodur.Core.Tests/pain-box-golden.tsv
new file mode 100644
index 0000000..37ad24d
--- /dev/null
+++ b/tests/Lodur.Core.Tests/pain-box-golden.tsv
@@ -0,0 +1,422 @@
+# Generated by tools/pain-box-golden/generate.sh from BadDaySimulator 9f59764 PainBoxSimulation (tick 10 ms, one sample row per tick). Do not edit.
+# seed intensity pull outcome break_ms end_ms flinches ticks hash
+1 0.8 0.5 WillBroke 14730 14830 16 1484 1ceb743a21f5ff5a
+2 0.8 0.5 WillBroke 14600 14700 16 1471 7259484084f5a927
+3 0.8 0.5 WillBroke 16520 16620 16 1663 1d6bba4a157df7a6
+4 0.8 0.5 WillBroke 14660 14760 15 1477 e5eebd484761de72
+5 0.8 0.5 WillBroke 15270 15370 16 1538 3c4747a8445cefd7
+6 0.8 0.5 WillBroke 15160 15260 17 1527 195b3053e604f362
+7 0.8 0.5 WillBroke 18400 18500 20 1851 9f21e1a7ce0e8e45
+8 0.8 0.5 WillBroke 14950 15050 16 1506 70030d48d40f4b19
+9 0.8 0.5 WillBroke 14330 14430 16 1444 42e87dc3299a52ac
+10 0.8 0.5 WillBroke 16720 16820 16 1683 ac540aa974f86a3d
+11 0.8 0.5 WillBroke 17460 17560 18 1757 27c1801dd3b14200
+12 0.8 0.5 WillBroke 14090 14190 15 1420 319ec304c2b2cc96
+13 0.8 0.5 WillBroke 15470 15570 17 1558 c5df29d2946eb2d0
+14 0.8 0.5 WillBroke 17950 18050 20 1806 9ae75b13832bd3e4
+15 0.8 0.5 WillBroke 14730 14830 16 1484 9d430ea61e812af0
+16 0.8 0.5 WillBroke 18100 18200 20 1821 8e5fb25cbd4fb1fe
+17 0.8 0.5 WillBroke 16190 16290 18 1630 05610c511c4d19c1
+18 0.8 0.5 WillBroke 16630 16730 16 1674 f5e2796f88e62ef6
+19 0.8 0.5 WillBroke 16540 16640 18 1665 b25f6c3df9d287d6
+20 0.8 0.5 WillBroke 19200 19300 20 1931 bfd2524973119a17
+21 0.8 0.5 WillBroke 16150 16250 16 1626 125a8dcf62f71b8a
+22 0.8 0.5 WillBroke 13550 13650 15 1366 7507771068c765e1
+23 0.8 0.5 WillBroke 14200 14300 16 1431 3bcf5023b59ce3a8
+24 0.8 0.5 WillBroke 14710 14810 16 1482 1a491d9500a4ee8a
+25 0.8 0.5 WillBroke 16820 16920 19 1693 f0830cd17098c811
+26 0.8 0.5 WillBroke 15070 15170 17 1518 c9e6b86dbee77d05
+27 0.8 0.5 WillBroke 14840 14940 16 1495 5e57b1ae95415f2d
+28 0.8 0.5 WillBroke 14770 14870 16 1488 2c0b8e2781a51ee3
+29 0.8 0.5 WillBroke 14250 14350 16 1436 c32ad3049a90f668
+30 0.8 0.5 WillBroke 14500 14600 16 1461 4910c161327cdb00
+31 0.8 0.5 WillBroke 13930 14030 15 1404 1bdcd50e804b9bdd
+32 0.8 0.5 WillBroke 14180 14280 16 1429 2ab161925bd68a7e
+33 0.8 0.5 WillBroke 19070 19170 20 1918 5c18119adec71cce
+34 0.8 0.5 WillBroke 14590 14690 15 1470 64587cd7060ee804
+35 0.8 0.5 WillBroke 16120 16220 17 1623 78ac045afa3e8511
+36 0.8 0.5 WillBroke 15050 15150 17 1516 82450899d9167065
+37 0.8 0.5 WillBroke 14190 14290 16 1430 ae4a4d35b3f54257
+38 0.8 0.5 WillBroke 16400 16500 19 1651 e0ea8c58df2c29c5
+39 0.8 0.5 WillBroke 13580 13680 15 1369 6d1697c268835c76
+40 0.8 0.5 WillBroke 15190 15290 15 1530 3c4a7a8be8eb2453
+41 0.8 0.5 WillBroke 17060 17160 17 1717 38ae8fdfa2ca5b91
+42 0.8 0.5 WillBroke 16310 16410 18 1642 3ff1fef4fb1442de
+43 0.8 0.5 WillBroke 14650 14750 16 1476 19f85bbaf383110c
+44 0.8 0.5 WillBroke 14110 14210 16 1422 027af17c0ac0fdc7
+45 0.8 0.5 WillBroke 12960 13060 14 1307 d1fb96d0ee7ba804
+46 0.8 0.5 WillBroke 16280 16380 18 1639 c8e839df23f5a211
+47 0.8 0.5 WillBroke 16600 16700 18 1671 e7f53b160c1853ae
+48 0.8 0.5 WillBroke 17070 17170 16 1718 aeec09055f384b43
+49 0.8 0.5 WillBroke 17970 18070 18 1808 f212a3419dd45eb8
+50 0.8 0.5 WillBroke 14720 14820 16 1483 138dc377b6038fc6
+51 0.8 0.5 WillBroke 17000 17100 18 1711 91bf94bf4f9b80a9
+52 0.8 0.5 WillBroke 15330 15430 18 1544 479d44543e6d898f
+53 0.8 0.5 WillBroke 16910 17010 19 1702 23c9ae667a13b1b8
+54 0.8 0.5 WillBroke 15710 15810 18 1582 5db0798e7430331f
+55 0.8 0.5 WillBroke 18080 18180 20 1819 bb57883965df4728
+56 0.8 0.5 WillBroke 14690 14790 16 1480 db298aebc9ac6475
+57 0.8 0.5 WillBroke 17110 17210 18 1722 a8b179b65459b425
+58 0.8 0.5 WillBroke 16040 16140 17 1615 9311f9bf9c30c9fa
+59 0.8 0.5 WillBroke 15280 15380 17 1539 d357274a150ed640
+60 0.8 0.5 WillBroke 16430 16530 18 1654 dce27d808a54e389
+1 1.0 0.5 WillBroke 12700 12800 15 1281 3778c1c08b0e4636
+2 1.0 0.5 WillBroke 12590 12690 15 1270 d2e72be9df803e3d
+3 1.0 0.5 WillBroke 14160 14260 16 1427 0b18cbb4d9d49fbb
+4 1.0 0.5 WillBroke 12650 12750 15 1276 da78405420316abd
+5 1.0 0.5 WillBroke 13140 13240 15 1325 c95a030fe020dd7a
+6 1.0 0.5 WillBroke 13040 13140 16 1315 44fd3277642c8a9a
+7 1.0 0.5 WillBroke 15660 15760 19 1577 017b21240992c769
+8 1.0 0.5 WillBroke 12880 12980 15 1299 599e66b4a1a5921e
+9 1.0 0.5 WillBroke 12370 12470 15 1248 cb45d1000cf1ea08
+10 1.0 0.5 WillBroke 14320 14420 16 1443 32fa60bc328344e0
+11 1.0 0.5 WillBroke 14910 15010 17 1502 fe8e6683df6f44c1
+12 1.0 0.5 WillBroke 12180 12280 14 1229 d7ceb4d09ec176aa
+13 1.0 0.5 WillBroke 13290 13390 16 1340 e8036a983b52c1ab
+14 1.0 0.5 WillBroke 15310 15410 18 1542 0b8a9b1c08492fbe
+15 1.0 0.5 WillBroke 12700 12800 15 1281 a8ed8929fa4337f0
+16 1.0 0.5 WillBroke 15430 15530 18 1554 eb95c4903824bb05
+17 1.0 0.5 WillBroke 13890 13990 16 1400 6db1399b0be214fa
+18 1.0 0.5 WillBroke 14250 14350 15 1436 535d36145c307a6a
+19 1.0 0.5 WillBroke 14160 14260 17 1427 547e4a683939cf31
+20 1.0 0.5 WillBroke 16310 16410 19 1642 0653fd31b3fc42d8
+21 1.0 0.5 WillBroke 13860 13960 15 1397 abb9fb41943aed14
+22 1.0 0.5 WillBroke 11720 11820 14 1183 1174869087f230c6
+23 1.0 0.5 WillBroke 12260 12360 15 1237 d5074ba63114d34f
+24 1.0 0.5 WillBroke 12680 12780 15 1279 d075ca28021bcb2f
+25 1.0 0.5 WillBroke 14390 14490 18 1450 ca018f228e141313
+26 1.0 0.5 WillBroke 12970 13070 16 1308 3c559d5142622b8a
+27 1.0 0.5 WillBroke 12790 12890 15 1290 04d51fbe35ed5cd5
+28 1.0 0.5 WillBroke 12730 12830 15 1284 e32fd88365db7019
+29 1.0 0.5 WillBroke 12300 12400 15 1241 e865da9fc3e136dd
+30 1.0 0.5 WillBroke 12500 12600 15 1261 ee7b9626cecaa543
+31 1.0 0.5 WillBroke 12030 12130 15 1214 58cfcc93405f718b
+32 1.0 0.5 WillBroke 12240 12340 15 1235 4a7a33fc862b87b6
+33 1.0 0.5 WillBroke 16210 16310 19 1632 a4321c62d0942b51
+34 1.0 0.5 WillBroke 12580 12680 15 1269 8d8084c506399075
+35 1.0 0.5 WillBroke 13830 13930 16 1394 80eab6a1a91fe47e
+36 1.0 0.5 WillBroke 12960 13060 16 1307 a3bf0483a30b9832
+37 1.0 0.5 WillBroke 12250 12350 15 1236 591a92e077f7fb7e
+38 1.0 0.5 WillBroke 14040 14140 17 1415 a37a6c6e88296d4c
+39 1.0 0.5 WillBroke 11750 11850 14 1186 c8e91a1813d1cf7f
+40 1.0 0.5 WillBroke 13080 13180 14 1319 59ad5f054dacf9b5
+41 1.0 0.5 WillBroke 14600 14700 16 1471 d6c53c1e324f31bc
+42 1.0 0.5 WillBroke 13980 14080 17 1409 82171315883210d2
+43 1.0 0.5 WillBroke 12620 12720 15 1273 cf5f3536022121f2
+44 1.0 0.5 WillBroke 12180 12280 15 1229 c9f7c2acacdc2a4f
+45 1.0 0.5 WillBroke 11230 11330 14 1134 e4dcb7f2fca454aa
+46 1.0 0.5 WillBroke 13950 14050 17 1406 4f6631c906041c50
+47 1.0 0.5 WillBroke 14210 14310 17 1432 94971d9adbcce7f4
+48 1.0 0.5 WillBroke 14610 14710 16 1472 52b86bd6f4d01970
+49 1.0 0.5 WillBroke 15330 15430 17 1544 b76a0e4f82a8f139
+50 1.0 0.5 WillBroke 12690 12790 15 1280 f3859d8ebae145f7
+51 1.0 0.5 WillBroke 14540 14640 17 1465 d54f534dbfd8ac98
+52 1.0 0.5 WillBroke 13170 13270 16 1328 e3ba704a9ee1a898
+53 1.0 0.5 WillBroke 14450 14550 18 1456 09513ed8620db12f
+54 1.0 0.5 WillBroke 13500 13600 16 1361 fa700ae33783c44b
+55 1.0 0.5 WillBroke 15410 15510 18 1552 37ce852a8984b97a
+56 1.0 0.5 WillBroke 12670 12770 15 1278 138a00120ccb00fe
+57 1.0 0.5 WillBroke 14630 14730 17 1474 18f604c62fdf14cf
+58 1.0 0.5 WillBroke 13760 13860 16 1387 40a380177cc0fb2f
+59 1.0 0.5 WillBroke 13150 13250 15 1326 cbb58f0ec6aacce2
+60 1.0 0.5 WillBroke 14070 14170 17 1418 fdd65da97d503bea
+1 0.6 0.5 WillBroke 18150 18250 16 1826 6ba0eac35d362331
+2 0.6 0.5 WillBroke 17970 18070 16 1808 e9a49730ebc3284e
+3 0.6 0.5 WillBroke 20530 20630 17 2064 f35e11a268ee6e5b
+4 0.6 0.5 WillBroke 18050 18150 16 1816 7f4d381a70594785
+5 0.6 0.5 WillBroke 18850 18950 16 1896 2255227b0f0566a4
+6 0.6 0.5 WillBroke 18740 18840 18 1885 77671a7b01e433c1
+7 0.6 0.5 WillBroke 23130 23230 21 2324 6d6875964a164a26
+8 0.6 0.5 WillBroke 18450 18550 17 1856 89995e2334a69fc4
+9 0.6 0.5 WillBroke 17630 17730 16 1774 3a57554bfdae952c
+10 0.6 0.5 WillBroke 20780 20880 16 2089 92d0d3ee482673bb
+11 0.6 0.5 WillBroke 21820 21920 20 2193 499413f37856cc67
+12 0.6 0.5 WillBroke 17300 17400 15 1741 cf400e983b9ab384
+13 0.6 0.5 WillBroke 19160 19260 18 1927 cc9cd1d981969951
+14 0.6 0.5 WillBroke 22520 22620 21 2263 ed6838239b11bc75
+15 0.6 0.5 WillBroke 18130 18230 16 1824 d749947d1fa45774
+16 0.6 0.5 WillBroke 22710 22810 21 2282 bda734962c5606f0
+17 0.6 0.5 WillBroke 20110 20210 18 2022 35e19cd78e4681c5
+18 0.6 0.5 WillBroke 20680 20780 16 2079 044b17ae0c8f471d
+19 0.6 0.5 WillBroke 20600 20700 20 2071 6bc5d68ea6d37f58
+20 0.6 0.5 WillBroke 24210 24310 21 2432 a8ea7744a790f179
+21 0.6 0.5 WillBroke 20020 20120 15 2013 024dc742aba6d11e
+22 0.6 0.5 WillBroke 16590 16690 16 1670 1ed9990a7a83680d
+23 0.6 0.5 WillBroke 17460 17560 17 1757 2f5c8bb3f7fbce51
+24 0.6 0.5 WillBroke 18120 18220 17 1823 39e31936bdc74dca
+25 0.6 0.5 WillBroke 20980 21080 20 2109 0c545a97c49f67d0
+26 0.6 0.5 WillBroke 18610 18710 18 1872 b84cafd2a5e955fd
+27 0.6 0.5 WillBroke 18300 18400 17 1841 7610f4a37901d7da
+28 0.6 0.5 WillBroke 18190 18290 17 1830 87c68d8444be7fe2
+29 0.6 0.5 WillBroke 17520 17620 16 1763 64e7b957cc2182a1
+30 0.6 0.5 WillBroke 17850 17950 16 1796 b318302a3ff94a1b
+31 0.6 0.5 WillBroke 17100 17200 16 1721 ab156f4dcec9413a
+32 0.6 0.5 WillBroke 17430 17530 17 1754 3505a668df088e29
+33 0.6 0.5 WillBroke 24030 24130 21 2414 62dad0cd6de6c6ad
+34 0.6 0.5 WillBroke 17960 18060 16 1807 468f81ede64f7032
+35 0.6 0.5 WillBroke 19990 20090 17 2010 8425b945af3a5546
+36 0.6 0.5 WillBroke 18600 18700 18 1871 2ada8cd49c8d5762
+37 0.6 0.5 WillBroke 17440 17540 17 1755 a98e38b6442eaf84
+38 0.6 0.5 WillBroke 20440 20540 21 2055 7762c24c4c087ea3
+39 0.6 0.5 WillBroke 16640 16740 16 1675 948a96907d9eefc0
+40 0.6 0.5 WillBroke 18740 18840 15 1885 cf3d3003437065ba
+41 0.6 0.5 WillBroke 21260 21360 17 2137 42ef7102a413d1c0
+42 0.6 0.5 WillBroke 20280 20380 20 2039 dcf19acb186b9283
+43 0.6 0.5 WillBroke 18040 18140 17 1815 a2b7896cebd7012a
+44 0.6 0.5 WillBroke 17340 17440 17 1745 ae0d1f06637ac29e
+45 0.6 0.5 WillBroke 15820 15920 15 1593 34ed73b3ed021ee4
+46 0.6 0.5 WillBroke 20240 20340 20 2035 1327132bbc471b49
+47 0.6 0.5 WillBroke 20670 20770 19 2078 6ed62543a7d622f7
+48 0.6 0.5 WillBroke 21260 21360 16 2137 7852586cc5440810
+49 0.6 0.5 WillBroke 22500 22600 19 2261 e5cb75e99d5282f9
+50 0.6 0.5 WillBroke 18130 18230 17 1824 b6ab5edaaf877789
+51 0.6 0.5 WillBroke 21210 21310 19 2132 41ac950e5cfaa653
+52 0.6 0.5 WillBroke 18990 19090 19 1910 413ccf741adabd38
+53 0.6 0.5 WillBroke 21110 21210 21 2122 36abd4e8cfe6083a
+54 0.6 0.5 WillBroke 19460 19560 19 1957 cab475fe2176ba46
+55 0.6 0.5 WillBroke 22700 22800 21 2281 4621276ba4894fea
+56 0.6 0.5 WillBroke 18100 18200 17 1821 ec9a774751bdedbf
+57 0.6 0.5 WillBroke 21340 21440 18 2145 5709bbcab913e98c
+58 0.6 0.5 WillBroke 19910 20010 18 2002 d16492ba1669abb8
+59 0.6 0.5 WillBroke 18890 18990 17 1900 f36f53cb80836d5e
+60 0.6 0.5 WillBroke 20450 20550 20 2056 c118dd86c7e0945f
+1 0.8 0.0 WillBroke 10070 10170 10 1018 1914ad90455159e8
+2 0.8 0.0 WillBroke 9990 10090 10 1010 3d6287598c77d9e3
+3 0.8 0.0 WillBroke 11160 11260 10 1127 7476613d96868cc1
+4 0.8 0.0 WillBroke 10030 10130 10 1014 50107275381fd7aa
+5 0.8 0.0 WillBroke 10400 10500 10 1051 d287687d8bf0078e
+6 0.8 0.0 WillBroke 10340 10440 11 1045 6ce913c53b72daf4
+7 0.8 0.0 WillBroke 12300 12400 12 1241 bc0a4e85028ea794
+8 0.8 0.0 WillBroke 10210 10310 10 1032 9d817ecb6fe288ee
+9 0.8 0.0 WillBroke 9820 9920 10 993 92da81d6468ebe82
+10 0.8 0.0 WillBroke 11280 11380 10 1139 f2f9c86856025f04
+11 0.8 0.0 WillBroke 11730 11830 11 1184 9f0a0926039f3e52
+12 0.8 0.0 WillBroke 9690 9790 9 980 33b8c796b8fe56e5
+13 0.8 0.0 WillBroke 10530 10630 11 1064 bc70c2da7b3b974c
+14 0.8 0.0 WillBroke 12040 12140 12 1215 c95036c6977e1b59
+15 0.8 0.0 WillBroke 10080 10180 10 1019 373431a56c7b9101
+16 0.8 0.0 WillBroke 12130 12230 12 1224 02dcac6b7da6c93c
+17 0.8 0.0 WillBroke 10970 11070 11 1108 baed4dff515bc947
+18 0.8 0.0 WillBroke 11220 11320 10 1133 ed5b57045897960d
+19 0.8 0.0 WillBroke 11190 11290 11 1130 9e9829f5785c1567
+20 0.8 0.0 WillBroke 12780 12880 12 1289 b0ce6f3a04534a83
+21 0.8 0.0 WillBroke 10930 11030 10 1104 5f92a1c351fcaade
+22 0.8 0.0 WillBroke 9350 9450 9 946 685587a2ecb63f49
+23 0.8 0.0 WillBroke 9760 9860 10 987 46ca2993ce13d9b7
+24 0.8 0.0 WillBroke 10060 10160 10 1017 8bbb14c9c6edd738
+25 0.8 0.0 WillBroke 11360 11460 12 1147 ca7a2943fbf35fa7
+26 0.8 0.0 WillBroke 10290 10390 11 1040 c2615398937c44cf
+27 0.8 0.0 WillBroke 10140 10240 10 1025 2c11a0e93231978e
+28 0.8 0.0 WillBroke 10100 10200 10 1021 02996614f9d1b6ad
+29 0.8 0.0 WillBroke 9770 9870 10 988 ee1586d573ca55c9
+30 0.8 0.0 WillBroke 9930 10030 10 1004 cb05f8a9a91fd3fa
+31 0.8 0.0 WillBroke 9580 9680 10 969 e8ecae5902642a8d
+32 0.8 0.0 WillBroke 9740 9840 10 985 f136abd42fb6b90f
+33 0.8 0.0 WillBroke 12710 12810 12 1282 87209b5050bf4859
+34 0.8 0.0 WillBroke 9980 10080 10 1009 b910622b9c39d291
+35 0.8 0.0 WillBroke 10930 11030 10 1104 e910f01456aee3b6
+36 0.8 0.0 WillBroke 10290 10390 11 1040 2468ae1f05faa180
+37 0.8 0.0 WillBroke 9740 9840 10 985 bf0e779e9243fe83
+38 0.8 0.0 WillBroke 11110 11210 12 1122 cd1edafd69f799db
+39 0.8 0.0 WillBroke 9360 9460 10 947 0a9c9db826fd6fc3
+40 0.8 0.0 WillBroke 10350 10450 9 1046 8a695f2a7b77be08
+41 0.8 0.0 WillBroke 11500 11600 10 1161 773e9846d68e4563
+42 0.8 0.0 WillBroke 11050 11150 12 1116 971f9792bb5190a5
+43 0.8 0.0 WillBroke 10030 10130 10 1014 290e32ab22867eef
+44 0.8 0.0 WillBroke 9690 9790 10 980 abf81ab05a0351ab
+45 0.8 0.0 WillBroke 8970 9070 9 908 c51f9d6618059105
+46 0.8 0.0 WillBroke 11030 11130 11 1114 3eefac78a2ec93b0
+47 0.8 0.0 WillBroke 11210 11310 11 1132 c1f575d6e9da5621
+48 0.8 0.0 WillBroke 11500 11600 10 1161 cc56a243e423592f
+49 0.8 0.0 WillBroke 12040 12140 11 1215 ab73b8cd07be0649
+50 0.8 0.0 WillBroke 10080 10180 10 1019 5b3f678f2f519458
+51 0.8 0.0 WillBroke 11460 11560 11 1157 49df060130506ba9
+52 0.8 0.0 WillBroke 10440 10540 11 1055 a04eaacb8803cb78
+53 0.8 0.0 WillBroke 11410 11510 12 1152 47d7de117d48f625
+54 0.8 0.0 WillBroke 10700 10800 11 1081 2dc02e576db39ec7
+55 0.8 0.0 WillBroke 12120 12220 12 1223 b59afb6f495f92cc
+56 0.8 0.0 WillBroke 10050 10150 10 1016 96cd4b621eb75a64
+57 0.8 0.0 WillBroke 11520 11620 11 1163 6ace2627157a30f5
+58 0.8 0.0 WillBroke 10870 10970 11 1098 d24694742d029864
+59 0.8 0.0 WillBroke 10420 10520 10 1053 cb0148bdde051390
+60 0.8 0.0 WillBroke 11120 11220 11 1123 89dcecf0208bd4c5
+1 0.8 0.8 WillBroke 26100 26200 31 2621 facb758365f7865b
+2 0.8 0.8 WillBroke 25850 25950 31 2596 7d282a08b15832e4
+3 0.8 0.8 WillBroke 29980 30080 34 3009 f2ded9f2c282d18f
+4 0.8 0.8 WillBroke 25990 26090 31 2610 5bb9737062e3e1ff
+5 0.8 0.8 WillBroke 27260 27360 32 2737 4bd7db07086983d8
+6 0.8 0.8 WillBroke 27040 27140 34 2715 58790a7cd5034891
+7 0.8 0.8 WillBroke 34160 34260 43 3427 c3b1132c88b0087b
+8 0.8 0.8 WillBroke 26600 26700 32 2671 e4f42c7e9a769659
+9 0.8 0.8 WillBroke 25280 25380 31 2539 ae0029cabb1ecb76
+10 0.8 0.8 WillBroke 30440 30540 35 3055 075dfb3f39c9f414
+11 0.8 0.8 WillBroke 32040 32140 39 3215 6edcb217700a8f7c
+12 0.8 0.8 WillBroke 24790 24890 30 2490 f8491701247bcb39
+13 0.8 0.8 WillBroke 27710 27810 35 2782 cb475aee74befea5
+14 0.8 0.8 WillBroke 33180 33280 41 3329 8af0b8a0fd5e834b
+15 0.8 0.8 WillBroke 26070 26170 31 2618 e2fbd7aa00441616
+16 0.8 0.8 WillBroke 33480 33580 42 3359 cc06979bd8253d1c
+17 0.8 0.8 WillBroke 29220 29320 36 2933 34d06f9996dc6314
+18 0.8 0.8 WillBroke 30290 30390 35 3040 f30283d3d1284d9a
+19 0.8 0.8 WillBroke 29950 30050 38 3006 ed2ffeeb23e4d2c7
+20 0.8 0.8 WillBroke 35990 36090 44 3610 441d34847f7052a3
+21 0.8 0.8 WillBroke 29210 29310 33 2932 97b819d64521f3f1
+22 0.8 0.8 WillBroke 23650 23750 29 2376 4bece642126eda8e
+23 0.8 0.8 WillBroke 24990 25090 31 2510 707aeeeb6326f2a8
+24 0.8 0.8 WillBroke 26050 26150 32 2616 e019c2e195081ba6
+25 0.8 0.8 WillBroke 30630 30730 39 3074 4193242a4b0f92a4
+26 0.8 0.8 WillBroke 26800 26900 34 2691 ea4cd91c79d0dae5
+27 0.8 0.8 WillBroke 26360 26460 32 2647 41475b4e3dcc78b5
+28 0.8 0.8 WillBroke 26190 26290 32 2630 2812da5c40655627
+29 0.8 0.8 WillBroke 25110 25210 31 2522 f5cce351f754c3dc
+30 0.8 0.8 WillBroke 25630 25730 31 2574 da101fc4522fbef8
+31 0.8 0.8 WillBroke 24440 24540 30 2455 d1ed5841b8f3d2c7
+32 0.8 0.8 WillBroke 24950 25050 31 2506 7a853f4af1372d33
+33 0.8 0.8 WillBroke 35700 35800 43 3581 c19ba694b20e2224
+34 0.8 0.8 WillBroke 25830 25930 31 2594 1fe8515aa980c3e8
+35 0.8 0.8 WillBroke 29070 29170 35 2918 b471b626e0a26207
+36 0.8 0.8 WillBroke 26760 26860 34 2687 7b47afeb2bda4f09
+37 0.8 0.8 WillBroke 24960 25060 31 2507 70611ac9655b4130
+38 0.8 0.8 WillBroke 29720 29820 39 2983 29e31c8aedca1b66
+39 0.8 0.8 WillBroke 23720 23820 29 2383 e6b672c0d11de53f
+40 0.8 0.8 WillBroke 27150 27250 31 2726 228e1e1209860ccf
+41 0.8 0.8 WillBroke 31230 31330 36 3134 d8bd943c7794fb4d
+42 0.8 0.8 WillBroke 29450 29550 37 2956 99532fe0b5bbd56a
+43 0.8 0.8 WillBroke 25920 26020 32 2603 8c12e7bb65f2c9ec
+44 0.8 0.8 WillBroke 24790 24890 31 2490 c1e40d8406efd5e9
+45 0.8 0.8 WillBroke 22450 22550 28 2256 4ae97c637521edaf
+46 0.8 0.8 WillBroke 29410 29510 37 2952 7760a4f76f63ebb5
+47 0.8 0.8 WillBroke 30160 30260 37 3027 f062837cb5b49eb0
+48 0.8 0.8 WillBroke 31220 31320 36 3133 5e41f3871a485c72
+49 0.8 0.8 WillBroke 33200 33300 39 3331 bf6f87e6642eeed9
+50 0.8 0.8 WillBroke 26050 26150 32 2616 800841a85e80970f
+51 0.8 0.8 WillBroke 31020 31120 38 3113 54d06d44545aa4fb
+52 0.8 0.8 WillBroke 27410 27510 35 2752 c545900336cea749
+53 0.8 0.8 WillBroke 30780 30880 40 3089 7b14f9d5b0dabe0d
+54 0.8 0.8 WillBroke 28150 28250 35 2826 46db795b35f34c5d
+55 0.8 0.8 WillBroke 33490 33590 42 3360 c4760d6e42ad2e59
+56 0.8 0.8 WillBroke 26030 26130 32 2614 0503e5395eaff483
+57 0.8 0.8 WillBroke 31290 31390 37 3140 b7b8ab30e565b2f9
+58 0.8 0.8 WillBroke 28940 29040 35 2905 4527feae8a218446
+59 0.8 0.8 WillBroke 27310 27410 33 2742 518030c576b6fcbe
+60 0.8 0.8 WillBroke 29750 29850 38 2986 53e33f04a6f4a7af
+1 0.12 0.5 Endured -1 120000 0 12001 a4d66728d54aad20
+2 0.12 0.5 Endured -1 120000 0 12001 0f86d5191fd466e2
+3 0.12 0.5 Endured -1 120000 0 12001 842a665c4588e215
+4 0.12 0.5 Endured -1 120000 0 12001 930164c1ef89e1d1
+5 0.12 0.5 Endured -1 120000 0 12001 a3c5f53000dc35b6
+6 0.12 0.5 Endured -1 120000 0 12001 6f2b82eed827ff94
+7 0.12 0.5 Endured -1 120000 0 12001 e8ccd63c058aac7e
+8 0.12 0.5 Endured -1 120000 0 12001 ce987e8b1ff40739
+9 0.12 0.5 Endured -1 120000 0 12001 311b03a75aa8774d
+10 0.12 0.5 Endured -1 120000 0 12001 335c11e8d64fdd7a
+11 0.12 0.5 Endured -1 120000 0 12001 ec84541c1a1c2b9e
+12 0.12 0.5 Endured -1 120000 0 12001 23d1461c11d6eecf
+13 0.12 0.5 Endured -1 120000 0 12001 e21fc8da5df2c979
+14 0.12 0.5 Endured -1 120000 0 12001 8c16fb1b49916ce9
+15 0.12 0.5 Endured -1 120000 0 12001 596e31a87d587289
+16 0.12 0.5 Endured -1 120000 0 12001 53e9f6c0cdc92586
+17 0.12 0.5 Endured -1 120000 0 12001 32a5669012845805
+18 0.12 0.5 Endured -1 120000 0 12001 bf03e03c67b40e3b
+19 0.12 0.5 Endured -1 120000 0 12001 178a29a6f8375006
+20 0.12 0.5 Endured -1 120000 0 12001 59c536047786a192
+21 0.12 0.5 Endured -1 120000 0 12001 b356add08dab94a5
+22 0.12 0.5 Endured -1 120000 0 12001 99922c10b6b32d2b
+23 0.12 0.5 Endured -1 120000 0 12001 e280c89341344aa7
+24 0.12 0.5 Endured -1 120000 0 12001 fa0726e3c32d99d8
+25 0.12 0.5 Endured -1 120000 0 12001 f9f241118be9983e
+26 0.12 0.5 Endured -1 120000 0 12001 80a50b45c9d799c0
+27 0.12 0.5 Endured -1 120000 0 12001 771cfaf72c64438b
+28 0.12 0.5 Endured -1 120000 0 12001 fbbd6f2007051076
+29 0.12 0.5 Endured -1 120000 0 12001 c08d546694da4a7e
+30 0.12 0.5 Endured -1 120000 0 12001 9df481a0c2cdee11
+31 0.12 0.5 Endured -1 120000 0 12001 ae9f606dafebfa1e
+32 0.12 0.5 Endured -1 120000 0 12001 06e696404e9256de
+33 0.12 0.5 Endured -1 120000 0 12001 066aafcddab6ef0e
+34 0.12 0.5 Endured -1 120000 0 12001 0833cb592b8138cd
+35 0.12 0.5 Endured -1 120000 0 12001 72f9ccaea0637ad4
+36 0.12 0.5 Endured -1 120000 0 12001 e0d1c64bc8e0fc48
+37 0.12 0.5 Endured -1 120000 0 12001 b70ad94cf12adce0
+38 0.12 0.5 Endured -1 120000 0 12001 ff435f0887180b71
+39 0.12 0.5 Endured -1 120000 0 12001 8da9c4370b584012
+40 0.12 0.5 Endured -1 120000 0 12001 74f9885c1a541501
+41 0.12 0.5 Endured -1 120000 0 12001 d4e11eb98b23c59a
+42 0.12 0.5 Endured -1 120000 0 12001 4289f6ae3fe60c0d
+43 0.12 0.5 Endured -1 120000 0 12001 f9595ac5caec95c2
+44 0.12 0.5 Endured -1 120000 0 12001 bc590d5d1b609c7e
+45 0.12 0.5 Endured -1 120000 0 12001 efdb32b1f8fb14ca
+46 0.12 0.5 Endured -1 120000 0 12001 6b1ed857ef93f9e7
+47 0.12 0.5 Endured -1 120000 0 12001 4dcb3fb4a7fb1808
+48 0.12 0.5 Endured -1 120000 0 12001 f11072ebdaf3fe06
+49 0.12 0.5 Endured -1 120000 0 12001 b2b83bbf20dcb8da
+50 0.12 0.5 Endured -1 120000 0 12001 1c976596616ad5bc
+51 0.12 0.5 Endured -1 120000 0 12001 3c9322031aac9a32
+52 0.12 0.5 Endured -1 120000 0 12001 a96cd8ca41cfa13a
+53 0.12 0.5 Endured -1 120000 0 12001 a215b789ed222a7d
+54 0.12 0.5 Endured -1 120000 0 12001 3be6e39bfa4d5424
+55 0.12 0.5 Endured -1 120000 0 12001 b40fe851ccb51114
+56 0.12 0.5 Endured -1 120000 0 12001 3eb672b6f8f9df4b
+57 0.12 0.5 Endured -1 120000 0 12001 0cc56de0d1df332a
+58 0.12 0.5 Endured -1 120000 0 12001 1c46b092e7a9f5fa
+59 0.12 0.5 Endured -1 120000 0 12001 9abf165506073db5
+60 0.12 0.5 Endured -1 120000 0 12001 d9913a1ed7920a47
+1 0.2 0.5 WillBroke 61550 61650 0 6166 4eb7b5f041058c3a
+2 0.2 0.5 WillBroke 60770 60870 0 6088 6adf5a0713405867
+3 0.2 0.5 WillBroke 73080 73180 0 7319 3b218fb3f2750d00
+4 0.2 0.5 WillBroke 60910 61010 0 6102 e6fc3dd13c4f4f88
+5 0.2 0.5 WillBroke 64890 64990 0 6500 13eb57c707621354
+6 0.2 0.5 WillBroke 65330 65430 0 6544 5d12aa022ce881c2
+7 0.2 0.5 WillBroke 89140 89240 0 8925 722956c2506d94ac
+8 0.2 0.5 WillBroke 63320 63420 0 6343 4c8556996b77c4d2
+9 0.2 0.5 WillBroke 59100 59200 0 5921 4fdeaa907d37b76a
+10 0.2 0.5 WillBroke 74460 74560 0 7457 e6a7d0c99e99df1d
+11 0.2 0.5 WillBroke 81360 81460 0 8147 8bb48eff4337aca3
+12 0.2 0.5 WillBroke 57220 57320 0 5733 5c1f16f19f35355c
+13 0.2 0.5 WillBroke 68020 68120 0 6813 7728601e0be34b58
+14 0.2 0.5 WillBroke 85960 86060 0 8607 a16720cf9093a2ba
+15 0.2 0.5 WillBroke 61270 61370 0 6138 84ad9eee8ece8cab
+16 0.2 0.5 WillBroke 86760 86860 0 8687 f30b663ba19039fa
+17 0.2 0.5 WillBroke 72150 72250 0 7226 adb357df88b33dc8
+18 0.2 0.5 WillBroke 73890 73990 0 7400 fbfa7d31601e6aa1
+19 0.2 0.5 WillBroke 75870 75970 0 7598 e142af5c45ee0be2
+20 0.2 0.5 WillBroke 94760 94860 0 9487 4c708580624a1d46
+21 0.2 0.5 WillBroke 70030 70130 0 7014 13ad55e6f3130be3
+22 0.2 0.5 WillBroke 53850 53950 0 5396 79f3bb316c0eaf85
+23 0.2 0.5 WillBroke 58520 58620 0 5863 9f0c6f85419ae6dd
+24 0.2 0.5 WillBroke 61550 61650 0 6166 f39221687519b487
+25 0.2 0.5 WillBroke 77990 78090 0 7810 10d4fc69f97b26d8
+26 0.2 0.5 WillBroke 64630 64730 0 6474 cc05ed3304923a87
+27 0.2 0.5 WillBroke 62610 62710 0 6272 39625ac195ca6345
+28 0.2 0.5 WillBroke 61980 62080 0 6209 1689dbf84daa149b
+29 0.2 0.5 WillBroke 58650 58750 0 5876 63711e804c1fd959
+30 0.2 0.5 WillBroke 60210 60310 0 6032 6750a2c42c1feb9b
+31 0.2 0.5 WillBroke 56770 56870 0 5688 efe09e0087130ba4
+32 0.2 0.5 WillBroke 58580 58680 0 5869 48e0e13604b41a59
+33 0.2 0.5 WillBroke 93390 93490 0 9350 0f7b98fadce89c49
+34 0.2 0.5 WillBroke 60530 60630 0 6064 7a4f7f1a4f63374c
+35 0.2 0.5 WillBroke 70790 70890 0 7090 85f8a9ddf9d30a53
+36 0.2 0.5 WillBroke 64920 65020 0 6503 73db5f07ae7671ad
+37 0.2 0.5 WillBroke 58250 58350 0 5836 09f7c4eb8062265a
+38 0.2 0.5 WillBroke 75920 76020 0 7603 2414eda9e29d7e3e
+39 0.2 0.5 WillBroke 54080 54180 0 5419 8668a6e52104341a
+40 0.2 0.5 WillBroke 63980 64080 0 6409 9b0483b182117ef2
+41 0.2 0.5 WillBroke 77210 77310 0 7732 1177a13eb3cc229b
+42 0.2 0.5 WillBroke 74160 74260 0 7427 666d37658845da58
+43 0.2 0.5 WillBroke 61350 61450 0 6146 871d25bd76ae94c8
+44 0.2 0.5 WillBroke 58190 58290 0 5830 f1e96621098bc360
+45 0.2 0.5 WillBroke 50280 50380 0 5039 c2f86a90a197eb00
+46 0.2 0.5 WillBroke 73840 73940 0 7395 17cf31b97a0d1671
+47 0.2 0.5 WillBroke 75630 75730 0 7574 8538745e7a5e1ff6
+48 0.2 0.5 WillBroke 76850 76950 0 7696 b6525c3189927f9a
+49 0.2 0.5 WillBroke 84340 84440 0 8445 8590d59e44ff5fd4
+50 0.2 0.5 WillBroke 61880 61980 0 6199 2e5718c722577755
+51 0.2 0.5 WillBroke 77980 78080 0 7809 8f8ccdb15763c750
+52 0.2 0.5 WillBroke 67470 67570 0 6758 ac01f6ce963b5334
+53 0.2 0.5 WillBroke 79110 79210 0 7922 6ea0bdfb3703d02a
+54 0.2 0.5 WillBroke 69530 69630 0 6964 fb7b9ac715a66a05
+55 0.2 0.5 WillBroke 87170 87270 0 8728 07bba7c2cd21b7b7
+56 0.2 0.5 WillBroke 61450 61550 0 6156 3136df798ca68e9d
+57 0.2 0.5 WillBroke 78000 78100 0 7811 d6a4a321a0936ef2
+58 0.2 0.5 WillBroke 71110 71210 0 7122 e7dfb64e0e60fff6
+59 0.2 0.5 WillBroke 65890 65990 0 6600 970e46a63d649f1d
+60 0.2 0.5 WillBroke 75320 75420 0 7543 cfedd17a42366fca
diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs
new file mode 100644
index 0000000..b0eea69
--- /dev/null
+++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs
@@ -0,0 +1,263 @@
+using Lodur;
+using Lodur.Body.Ymir;
+using Ymir.Box3D;
+
+namespace Lodur.Tests;
+
+///
+/// The pain box on the real body: a ground, a static stool welded to the pelvis (the PD ragdoll cannot balance for
+/// 15 s), the ragdoll, a stimulus box around the right hand's hold point, and an Actor at 1/120 s driving the
+/// ragdoll through strengths and targets only. The game (this scenario) owns the world and steps it.
+///
+internal sealed class ConnectedPainBox : IDisposable
+{
+ public const double Dt = 1.0 / 120.0;
+ public static readonly (float X, float Y, float Z) Box = (-0.21f, 1.19f, 0.46f);
+
+ public readonly Box3DSoaWorld World;
+ public readonly HumanoidRagdoll Ragdoll;
+ public readonly Actor Actor;
+ public readonly BoxStimulus[] Sources = { new BoxStimulus(Box.X, Box.Y, Box.Z, 0.12f, 0.12f, 0.12f) };
+ public readonly float[] X = new float[HumanoidRagdoll.RegionCount], Y = new float[HumanoidRagdoll.RegionCount], Z = new float[HumanoidRagdoll.RegionCount];
+ public readonly float[] Strength = new float[HumanoidRagdoll.MuscleCount];
+ public readonly Quat[] Target = new Quat[HumanoidRagdoll.MuscleCount];
+ private SplitMix64 _rng;
+
+ 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);
+ var stool = World.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
+ Ragdoll = HumanoidRagdoll.Build(World, (0f, 0f), firstStableId: 100);
+ World.AddJoint(Box3DSoaJointKind.Weld, stool, Ragdoll.BodyLane(Limb.Pelvis), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
+
+ var holdPose = new Quat[HumanoidRagdoll.MuscleCount];
+ var withdrawPose = new Quat[HumanoidRagdoll.MuscleCount];
+ Array.Fill(holdPose, Quat.Identity);
+ Array.Fill(withdrawPose, Quat.Identity);
+ holdPose[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, -1.0f);
+ holdPose[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -0.6f);
+ withdrawPose[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
+ withdrawPose[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f);
+
+ _rng = new SplitMix64(seed);
+ var gain = 1.0 + 0.2 * _rng.NextSigned();
+ var drain = 1.0 + 0.2 * _rng.NextSigned();
+ // The pain box as a Brain: hold against the reflex until the will breaks, then release into the withdraw pose.
+ var tunables = hold ?? new HoldParameters();
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec
+ {
+ Id = "objective", Priority = 0.0, Pull = 0.5,
+ Behaviour = new PoseBehaviour { Keys = new[] { holdPose }, FlinchPose = withdrawPose, Hold = tunables },
+ },
+ new GoalSpec
+ {
+ Id = "release", Priority = 1.0, Pull = 0.5, InvoluntarySeconds = double.PositiveInfinity,
+ When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
+ Behaviour = new PoseBehaviour
+ {
+ Keys = new[] { withdrawPose }, FlinchPose = withdrawPose,
+ Hold = tunables with { FlinchGain = 0.0, StrainShake = 0.0 },
+ },
+ },
+ },
+ };
+ Actor = new Actor(Dt, HumanoidRagdoll.RegionCount, new NerveParameters { Gain = gain }, new WithdrawalParameters(),
+ (driveTunables ?? new DriveParameters()) with { DrainTrait = drain }, brain);
+ }
+
+ public Box3DSoaView View => World.View;
+
+ /// Right hand point now.
+ public (float X, float Y, float Z) Hand
+ {
+ get { Ragdoll.ReadRegions(X, Y, Z); return (X[(int)Region.HandR], Y[(int)Region.HandR], Z[(int)Region.HandR]); }
+ }
+
+ public bool HandInBox => Sources[0].Contains(Hand.X, Hand.Y, Hand.Z);
+
+ /// One tick: the game writes the box intensity, the body reports its regions, the Actor decides, the body is driven, the world steps.
+ public TickEvents Tick()
+ {
+ var tick = Actor.TickCount;
+ var ramp = Math.Min(1.0, tick * Dt / 2.0);
+ Sources[0].Intensity = Math.Max(0.0, 0.8 * ramp * (1.0 + 0.1 * _rng.NextSigned()));
+ Ragdoll.ReadRegions(X, Y, Z);
+ var events = Actor.Tick(X, Y, Z, Sources, Strength, Target);
+ Ragdoll.Drive(Strength, Target);
+ World.Step((float)Dt, 4);
+ return events;
+ }
+
+ public void Dispose() => World.Dispose();
+}
+
+public sealed class ConnectedPainBoxTests
+{
+ private static float Dist((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
+ MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
+
+ [Fact]
+ public void ReadRegions_puts_the_hands_at_the_lower_arm_tips_at_the_creation_pose()
+ {
+ using var s = new RagdollScenario(seed: 1);
+ var x = new float[HumanoidRagdoll.RegionCount]; var y = new float[HumanoidRagdoll.RegionCount]; var z = new float[HumanoidRagdoll.RegionCount];
+ s.Ragdoll.ReadRegions(x, y, z);
+ Assert.Equal(0.21f, x[(int)Region.HandL], 3);
+ Assert.Equal(-0.21f, x[(int)Region.HandR], 3);
+ Assert.Equal(0.96f, y[(int)Region.HandR], 3);
+ Assert.Equal(0f, z[(int)Region.HandR], 3);
+ Assert.Equal(0f, x[(int)Region.Head], 3); // the head body's centre, within a millimetre
+ Assert.Equal(1.74f, y[(int)Region.Head], 3);
+ Assert.Equal(0f, z[(int)Region.Head], 3);
+ Assert.Throws(() => s.Ragdoll.ReadRegions(new float[1], y, z));
+ }
+
+ [Fact]
+ public void ReadRegions_allocates_nothing()
+ {
+ using var s = new RagdollScenario(seed: 1);
+ var x = new float[HumanoidRagdoll.RegionCount]; var y = new float[HumanoidRagdoll.RegionCount]; var z = new float[HumanoidRagdoll.RegionCount];
+ s.Ragdoll.ReadRegions(x, y, z);
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 1000; i++) s.Ragdoll.ReadRegions(x, y, z);
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ }
+
+ 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, DriveParameters? drive = null)
+ {
+ 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);
+ for (long i = 0; i < max && withdrew < 0; i++)
+ {
+ var e = s.Tick();
+ if ((e & TickEvents.Flinch) != 0) t.Flinches.Add(i);
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ t.Hand.Add((i, s.Hand, s.HandInBox));
+ }
+ // Keep running a little so the broken will has time to pull the arm out.
+ for (var k = 0; k < 60; k++)
+ {
+ s.Tick();
+ t.Hand.Add((t.Hand.Count, s.Hand, s.HandInBox));
+ }
+ return t with { Broke = broke, Withdrew = withdrew, Hash = RagdollScenario.HashOf(s.World) };
+ }
+
+ private static readonly (float X, float Y, float Z) Centre = ConnectedPainBox.Box;
+ private const int Hz = 120;
+
+ [Fact]
+ public void The_reflex_leaks_through_real_muscle_strength_and_the_broken_will_pulls_the_arm_out()
+ {
+ var t = Run(seed: 1);
+ Assert.True(t.Broke > 0, "the will never broke");
+ Assert.True(t.Flinches.Count > 0);
+
+ // The hand stays in the box until the will breaks (from 2 s on: before that the arm is still swinging up into it).
+ for (var i = 2 * Hz; i < t.Broke; i++) Assert.True(t.Hand[i].InBox, $"hand left the box at tick {i}, will broke at {t.Broke}");
+
+ // A flinch moves it: within 200 ms of some Flinch the hand is over 2.3 cm from its hold point (the box centre).
+ var moved = t.Flinches.Any(f => t.Hand.Skip((int)f).Take(Hz / 5 + 1).Any(h => Dist(h.Hand, Centre) > 0.023f));
+ Assert.True(moved, "no flinch moved the hand over 2.3 cm from the hold point");
+
+ // The broken will pulls it out within 300 ms.
+ Assert.Contains(t.Hand.Skip((int)t.Broke).Take(Hz * 3 / 10 + 1), h => !h.InBox);
+ }
+
+ [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()
+ {
+ // 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.
+ for (var i = 3 * Hz; i < plain.Broke; i++) Assert.True(Dist(plain.Hand[i].Hand, Centre) <= 0.023f, $"drift {Dist(plain.Hand[i].Hand, Centre)} at tick {i}");
+
+ // With the leak, at the last flinch the hand is over 2.3 cm from where the leak-free arm is at the same tick.
+ var last = (int)full.Flinches[^1];
+ 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();
+ return seg.Max() - seg.Min();
+ }
+
+ [Fact]
+ public void Strain_shows_as_a_visible_shake_of_the_hand_which_the_shipped_amplitude_makes_and_zero_does_not()
+ {
+ // Seconds 8 to 13 of seed 1: strain is about 3, the will has not broken (it breaks at 14.75 s). Measured at the
+ // shipped StrainShake 0.03 / ShakeHz 3.5: 3.9-4.7 cm peak to peak in hand height per second; at 0, 0.3-0.7 cm.
+ var shaking = Run(seed: 1, new HoldParameters(), maxSeconds: 16.0);
+ var still = Run(seed: 1, new HoldParameters { StrainShake = 0.0 }, maxSeconds: 16.0);
+ for (var s = 8; s <= 13; s++)
+ {
+ Assert.True(VerticalPeakToPeak(shaking, s) > 0.03f, $"shipped shake only {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}");
+ Assert.True(VerticalPeakToPeak(shaking, s) < 0.07f, $"shipped shake is {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}, more than a strain tremor");
+ Assert.True(VerticalPeakToPeak(still, s) < 0.015f, $"no shake still moved {VerticalPeakToPeak(still, s)} m in second {s}");
+ }
+ }
+
+ [Fact]
+ public void The_same_seed_twice_gives_the_same_events_and_the_same_world_state_hash()
+ {
+ var a = Run(seed: 1);
+ var b = Run(seed: 1);
+ Assert.Equal(a.Flinches, b.Flinches);
+ Assert.Equal(a.Broke, b.Broke);
+ Assert.Equal(a.Withdrew, b.Withdrew);
+ Assert.Equal(a.Hash, b.Hash);
+ Assert.NotEqual(a.Hash, Run(seed: 2).Hash);
+ }
+
+ private static ulong HandTrackHash(Timeline t)
+ {
+ var h = 14695981039346656037ul;
+ foreach (var (tick, hand, inBox) in t.Hand)
+ {
+ foreach (var f in new[] { hand.X, hand.Y, hand.Z })
+ {
+ h ^= (uint)BitConverter.SingleToInt32Bits(f);
+ h *= 1099511628211ul;
+ }
+ h ^= inBox ? 1ul : 0ul;
+ h *= 1099511628211ul;
+ }
+ return h;
+ }
+
+ [Fact]
+ public void Seed_1_to_16_seconds_replays_the_world_the_break_and_the_deliberate_switch_recorded_at_the_will_mix()
+ {
+ // 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=a0fafe85c80e98f7 world=83155f2abf0e7e91",
+ $"broke={t.Broke} withdrew={t.Withdrew} flinches={t.Flinches.Count} hand={HandTrackHash(t):x16} world={t.Hash:x16}");
+ }
+}
diff --git a/tests/Lodur.Tests/RagdollScenario.cs b/tests/Lodur.Tests/RagdollScenario.cs
index aebfbcc..0c75a89 100644
--- a/tests/Lodur.Tests/RagdollScenario.cs
+++ b/tests/Lodur.Tests/RagdollScenario.cs
@@ -75,17 +75,20 @@ internal sealed class RagdollScenario : IDisposable
return (lin, ang);
}
- /// FNV-1a 64 over every body and joint state lane, byte for byte, in lane order.
- public ulong StateHash()
+ /// FNV-1a 64 over every body and joint state lane of this scenario's world.
+ public ulong StateHash() => HashOf(World);
+
+ /// FNV-1a 64 over every body and joint state lane of any world.
+ public static ulong HashOf(Box3DSoaWorld world)
{
- var v = World.View;
+ var v = world.View;
var h = 14695981039346656037ul;
void Bytes(ReadOnlySpan b)
{
foreach (var x in b) { h ^= x; h *= 1099511628211ul; }
}
void F(ReadOnlySpan lane) => Bytes(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
- Bytes(System.Runtime.InteropServices.MemoryMarshal.AsBytes(BitConverter.GetBytes(World.StepCount).AsSpan()));
+ Bytes(System.Runtime.InteropServices.MemoryMarshal.AsBytes(BitConverter.GetBytes(world.StepCount).AsSpan()));
F(v.PositionX); F(v.PositionY); F(v.PositionZ);
F(v.RotationX); F(v.RotationY); F(v.RotationZ); F(v.RotationW);
F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ);
diff --git a/tools/pain-box-golden/PainBoxGolden.csproj b/tools/pain-box-golden/PainBoxGolden.csproj
new file mode 100644
index 0000000..f8c74ed
--- /dev/null
+++ b/tools/pain-box-golden/PainBoxGolden.csproj
@@ -0,0 +1,16 @@
+
+
+
+
+ Exe
+ net10.0
+ enable
+ disable
+
+
+
+
+
+
+
diff --git a/tools/pain-box-golden/Program.cs b/tools/pain-box-golden/Program.cs
new file mode 100644
index 0000000..5db904d
--- /dev/null
+++ b/tools/pain-box-golden/Program.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Globalization;
+using System.IO;
+using BadDay.Core;
+
+// One row per (intensity, pull, seed): the outcome of BadDaySimulator's PainBoxSimulation at 9f59764 with
+// SampleEverySeconds 0.01, so the timeline holds one Sample row per tick, and an FNV-1a 64 hash of that
+// per-tick stream (stimulus, pain, strain, resolve as raw double bits, then the goal byte).
+var settings = new (double Intensity, double Pull)[]
+{
+ (0.8, 0.5), (1.0, 0.5), (0.6, 0.5), (0.8, 0.0), (0.8, 0.8), (0.12, 0.5), (0.2, 0.5),
+};
+const int Seeds = 60;
+
+using var w = new StreamWriter(args[0], false, new System.Text.UTF8Encoding(false)) { NewLine = "\n" };
+w.WriteLine("# Generated by tools/pain-box-golden/generate.sh from BadDaySimulator 9f59764 PainBoxSimulation (tick 10 ms, one sample row per tick). Do not edit.");
+w.WriteLine("# seed intensity pull outcome break_ms end_ms flinches ticks hash");
+foreach (var (intensity, pull) in settings)
+{
+ for (ulong seed = 1; seed <= Seeds; seed++)
+ {
+ var p = new PainBoxParameters { BoxIntensity = intensity, ObjectivePull = pull, SampleEverySeconds = 0.01 };
+ var r = PainBoxSimulation.Run(p, seed);
+ var h = 14695981039346656037ul;
+ void Byte(byte b) { h ^= b; h *= 1099511628211ul; }
+ void Double(double d) { foreach (var b in BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(d))) Byte(b); }
+ long ticks = 0;
+ foreach (var e in r.Timeline)
+ {
+ if (e.Kind != EntryKind.Sample) continue;
+ ticks++;
+ Double(e.Stimulus); Double(e.Pain); Double(e.Strain); Double(e.Resolve);
+ Byte((byte)e.Goal);
+ }
+ w.WriteLine(string.Join(' ',
+ seed.ToString(CultureInfo.InvariantCulture),
+ intensity.ToString("0.0#", CultureInfo.InvariantCulture),
+ pull.ToString("0.0#", CultureInfo.InvariantCulture),
+ r.Outcome,
+ (r.TimeToBreakMs ?? -1).ToString(CultureInfo.InvariantCulture),
+ r.EndMs.ToString(CultureInfo.InvariantCulture),
+ r.Flinches.ToString(CultureInfo.InvariantCulture),
+ ticks.ToString(CultureInfo.InvariantCulture),
+ h.ToString("x16", CultureInfo.InvariantCulture)));
+ }
+}
diff --git a/tools/pain-box-golden/generate.sh b/tools/pain-box-golden/generate.sh
new file mode 100644
index 0000000..14b1ad6
--- /dev/null
+++ b/tools/pain-box-golden/generate.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Regenerates tests/Lodur.Core.Tests/pain-box-golden.tsv from Bad Day Simulator's pain box at 9f59764.
+# Usage: tools/pain-box-golden/generate.sh
+set -euo pipefail
+bds="${1:?path to a BadDaySimulator checkout at 9f59764}"
+want=9f597647a608a6c6e44473cc9f1399983de14616
+have="$(git -C "$bds" rev-parse HEAD)"
+[ "$have" = "$want" ] || { echo "BadDaySimulator is at $have, need $want" >&2; exit 1; }
+[ -z "$(git -C "$bds" status --porcelain -- src)" ] || { echo "BadDaySimulator has local changes under src/; the table must come from $want as committed" >&2; exit 1; }
+here="$(cd "$(dirname "$0")" && pwd)"
+dotnet run --project "$here/PainBoxGolden.csproj" -p:BdsRoot="$(cd "$bds" && pwd -W 2>/dev/null || pwd)" -- "$here/../../tests/Lodur.Core.Tests/pain-box-golden.tsv"