From d23683c8d174c07a32fc57faa99995e55b8871dc Mon Sep 17 00:00:00 2001 From: Nibu Date: Fri, 6 Nov 2026 19:23:48 +0000 Subject: [PATCH 01/47] docs: MotionBricks fit survey Licences (quoted from the NVIDIA Open Model Agreement), training-data provenance, runtime needs, pose format, tracker sketch, verdict. Co-Authored-By: Claude Sonnet 5.5 --- docs/notes/motionbricks-fit.md | 249 +++++++++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 docs/notes/motionbricks-fit.md diff --git a/docs/notes/motionbricks-fit.md b/docs/notes/motionbricks-fit.md new file mode 100644 index 0000000..42daff7 --- /dev/null +++ b/docs/notes/motionbricks-fit.md @@ -0,0 +1,249 @@ +# 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's `NOTICE` file is 14 bytes at + this commit, so check what it says before shipping anything.) 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 `NOTICE` carries the attribution line (the file is 14 bytes at + `54fc563`), and what ships in the HF checkpoint repos. +- 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. From aa59b6887b0184fab969ce7e198bcd676311d4dd Mon Sep 17 00:00:00 2001 From: Nibu Date: Fri, 6 Nov 2026 19:23:58 +0000 Subject: [PATCH 02/47] docs: correct NOTICE finding in MotionBricks note The 14-byte file was a 404 body; the repo has no NOTICE. Co-Authored-By: Claude Sonnet 5.5 --- docs/notes/motionbricks-fit.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/notes/motionbricks-fit.md b/docs/notes/motionbricks-fit.md index 42daff7..088ea84 100644 --- a/docs/notes/motionbricks-fit.md +++ b/docs/notes/motionbricks-fit.md @@ -66,8 +66,9 @@ Section numbers did not survive the page; clauses are cited by heading. 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's `NOTICE` file is 14 bytes at - this commit, so check what it says before shipping anything.) You may add + 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 @@ -235,8 +236,8 @@ or Lodur work that exists whether or not MotionBricks is used. - 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 `NOTICE` carries the attribution line (the file is 14 bytes at - `54fc563`), and what ships in the HF checkpoint repos. +- 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. From fd7afc11746000c88e5d58268686fdad7b2bf5ca Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:42:36 +0100 Subject: [PATCH 03/47] Lodur.Core: perception, withdrawal reflex, drive and a hold-against-reflex stand-in, run by Actor Layers 1-3 and a layer-4 stand-in move in from the pain box (BadDaySimulator PainBoxSimulation.cs at 9f59764), keeping its double arithmetic and in-tick order. Actor owns one character's nervous state and runs perception, reflex, drive, behaviour once per tick from caller-owned spans into caller-owned spans; it allocates only in its constructor and never touches physics. Quat gains Nlerp. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Actor.cs | 114 +++++++++++++++++++++++++++ src/Lodur.Core/DriveState.cs | 59 ++++++++++++++ src/Lodur.Core/HoldAgainstReflex.cs | 81 ++++++++++++++++++++ src/Lodur.Core/IsExternalInit.cs | 7 ++ src/Lodur.Core/PdMuscle.cs | 12 +++ src/Lodur.Core/Perception.cs | 115 ++++++++++++++++++++++++++++ src/Lodur.Core/WithdrawalReflex.cs | 57 ++++++++++++++ 7 files changed, 445 insertions(+) create mode 100644 src/Lodur.Core/Actor.cs create mode 100644 src/Lodur.Core/DriveState.cs create mode 100644 src/Lodur.Core/HoldAgainstReflex.cs create mode 100644 src/Lodur.Core/IsExternalInit.cs create mode 100644 src/Lodur.Core/Perception.cs create mode 100644 src/Lodur.Core/WithdrawalReflex.cs diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs new file mode 100644 index 0000000..b5ea509 --- /dev/null +++ b/src/Lodur.Core/Actor.cs @@ -0,0 +1,114 @@ +using System; + +namespace Lodur +{ + /// What happened on one tick. + [Flags] + public enum TickEvents + { + None = 0, + /// A reflex flinched while the will still held. + Flinch = 1, + /// Resolve reached zero this tick. + WillBroke = 2, + /// Deliberate behaviour took over, the withdrawal latency after the will broke. + Withdrew = 4, + } + + /// + /// One character's nervous state and the per-tick order: perception, reflex, drive, behaviour. The caller + /// supplies one point per body region, the game's stimulus sources, and the spans the behaviour writes its + /// strengths and targets into; the Actor writes nothing else of the caller's and never touches physics. + /// Everything is allocated in the constructor, and the same inputs give the same outputs. + /// + public sealed class Actor + { + private readonly double _dt; + private readonly DriveParameters _driveP; + private readonly long _withdrawLatency; + private readonly Perception _perception; + private readonly WithdrawalReflex[] _reflexes; + private readonly HoldAgainstReflex _behaviour; + private DriveState _drive = DriveState.Fresh; + private long _tick; + private long _withdrawTick = -1; + private bool _withdrew; + + public Actor( + double tickSeconds, int regionCount, + NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, HoldParameters hold, + ReadOnlySpan holdPose, ReadOnlySpan withdrawPose) + { + _dt = tickSeconds; + _driveP = drive; + _withdrawLatency = Math.Max(1, (long)Math.Round(withdrawal.LatencySeconds / tickSeconds)); + _perception = new Perception(nerve, tickSeconds, regionCount); + _reflexes = new WithdrawalReflex[regionCount]; + for (var r = 0; r < regionCount; r++) + { + _reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds); + } + + _behaviour = new HoldAgainstReflex(hold, holdPose, withdrawPose); + } + + public int RegionCount => _reflexes.Length; + + /// Ticks run so far. + public long TickCount => _tick; + + /// A snapshot of the drive; nothing but writes it. + public DriveState Drive => _drive; + + /// Hold until the will breaks, Withdraw from then on. + public Goal Goal => _drive.WillBroken ? Goal.Withdraw : Goal.Hold; + + public double Stimulus(int region) => _perception.Stimulus(region); + + public double Afferent(int region) => _perception.Afferent(region); + + /// + /// Runs one physics step's worth of nervous system. The point spans hold one entry per region; the strengths + /// and targets spans one entry per muscle, written for the body to follow. + /// + public TickEvents Tick( + ReadOnlySpan regionX, ReadOnlySpan regionY, ReadOnlySpan regionZ, + ReadOnlySpan sources, Span strengths, Span targets) + { + var events = TickEvents.None; + var holding = !_drive.WillBroken; + + _perception.Sense(regionX, regionY, regionZ, sources); + + double afferent = 0.0, strainLoad = 0.0, leak = 0.0; + for (var r = 0; r < _reflexes.Length; r++) + { + var a = _perception.Afferent(r); + var flinch = _reflexes[r].Step(a, _drive); + afferent += a; + strainLoad += _reflexes[r].StrainLoad; + leak += _reflexes[r].Leak; + if (flinch && holding) + { + events |= TickEvents.Flinch; + } + } + + if (_drive.Step(_driveP, _dt, afferent, strainLoad)) + { + events |= TickEvents.WillBroke; + _withdrawTick = _tick + _withdrawLatency; + } + + if (_tick == _withdrawTick) + { + events |= TickEvents.Withdrew; + _withdrew = true; + } + + _behaviour.Write(_withdrew ? Goal.Withdraw : Goal.Hold, leak, _drive.Strain, _tick * _dt, strengths, targets); + _tick++; + return events; + } + } +} diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs new file mode 100644 index 0000000..ed55aac --- /dev/null +++ b/src/Lodur.Core/DriveState.cs @@ -0,0 +1,59 @@ +using System; + +namespace Lodur +{ + /// The drive's tunables: how pain and strain accumulate, and how they drain the will. + public sealed record DriveParameters + { + public double PainRise { get; init; } = 1.0; + public double PainDecay { get; init; } = 0.05; + public double StrainRecover { get; init; } = 0.1; + public double ResolveDrainPain { get; init; } = 0.012; + public double ResolveDrainStrain { get; init; } = 0.05; + public double ResolveRecovery { get; init; } = 0.02; + public double ResolveRecoversBelowPain { get; init; } = 0.1; + + /// How hard the objective pulls, 0..1. It scales resolve drain by (1 - pull); it is not a second resolve bar. + public double ObjectivePull { get; init; } = 0.5; + + /// Per-character multiplier on resolve drain (the consumer draws its trait spread). + public double DrainTrait { get; init; } = 1.0; + } + + /// + /// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the + /// reflex held down, resolve drains under both and recovers when pain is low. Resolve reaching zero breaks + /// the will, and a broken will never mends. Only the owning steps it. + /// + public struct DriveState + { + public double Pain { get; private set; } + public double Strain { get; private set; } + public double Resolve { get; private set; } + public bool WillBroken { get; private set; } + + internal static DriveState Fresh => new DriveState { Resolve = 1.0 }; + + /// Steps one tick; returns true on the tick the will breaks. + internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad) + { + Pain = Math.Min(Math.Max(Pain + dt * (p.PainRise * afferent * (1.0 - Pain) - p.PainDecay * Pain), 0.0), 1.0); + Strain = Math.Max(0.0, Strain + dt * (strainLoad - p.StrainRecover * Strain)); + if (WillBroken) + { + return false; + } + + var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain) * (1.0 - p.ObjectivePull) * p.DrainTrait; + var recovery = Pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - Resolve) : 0.0; + Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0); + if (Resolve <= 0.0) + { + WillBroken = true; + return true; + } + + return false; + } + } +} diff --git a/src/Lodur.Core/HoldAgainstReflex.cs b/src/Lodur.Core/HoldAgainstReflex.cs new file mode 100644 index 0000000..45c63ad --- /dev/null +++ b/src/Lodur.Core/HoldAgainstReflex.cs @@ -0,0 +1,81 @@ +using System; + +namespace Lodur +{ + /// What a character is trying to do. Today: hold against the reflex, or withdraw. + public enum Goal + { + Hold, + Withdraw, + } + + /// The layer-4 stand-in's tunables. + public sealed record HoldParameters + { + /// Muscle strength written for every muscle, in [0, 1] (above 1 an explicit PD arm sags and drifts). + public float HoldStrength { get; init; } = 1f; + + /// How far the reflex leak pulls the pose from hold toward withdraw, per unit of leak. + public double FlinchGain { get; init; } = 0.3; + + /// Strain shake amplitude (blend fraction) per unit of strain. Zero strain, no shake. + public double StrainShake { get; init; } = 0.03; + + /// Shake frequency. A few Hz: the arm's PD filters anything faster to nothing. + public double ShakeHz { get; init; } = 3.5; + } + + /// + /// Layer 4 stand-in: hold a pose against the withdrawal reflex. The target is the hold pose blended toward + /// the withdraw pose by the reflex leak and a strain-scaled shake; once the goal is Withdraw it is the + /// withdraw pose. It writes per-muscle strength and target rotation into the caller's spans and nothing else + /// (invariant body-one-interface). The poses are the caller's data, one rotation per muscle. + /// + public sealed class HoldAgainstReflex + { + private readonly HoldParameters _p; + private readonly Quat[] _hold; + private readonly Quat[] _withdraw; + + public HoldAgainstReflex(HoldParameters parameters, ReadOnlySpan holdPose, ReadOnlySpan withdrawPose) + { + if (holdPose.Length != withdrawPose.Length) + { + throw new ArgumentException("The hold and withdraw poses need one rotation per muscle each."); + } + + _p = parameters; + _hold = holdPose.ToArray(); + _withdraw = withdrawPose.ToArray(); + } + + public int MuscleCount => _hold.Length; + + /// The blend toward the withdraw pose: 1 once withdrawing, else the clamped leak and shake. + public double Blend(Goal goal, double leak, double strain, double seconds) + { + if (goal == Goal.Withdraw) + { + return 1.0; + } + + var w = leak * _p.FlinchGain + _p.StrainShake * strain * Math.Sin(2.0 * Math.PI * _p.ShakeHz * seconds); + return Math.Min(Math.Max(w, 0.0), 1.0); + } + + public void Write(Goal goal, double leak, double strain, double seconds, Span strengths, Span targets) + { + if (strengths.Length != _hold.Length || targets.Length != _hold.Length) + { + throw new ArgumentException($"strengths and targets need {_hold.Length} entries, one per muscle."); + } + + var w = (float)Blend(goal, leak, strain, seconds); + for (var m = 0; m < _hold.Length; m++) + { + strengths[m] = _p.HoldStrength; + targets[m] = Quat.Nlerp(_hold[m], _withdraw[m], w); + } + } + } +} diff --git a/src/Lodur.Core/IsExternalInit.cs b/src/Lodur.Core/IsExternalInit.cs new file mode 100644 index 0000000..a925713 --- /dev/null +++ b/src/Lodur.Core/IsExternalInit.cs @@ -0,0 +1,7 @@ +// Lets C# 9 records use init accessors on netstandard2.1, which does not ship this marker type. +namespace System.Runtime.CompilerServices +{ + internal static class IsExternalInit + { + } +} diff --git a/src/Lodur.Core/PdMuscle.cs b/src/Lodur.Core/PdMuscle.cs index 05c0cb1..33e2ead 100644 --- a/src/Lodur.Core/PdMuscle.cs +++ b/src/Lodur.Core/PdMuscle.cs @@ -30,6 +30,18 @@ namespace Lodur return new Quat(x * s, y * s, z * s, MathF.Cos(half)); } + /// Normalised linear blend from (t = 0) to (t = 1), the shorter way round. + public static Quat Nlerp(in Quat a, in Quat b, float t) + { + var s = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f; + var x = a.X + t * (s * b.X - a.X); + var y = a.Y + t * (s * b.Y - a.Y); + var z = a.Z + t * (s * b.Z - a.Z); + var w = a.W + t * (s * b.W - a.W); + var inv = 1f / MathF.Sqrt(x * x + y * y + z * z + w * w); + return new Quat(x * inv, y * inv, z * inv, w * inv); + } + /// Rotates the vector v by this quaternion. public void Rotate(float vx, float vy, float vz, out float rx, out float ry, out float rz) { diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs new file mode 100644 index 0000000..fba72f1 --- /dev/null +++ b/src/Lodur.Core/Perception.cs @@ -0,0 +1,115 @@ +using System; + +namespace Lodur +{ + /// + /// A game stimulus: an axis-aligned box volume with an intensity the game writes every tick. Lodur reads + /// it and decides containment and transduction; the box is never a physics body. + /// + public struct BoxStimulus + { + public float CenterX, CenterY, CenterZ; + public float HalfX, HalfY, HalfZ; + + /// Noxious intensity inside the box, written by the game each tick (0..1 in the slice's scale). + public double Intensity; + + public BoxStimulus(float centerX, float centerY, float centerZ, float halfX, float halfY, float halfZ, double intensity = 0.0) + { + CenterX = centerX; CenterY = centerY; CenterZ = centerZ; + HalfX = halfX; HalfY = halfY; HalfZ = halfZ; + Intensity = intensity; + } + + /// True when the point is inside the box or on one of its faces. + public bool Contains(float x, float y, float z) => + MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ; + } + + /// The nerve's tunables: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain. + public sealed record NerveParameters + { + public double NociceptorThreshold { get; init; } = 0.1; + public double SensitisationGrowth { get; init; } = 0.04; + public double SensitisationRecovery { get; init; } = 0.02; + public double SensitisationCap { get; init; } = 2.0; + public double ConductionDelaySeconds { get; init; } = 0.06; + + /// Per-character nociceptor gain (the consumer draws its trait spread). + public double Gain { get; init; } = 1.0; + } + + /// + /// Layer 1 for one character, a fixed number of body regions. Each tick it takes one point per region and the + /// game's stimulus sources and produces, per region, the stimulus there and the afferent signal after + /// threshold, sensitisation and conduction delay. Everything is allocated in the constructor. + /// + public sealed class Perception + { + private readonly NerveParameters _p; + private readonly double _dt; + private readonly int _regions; + private readonly int _slots; + private readonly double[] _ring; // afferent signal in flight along the nerve, region-major + private readonly double[] _sens; + private readonly double[] _stimulus; + private readonly double[] _afferent; + private long _tick; + + public Perception(NerveParameters parameters, double tickSeconds, int regionCount) + { + _p = parameters; + _dt = tickSeconds; + _regions = regionCount; + var delayTicks = (int)Math.Round(parameters.ConductionDelaySeconds / tickSeconds); + _slots = Math.Max(1, delayTicks); + _ring = new double[regionCount * _slots]; + _sens = new double[regionCount]; + Array.Fill(_sens, 1.0); + _stimulus = new double[regionCount]; + _afferent = new double[regionCount]; + } + + public int RegionCount => _regions; + + /// The stimulus at the region's point this tick: the largest intensity among the boxes containing it. + public double Stimulus(int region) => _stimulus[region]; + + /// The afferent signal arriving this tick: what the nerve took in a conduction delay ago. + public double Afferent(int region) => _afferent[region]; + + /// Senses once per physics step. The spans are the caller's, one point per region. + public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources) + { + if (x.Length != _regions || y.Length != _regions || z.Length != _regions) + { + throw new ArgumentException($"x, y and z need {_regions} entries, one per region."); + } + + var slot = (int)(_tick % _slots); + for (var r = 0; r < _regions; r++) + { + var stimulus = 0.0; + for (var i = 0; i < sources.Length; i++) + { + if (sources[i].Intensity > stimulus && sources[i].Contains(x[r], y[r], z[r])) + { + stimulus = sources[i].Intensity; + } + } + + // Nociceptor: threshold, then sensitisation, then conduction delay. + var above = Math.Max(0.0, stimulus - _p.NociceptorThreshold); + var sens = _sens[r] + _dt * (_p.SensitisationGrowth * above - _p.SensitisationRecovery * (_sens[r] - 1.0)); + sens = Math.Min(Math.Max(sens, 1.0), _p.SensitisationCap); + _sens[r] = sens; + var ring = r * _slots + slot; + _afferent[r] = _ring[ring]; // written one conduction delay ago + _ring[ring] = above * sens * _p.Gain; + _stimulus[r] = stimulus; + } + + _tick++; + } + } +} diff --git a/src/Lodur.Core/WithdrawalReflex.cs b/src/Lodur.Core/WithdrawalReflex.cs new file mode 100644 index 0000000..0655188 --- /dev/null +++ b/src/Lodur.Core/WithdrawalReflex.cs @@ -0,0 +1,57 @@ +using System; + +namespace Lodur +{ + /// The withdrawal reflex's tunables, and the latency of the deliberate withdrawal that takes over from it. + public sealed record WithdrawalParameters + { + /// How much of the reflex a fully resolved will can hold down (0..1). + public double MaxSuppression { get; init; } = 0.95; + public double FlinchLeakThreshold { get; init; } = 0.3; + public double FlinchRefractorySeconds { get; init; } = 0.5; + + /// How long after the will breaks deliberate behaviour withdraws. + public double LatencySeconds { get; init; } = 0.1; + } + + /// + /// Layer 2 for one body region. Its gain is set ahead of time by the drive: it reads the drive state the + /// previous tick left, before the drive steps (invariant reflex-gain-from-drive). What the suppression holds + /// down is the strain load; what leaks past is the reflex command and, over the threshold, a flinch. + /// + public sealed class WithdrawalReflex + { + private readonly WithdrawalParameters _p; + private readonly long _refractory; + private long _tick; + private long _lastFlinch = long.MinValue / 2; + + public WithdrawalReflex(WithdrawalParameters parameters, double tickSeconds) + { + _p = parameters; + _refractory = (long)Math.Round(parameters.FlinchRefractorySeconds / tickSeconds); + } + + /// The part of the afferent signal that gets past the will this tick. + public double Leak { get; private set; } + + /// The part the will holds down this tick: the strain the drive accumulates. + public double StrainLoad { get; private set; } + + /// Steps once; returns true on a flinch (leak over the threshold, outside the refractory window). + public bool Step(double afferent, in DriveState drive) + { + var suppression = drive.WillBroken ? 0.0 : _p.MaxSuppression * drive.Resolve; + Leak = afferent * (1.0 - suppression); + StrainLoad = afferent * suppression; + var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory; + if (flinch) + { + _lastFlinch = _tick; + } + + _tick++; + return flinch; + } + } +} From 5e0e8c48661f962894e995392d064e88543a0ec6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:42:37 +0100 Subject: [PATCH 04/47] Lodur.Core.Tests: behaviour tests for the nervous layers, core-engine-free References only Lodur.Core. Covers conduction delay, sensitisation, containment, reflex gain set from the previous tick's resolve, suppression cost, broken will, ordered break times, stand-in output, zero allocation, no shared state, and parity with the pain box (seed 1: will breaks at 14730 ms, withdraws at 14830 ms, 16 flinches). Co-Authored-By: Claude Sonnet 5.5 --- Lodur.slnx | 1 + tests/Lodur.Core.Tests/ActorTests.cs | 150 ++++++++++++++++++ .../HoldAgainstReflexTests.cs | 65 ++++++++ .../Lodur.Core.Tests/Lodur.Core.Tests.csproj | 24 +++ tests/Lodur.Core.Tests/PainBoxReplay.cs | 76 +++++++++ tests/Lodur.Core.Tests/PerceptionTests.cs | 82 ++++++++++ 6 files changed, 398 insertions(+) create mode 100644 tests/Lodur.Core.Tests/ActorTests.cs create mode 100644 tests/Lodur.Core.Tests/HoldAgainstReflexTests.cs create mode 100644 tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj create mode 100644 tests/Lodur.Core.Tests/PainBoxReplay.cs create mode 100644 tests/Lodur.Core.Tests/PerceptionTests.cs 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/tests/Lodur.Core.Tests/ActorTests.cs b/tests/Lodur.Core.Tests/ActorTests.cs new file mode 100644 index 0000000..f462cf8 --- /dev/null +++ b/tests/Lodur.Core.Tests/ActorTests.cs @@ -0,0 +1,150 @@ +using Lodur; + +namespace Lodur.Core.Tests; + +public sealed class ActorTests +{ + [Fact] + public void Parity_seed_1_breaks_at_14730_ms_withdraws_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_goal_withdraws_for_good_and_deliberate_withdrawal_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(); + Assert.Equal(broke < 0 && (e & TickEvents.WillBroke) == 0 ? Goal.Hold : Goal.Withdraw, r.Actor.Goal); + 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.Withdrew) != 0) withdrew = i; + strain = r.Actor.Drive.Strain; + if (withdrew >= 0) break; + } + Assert.Equal(broke + 10, withdrew); // round(0.1 s / 10 ms) + // From Withdrew the behaviour is 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); + } + + 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.Goal, y.Actor.Goal); + 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/HoldAgainstReflexTests.cs b/tests/Lodur.Core.Tests/HoldAgainstReflexTests.cs new file mode 100644 index 0000000..91b98eb --- /dev/null +++ b/tests/Lodur.Core.Tests/HoldAgainstReflexTests.cs @@ -0,0 +1,65 @@ +using Lodur; + +namespace Lodur.Core.Tests; + +public sealed class HoldAgainstReflexTests +{ + 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 (float[] S, Quat[] T) Write(HoldAgainstReflex b, Goal g, double leak, double strain, double t) + { + var s = new float[2]; + var q = new Quat[2]; + b.Write(g, leak, strain, t, s, q); + return (s, q); + } + + private static float AngleAboutX(Quat q) => 2f * MathF.Atan2(q.X, q.W); + + [Fact] + public void No_leak_and_no_strain_write_the_hold_pose_withdraw_writes_the_withdraw_pose_strengths_stay_in_unit_range() + { + var b = new HoldAgainstReflex(new HoldParameters(), Hold, Withdraw); + var (s, q) = Write(b, Goal.Hold, 0.0, 0.0, 0.123); + Assert.Equal(-1f, AngleAboutX(q[1]), 4); + Assert.All(s, x => Assert.InRange(x, 0f, 1f)); + + (s, q) = Write(b, Goal.Withdraw, 0.0, 0.0, 0.123); + Assert.Equal(0.3f, AngleAboutX(q[1]), 4); + Assert.All(s, x => Assert.InRange(x, 0f, 1f)); + + (s, q) = Write(b, Goal.Hold, 50.0, 50.0, 0.1); // huge input: the blend clamps, strength does not leave [0, 1] + Assert.All(s, x => Assert.InRange(x, 0f, 1f)); + Assert.InRange(AngleAboutX(q[1]), -1.0001f, 0.3001f); + } + + [Fact] + public void The_shake_is_zero_at_zero_strain_and_its_amplitude_grows_with_strain() + { + var b = new HoldAgainstReflex(new HoldParameters(), Hold, Withdraw); + double Peak(double strain) + { + var peak = 0.0; + for (var i = 0; i < 400; i++) peak = Math.Max(peak, b.Blend(Goal.Hold, 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 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/Lodur.Core.Tests.csproj b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj new file mode 100644 index 0000000..3bc3aec --- /dev/null +++ b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj @@ -0,0 +1,24 @@ + + + + + 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..8ac0d4c --- /dev/null +++ b/tests/Lodur.Core.Tests/PainBoxReplay.cs @@ -0,0 +1,76 @@ +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; + } +} + +/// +/// 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 readonly Quat[] Hold = { Quat.Identity, Quat.Identity }; + public static readonly Quat[] Withdraw = { Quat.FromAxisAngle(1f, 0f, 0f, 1f), Quat.FromAxisAngle(0f, 0f, 1f, -1f) }; + + 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) + { + _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 { ObjectivePull = pull, DrainTrait = drainTrait }, new HoldParameters(), Hold, Withdraw); + } + + /// One tick of the replayed stimulus; the tick index is Actor.TickCount before the call. + public TickEvents Tick() + { + var tick = Actor.TickCount; + var noise = _rng.NextSigned(); + var ramp = Math.Min(1.0, tick * Dt / 2.0); + Sources[0].Intensity = Math.Max(0.0, _intensity * ramp * (1.0 + 0.1 * noise)); + return Actor.Tick(_p, _p, _p, Sources, Strengths, Targets); + } + + /// Runs to Withdrew or the cap; returns the tick of WillBroke and Withdrew (-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.Withdrew) != 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)); + } +} From 0e6bec1dfc3acf99f224cdb4ef357ab5c71a80b1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:48:35 +0100 Subject: [PATCH 05/47] Lodur.Body.Ymir: Region and HumanoidRagdoll.ReadRegions, the hand points perception senses at A hand is the tip of its lower-arm capsule (centre + rotation * (0, -0.14, 0)); the ragdoll has no hand body. Allocates nothing. The visibility change (HumanoidRagdoll, Muscle, Limb public; InternalsVisibleTo deleted) waits on Ymir's public SoA world. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Body.Ymir/HumanoidRagdoll.cs | 35 +++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs index eaa28f0..bfe39f3 100644 --- a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs +++ b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs @@ -9,6 +9,12 @@ namespace Lodur.Body.Ymir 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 + } + /// The ragdoll's bodies, also the limb label written into the world's limb lane. internal enum Limb { @@ -26,9 +32,12 @@ namespace Lodur.Body.Ymir { public const int MuscleCount = 12; public const int LimbCount = 13; + public const int RegionCount = 2; 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,29 @@ 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. 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 < RegionCount; 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; + } + } } } From 83eb5afdca7811660ba84e30569010b9fd275b71 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:48:36 +0100 Subject: [PATCH 06/47] Lodur.Tests: connected pain box on the ragdoll, region readout, native worlds serialised The Actor drives the ragdoll (pelvis welded to a static stool) through strengths and targets only: the hand stays in the stimulus box until the will breaks, flinches pull it away from a leak-free control, the broken will takes it out within 300 ms, same seed gives the same events and world hash. Classes that build native worlds share one xunit collection: two live Box3D worlds on different threads crashed the host (0xC000001D). Co-Authored-By: Claude Sonnet 5.5 --- tests/Lodur.Tests/ConnectedPainBoxTests.cs | 178 +++++++++++++++++++++ tests/Lodur.Tests/NativeWorld.cs | 11 ++ tests/Lodur.Tests/RagdollScenario.cs | 11 +- tests/Lodur.Tests/RagdollTests.cs | 2 + 4 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 tests/Lodur.Tests/ConnectedPainBoxTests.cs create mode 100644 tests/Lodur.Tests/NativeWorld.cs diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs new file mode 100644 index 0000000..47ef546 --- /dev/null +++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs @@ -0,0 +1,178 @@ +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[2], Y = new float[2], Z = new float[2]; + 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) + { + 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(); + Actor = new Actor(Dt, HumanoidRagdoll.RegionCount, new NerveParameters { Gain = gain }, new WithdrawalParameters(), + new DriveParameters { DrainTrait = drain }, hold ?? new HoldParameters(), holdPose, withdrawPose); + } + + 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(); +} + +[Collection(NativeWorld.Name)] +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[2]; var y = new float[2]; var z = new float[2]; + 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.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[2]; var y = new float[2]; var z = new float[2]; + 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) + { + using var s = new ConnectedPainBox(seed, hold); + 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.Withdrew) != 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() + { + var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0); + var full = Run(seed: 1); + 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 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); + } +} diff --git a/tests/Lodur.Tests/NativeWorld.cs b/tests/Lodur.Tests/NativeWorld.cs new file mode 100644 index 0000000..d601f44 --- /dev/null +++ b/tests/Lodur.Tests/NativeWorld.cs @@ -0,0 +1,11 @@ +namespace Lodur.Tests; + +/// +/// Test classes that build Ymir worlds share this collection so xunit runs them one at a time: two native +/// Box3D worlds alive on different threads crashed the test host (0xC000001D) on Windows/MinGW, 2026-11-19. +/// +[CollectionDefinition(Name)] +public sealed class NativeWorld +{ + public const string Name = "native Ymir world"; +} 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/tests/Lodur.Tests/RagdollTests.cs b/tests/Lodur.Tests/RagdollTests.cs index 0590a97..d70845e 100644 --- a/tests/Lodur.Tests/RagdollTests.cs +++ b/tests/Lodur.Tests/RagdollTests.cs @@ -4,6 +4,8 @@ using Ymir.Box3D; namespace Lodur.Tests; +/// Native Ymir worlds are not created concurrently (see NativeWorld.cs). +[Collection(NativeWorld.Name)] public sealed class RagdollTests { private const float StandingHead = 1.74f; From fc34388ef9dd26a92ade8b7be7bf61dc1364f7b6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:49:12 +0100 Subject: [PATCH 07/47] docs: target r3 text, README status and entry points, Windows MinGW result lodur-target.md becomes the r3 text: body on Ymir, layer type names and tick order, one-physics-world restated with the game as owner, core tests build without Ymir. README status drops 'layers 1-4 not coded'. first-slice.md records the MinGW Windows build (DLL prefix workaround) instead of 'unrun'. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 27 ++++--- docs/first-slice.md | 2 +- docs/lodur-target.md | 184 +++++++++++++++++++++---------------------- 3 files changed, 107 insertions(+), 106 deletions(-) diff --git a/README.md b/README.md index b079601..c719274 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 @@ -30,7 +37,7 @@ time. Lodur is that layer. pain, shock, adrenaline and resolve that evolves every tick, and behaviour selection that turns the drive into targets plus muscle strength. - **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/first-slice.md b/docs/first-slice.md index 361e474..48a9a1b 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`; MinGW names the DLL `libymir_box3d.dll` where `Ymir.Box3D.csproj` expects `ymir_box3d.dll`, so copy it to the unprefixed name in `artifacts/box3d-native/production/Debug/bin/Debug` until Ymir emits that name. Test classes that build worlds must not run in parallel there (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..b8780f4 100644 --- a/docs/lodur-target.md +++ b/docs/lodur-target.md @@ -1,123 +1,117 @@ # 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`). 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`.) -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, withdrew) as flags. ## 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 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`.) 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 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). +- 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 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). +- **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. +- **Trademark search** on "Bad Day Simulator" before anything public is announced. From 4dc827083bcad4d44514019a5a54562f8aae5dde Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:49:13 +0100 Subject: [PATCH 08/47] docs: connect-rungs map (body facts, model page, rationale, Ymir cut draft) Imagination's map for the nervous-layers cut, committed from the scratchpad so it is durable. Co-Authored-By: Claude Sonnet 5.5 --- docs/connect-rungs-map.md | 265 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 docs/connect-rungs-map.md diff --git a/docs/connect-rungs-map.md b/docs/connect-rungs-map.md new file mode 100644 index 0000000..d4df271 --- /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, withdrew) 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. From af83eee8a55d88b0b91f44d57c2cf485c7598c56 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 20:49:20 +0100 Subject: [PATCH 09/47] Lodur.Core.Tests: csproj comment names no engine Co-Authored-By: Claude Sonnet 5.5 --- tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj index 3bc3aec..4854a3f 100644 --- a/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj +++ b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj @@ -1,6 +1,6 @@ - + net10.0 enable From 9c07f42545b61f69366a2fed610e52dff35b703f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 21:12:14 +0100 Subject: [PATCH 10/47] Actor: a flinch is a suppressed-reflex leak, so none after the will breaks Corrects the stated reason: the gate is the intended semantics, not seed 1 parity. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Actor.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs index b5ea509..84a4e18 100644 --- a/src/Lodur.Core/Actor.cs +++ b/src/Lodur.Core/Actor.cs @@ -7,7 +7,7 @@ namespace Lodur public enum TickEvents { None = 0, - /// A reflex flinched while the will still held. + /// A reflex leaked past the suppression the will still held. After the will breaks nothing is suppressed, so there is no flinch. Flinch = 1, /// Resolve reached zero this tick. WillBroke = 2, @@ -76,6 +76,7 @@ namespace Lodur ReadOnlySpan sources, Span strengths, Span targets) { var events = TickEvents.None; + // A flinch is the leak of a suppressed reflex; once the will has broken nothing is suppressed, so none is reported. var holding = !_drive.WillBroken; _perception.Sense(regionX, regionY, regionZ, sources); From c52d67bcfdf73d5293cdf67fe22cb83224c9d4fe Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 21:12:14 +0100 Subject: [PATCH 11/47] Lodur.Core.Tests: pain-box golden table (420 runs), resolve recovery, flinch gate; generator committed pain-box-golden.tsv holds BadDaySimulator 9f59764's PainBoxSimulation for 7 intensity/pull settings x seeds 1-60: outcome, break and end ms, flinch count and a hash of the per-tick stimulus/pain/strain/resolve/goal stream. The Actor reproduces it exactly. tools/pain-box-golden regenerates it from that commit. New tests kill 'resolve recovery off' and 'flinch reported after the break'. Co-Authored-By: Claude Sonnet 5.5 --- tests/Lodur.Core.Tests/ActorTests.cs | 39 ++ tests/Lodur.Core.Tests/GoldenParityTests.cs | 65 +++ .../Lodur.Core.Tests/Lodur.Core.Tests.csproj | 1 + tests/Lodur.Core.Tests/PainBoxReplay.cs | 4 +- tests/Lodur.Core.Tests/pain-box-golden.tsv | 422 ++++++++++++++++++ tools/pain-box-golden/PainBoxGolden.csproj | 16 + tools/pain-box-golden/Program.cs | 46 ++ tools/pain-box-golden/generate.sh | 10 + 8 files changed, 601 insertions(+), 2 deletions(-) create mode 100644 tests/Lodur.Core.Tests/GoldenParityTests.cs create mode 100644 tests/Lodur.Core.Tests/pain-box-golden.tsv create mode 100644 tools/pain-box-golden/PainBoxGolden.csproj create mode 100644 tools/pain-box-golden/Program.cs create mode 100644 tools/pain-box-golden/generate.sh diff --git a/tests/Lodur.Core.Tests/ActorTests.cs b/tests/Lodur.Core.Tests/ActorTests.cs index f462cf8..b95b769 100644 --- a/tests/Lodur.Core.Tests/ActorTests.cs +++ b/tests/Lodur.Core.Tests/ActorTests.cs @@ -84,6 +84,45 @@ public sealed class ActorTests 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.Withdrew) != 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); diff --git a/tests/Lodur.Core.Tests/GoldenParityTests.cs b/tests/Lodur.Core.Tests/GoldenParityTests.cs new file mode 100644 index 0000000..508be6e --- /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.Withdrew) != 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.Goal == Goal.Hold ? 0 : 1)); + } + + 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 index 4854a3f..617d2d1 100644 --- a/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj +++ b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/Lodur.Core.Tests/PainBoxReplay.cs b/tests/Lodur.Core.Tests/PainBoxReplay.cs index 8ac0d4c..46ba6ce 100644 --- a/tests/Lodur.Core.Tests/PainBoxReplay.cs +++ b/tests/Lodur.Core.Tests/PainBoxReplay.cs @@ -49,12 +49,12 @@ internal sealed class PainBoxReplay } /// One tick of the replayed stimulus; the tick index is Actor.TickCount before the call. - public TickEvents Tick() + 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 = Math.Max(0.0, _intensity * ramp * (1.0 + 0.1 * noise)); + 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); } 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/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..4bf2ba1 --- /dev/null +++ b/tools/pain-box-golden/generate.sh @@ -0,0 +1,10 @@ +#!/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; } +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" From ca2c02e67fc32939d8794d0f42f0298cf72daddd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 21:12:14 +0100 Subject: [PATCH 12/47] Lodur.Tests: pin the strain shake on the body; name the Ymir defect on the native-world collection At the shipped StrainShake 0.03 the hand's height moves over 3 cm peak to peak per second in seconds 8-13; at StrainShake 0 it moves under 1.5 cm. NativeWorld.cs now names lodur:finding:cut-nervous-layers.s1.ymir-concurrent-world-create and says to remove it once Ymir's lock lands. Co-Authored-By: Claude Sonnet 5.5 --- tests/Lodur.Tests/ConnectedPainBoxTests.cs | 20 ++++++++++++++++++++ tests/Lodur.Tests/NativeWorld.cs | 3 +++ 2 files changed, 23 insertions(+) diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs index 47ef546..6a3002b 100644 --- a/tests/Lodur.Tests/ConnectedPainBoxTests.cs +++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs @@ -164,6 +164,26 @@ public sealed class ConnectedPainBoxTests Assert.True(Dist(full.Hand[last].Hand, plain.Hand[last].Hand) > 0.023f); } + 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(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() { diff --git a/tests/Lodur.Tests/NativeWorld.cs b/tests/Lodur.Tests/NativeWorld.cs index d601f44..5a22cbc 100644 --- a/tests/Lodur.Tests/NativeWorld.cs +++ b/tests/Lodur.Tests/NativeWorld.cs @@ -3,6 +3,9 @@ namespace Lodur.Tests; /// /// Test classes that build Ymir worlds share this collection so xunit runs them one at a time: two native /// Box3D worlds alive on different threads crashed the test host (0xC000001D) on Windows/MinGW, 2026-11-19. +/// This works around a Ymir defect (lodur:finding:cut-nervous-layers.s1.ymir-concurrent-world-create: world create and +/// destroy are not thread-safe). Remove this collection, and the attributes naming it, in the body commit after Ymir +/// merges its lock around world create/destroy. /// [CollectionDefinition(Name)] public sealed class NativeWorld From 7a82ce1fcf0238a667ca9c1f22bd84375ff21567 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 21:12:21 +0100 Subject: [PATCH 13/47] gitattributes: shell scripts keep LF on Windows checkouts Co-Authored-By: Claude Sonnet 5.5 --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf From 05b74e864e30558f61106117b0d7a08f7eb75742 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 21:51:28 +0100 Subject: [PATCH 14/47] Lodur.Body.Ymir: HumanoidRagdoll, Muscle and Limb public; friend grant and native-world collection gone Ymir 0b0321a makes the SoA world public and locks world create/destroy. The ragdoll's Build takes the caller's Box3DSoaWorld and Lodur still never creates one. Deleted AssemblyInfo.cs (InternalsVisibleTo), NativeWorld.cs and the collection attributes; first-slice.md now records that no DLL rename is needed under MinGW. Co-Authored-By: Claude Sonnet 5.5 --- docs/first-slice.md | 2 +- src/Lodur.Body.Ymir/AssemblyInfo.cs | 1 - src/Lodur.Body.Ymir/HumanoidRagdoll.cs | 8 ++++---- tests/Lodur.Tests/ConnectedPainBoxTests.cs | 1 - tests/Lodur.Tests/NativeWorld.cs | 14 -------------- tests/Lodur.Tests/RagdollTests.cs | 2 -- 6 files changed, 5 insertions(+), 23 deletions(-) delete mode 100644 src/Lodur.Body.Ymir/AssemblyInfo.cs delete mode 100644 tests/Lodur.Tests/NativeWorld.cs diff --git a/docs/first-slice.md b/docs/first-slice.md index 48a9a1b..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 (2026-11-19, no MSVC): builds and passes with MinGW gcc, `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; MinGW names the DLL `libymir_box3d.dll` where `Ymir.Box3D.csproj` expects `ymir_box3d.dll`, so copy it to the unprefixed name in `artifacts/box3d-native/production/Debug/bin/Debug` until Ymir emits that name. Test classes that build worlds must not run in parallel there (two live worlds crashed the host). 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/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 bfe39f3..8289dd3 100644 --- a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs +++ b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs @@ -4,7 +4,7 @@ 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 } @@ -16,7 +16,7 @@ namespace Lodur.Body.Ymir } /// 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 } @@ -25,10 +25,10 @@ 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; diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs index 6a3002b..efe1255 100644 --- a/tests/Lodur.Tests/ConnectedPainBoxTests.cs +++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs @@ -73,7 +73,6 @@ internal sealed class ConnectedPainBox : IDisposable public void Dispose() => World.Dispose(); } -[Collection(NativeWorld.Name)] public sealed class ConnectedPainBoxTests { private static float Dist((float X, float Y, float Z) a, (float X, float Y, float Z) b) => diff --git a/tests/Lodur.Tests/NativeWorld.cs b/tests/Lodur.Tests/NativeWorld.cs deleted file mode 100644 index 5a22cbc..0000000 --- a/tests/Lodur.Tests/NativeWorld.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Lodur.Tests; - -/// -/// Test classes that build Ymir worlds share this collection so xunit runs them one at a time: two native -/// Box3D worlds alive on different threads crashed the test host (0xC000001D) on Windows/MinGW, 2026-11-19. -/// This works around a Ymir defect (lodur:finding:cut-nervous-layers.s1.ymir-concurrent-world-create: world create and -/// destroy are not thread-safe). Remove this collection, and the attributes naming it, in the body commit after Ymir -/// merges its lock around world create/destroy. -/// -[CollectionDefinition(Name)] -public sealed class NativeWorld -{ - public const string Name = "native Ymir world"; -} diff --git a/tests/Lodur.Tests/RagdollTests.cs b/tests/Lodur.Tests/RagdollTests.cs index d70845e..0590a97 100644 --- a/tests/Lodur.Tests/RagdollTests.cs +++ b/tests/Lodur.Tests/RagdollTests.cs @@ -4,8 +4,6 @@ using Ymir.Box3D; namespace Lodur.Tests; -/// Native Ymir worlds are not created concurrently (see NativeWorld.cs). -[Collection(NativeWorld.Name)] public sealed class RagdollTests { private const float StandingHead = 1.74f; From 1491bed18dd822888775fdc1d0cf8b34219571a8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 22:06:34 +0100 Subject: [PATCH 15/47] Pin the shake's upper bound, the golden table's line endings, and a clean BDS tree for regeneration Soul lows on cut-nervous-layers.s2: shake-test-has-no-upper-bound (0.06 and 0.15 now fail at 7.7 and 14 cm), golden-tsv-eol-unpinned, golden-generator-trusts-head. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 1 + tests/Lodur.Tests/ConnectedPainBoxTests.cs | 1 + tools/pain-box-golden/generate.sh | 1 + 3 files changed, 3 insertions(+) diff --git a/.gitattributes b/.gitattributes index dfdb8b7..78ef940 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ *.sh text eol=lf +tests/Lodur.Core.Tests/pain-box-golden.tsv text eol=lf diff --git a/tests/Lodur.Tests/ConnectedPainBoxTests.cs b/tests/Lodur.Tests/ConnectedPainBoxTests.cs index efe1255..f0397e8 100644 --- a/tests/Lodur.Tests/ConnectedPainBoxTests.cs +++ b/tests/Lodur.Tests/ConnectedPainBoxTests.cs @@ -179,6 +179,7 @@ public sealed class ConnectedPainBoxTests 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}"); } } diff --git a/tools/pain-box-golden/generate.sh b/tools/pain-box-golden/generate.sh index 4bf2ba1..14b1ad6 100644 --- a/tools/pain-box-golden/generate.sh +++ b/tools/pain-box-golden/generate.sh @@ -6,5 +6,6 @@ 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" From 981b941e495d612e806f8f30271d8e1d0378e6ac Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:15:32 +0100 Subject: [PATCH 16/47] NerveParameters: NociceptorThreshold becomes Threshold The record is the one transduction for every channel from the sensory-load cut on, noxious or not. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Perception.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs index fba72f1..c1e4f5a 100644 --- a/src/Lodur.Core/Perception.cs +++ b/src/Lodur.Core/Perception.cs @@ -29,7 +29,7 @@ namespace Lodur /// The nerve's tunables: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain. public sealed record NerveParameters { - public double NociceptorThreshold { get; init; } = 0.1; + public double 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; @@ -99,7 +99,7 @@ namespace Lodur } // Nociceptor: threshold, then sensitisation, then conduction delay. - var above = Math.Max(0.0, stimulus - _p.NociceptorThreshold); + 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; From f052a36f2ca3549f75054bae2686c3de1c89eaf3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:16:45 +0100 Subject: [PATCH 17/47] Perception: point emitters on audio, visual and interrupt channels, combined into one load Per channel the largest emitter intensity at the sense region's point goes through the same threshold, sensitisation and conduction delay as noxious input; the channels saturate as 1 - prod(1 - afferent). Without senses the loop does nothing and the pain box is untouched. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Perception.cs | 122 ++++++++++++++++++++- tests/Lodur.Core.Tests/SensoryTests.cs | 140 +++++++++++++++++++++++++ 2 files changed, 257 insertions(+), 5 deletions(-) create mode 100644 tests/Lodur.Core.Tests/SensoryTests.cs diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs index c1e4f5a..876726b 100644 --- a/src/Lodur.Core/Perception.cs +++ b/src/Lodur.Core/Perception.cs @@ -26,7 +26,44 @@ namespace Lodur MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ; } - /// The nerve's tunables: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain. + /// 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; @@ -35,14 +72,15 @@ namespace Lodur public double SensitisationCap { get; init; } = 2.0; public double ConductionDelaySeconds { get; init; } = 0.06; - /// Per-character nociceptor gain (the consumer draws its trait spread). + /// 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. Everything is allocated in the constructor. + /// 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 { @@ -54,9 +92,20 @@ namespace Lodur 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; - public Perception(NerveParameters parameters, double tickSeconds, int regionCount) + 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; @@ -68,6 +117,23 @@ namespace Lodur 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; @@ -78,8 +144,18 @@ namespace Lodur /// 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). 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. + public double ChannelAfferent(Channel channel) => _senseAfferent[(int)channel]; + /// Senses once per physics step. The spans are the caller's, one point per region. - public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources) + public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources, + ReadOnlySpan emitters = default) { if (x.Length != _regions || y.Length != _regions || z.Length != _regions) { @@ -109,7 +185,43 @@ namespace Lodur _stimulus[r] = stimulus; } + if (_senses != null) + { + SenseEmitters(x[_senseRegion], y[_senseRegion], z[_senseRegion], emitters); + } + _tick++; } + + private void SenseEmitters(float x, float y, float z, ReadOnlySpan emitters) + { + 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; + _senseAfferent[c] = _senseRing[ring]; // written one conduction delay ago + _senseRing[ring] = above * sens * senses.Gain; + quiet *= 1.0 - Math.Min(1.0, _senseAfferent[c]); + } + + Load = 1.0 - quiet; + } } } diff --git a/tests/Lodur.Core.Tests/SensoryTests.cs b/tests/Lodur.Core.Tests/SensoryTests.cs new file mode 100644 index 0000000..343516e --- /dev/null +++ b/tests/Lodur.Core.Tests/SensoryTests.cs @@ -0,0 +1,140 @@ +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)); + } +} From c6a1208aa289932fa0e481607c116a00f9ef6ac5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:18:33 +0100 Subject: [PATCH 18/47] Drive: arousal from sensory load drains resolve; Actor takes senses and emitters Arousal rises under load and decays when quiet, drains resolve beside pain and strain (scaled by pull and trait), and resolve recovers only when pain and arousal are both low. Actor.Tick gains a trailing emitter span; the pain box's expressions keep their operand order and the 420-row golden table passes unchanged. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Actor.cs | 22 ++- src/Lodur.Core/DriveState.cs | 27 +++- tests/Lodur.Core.Tests/ArousalTests.cs | 187 +++++++++++++++++++++++++ 3 files changed, 225 insertions(+), 11 deletions(-) create mode 100644 tests/Lodur.Core.Tests/ArousalTests.cs diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs index 84a4e18..07e5502 100644 --- a/src/Lodur.Core/Actor.cs +++ b/src/Lodur.Core/Actor.cs @@ -37,12 +37,13 @@ namespace Lodur public Actor( double tickSeconds, int regionCount, NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, HoldParameters hold, - ReadOnlySpan holdPose, ReadOnlySpan withdrawPose) + ReadOnlySpan holdPose, ReadOnlySpan withdrawPose, + NerveParameters? senses = null, int senseRegion = 0) { _dt = tickSeconds; _driveP = drive; _withdrawLatency = Math.Max(1, (long)Math.Round(withdrawal.LatencySeconds / tickSeconds)); - _perception = new Perception(nerve, tickSeconds, regionCount); + _perception = new Perception(nerve, tickSeconds, regionCount, senses, senseRegion); _reflexes = new WithdrawalReflex[regionCount]; for (var r = 0; r < regionCount; r++) { @@ -67,19 +68,28 @@ namespace Lodur 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. + /// 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 sources, Span strengths, Span targets, + ReadOnlySpan emitters = default) { var events = TickEvents.None; // A flinch is the leak of a suppressed reflex; once the will has broken nothing is suppressed, so none is reported. var holding = !_drive.WillBroken; - _perception.Sense(regionX, regionY, regionZ, sources); + _perception.Sense(regionX, regionY, regionZ, sources, emitters); double afferent = 0.0, strainLoad = 0.0, leak = 0.0; for (var r = 0; r < _reflexes.Length; r++) @@ -95,7 +105,7 @@ namespace Lodur } } - if (_drive.Step(_driveP, _dt, afferent, strainLoad)) + if (_drive.Step(_driveP, _dt, afferent, strainLoad, _perception.Load)) { events |= TickEvents.WillBroke; _withdrawTick = _tick + _withdrawLatency; diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs index ed55aac..205c5e9 100644 --- a/src/Lodur.Core/DriveState.cs +++ b/src/Lodur.Core/DriveState.cs @@ -2,7 +2,7 @@ using System; namespace Lodur { - /// The drive's tunables: how pain and strain accumulate, and how they drain the will. + /// 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; @@ -18,25 +18,42 @@ namespace Lodur /// 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 objective'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; } /// /// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the - /// reflex held down, resolve drains under both and recovers when pain is low. Resolve reaching zero breaks + /// 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, and a broken will never mends. Only the owning steps it. /// public struct DriveState { public double Pain { get; private set; } public double Strain { get; private set; } + + /// Sensory load carried over time, 0..1; it rises under load and decays when quiet. + public double Arousal { get; private set; } public double Resolve { get; private set; } public bool WillBroken { get; private set; } internal static DriveState Fresh => new DriveState { Resolve = 1.0 }; /// Steps one tick; returns true on the tick the will breaks. - internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad) + internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad, double load) { + 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)); if (WillBroken) @@ -44,8 +61,8 @@ namespace Lodur return false; } - var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain) * (1.0 - p.ObjectivePull) * p.DrainTrait; - var recovery = Pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - Resolve) : 0.0; + var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain + p.ResolveDrainArousal * Arousal) * (1.0 - p.ObjectivePull) * 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 (Resolve <= 0.0) { diff --git a/tests/Lodur.Core.Tests/ArousalTests.cs b/tests/Lodur.Core.Tests/ArousalTests.cs new file mode 100644 index 0000000..92d3325 --- /dev/null +++ b/tests/Lodur.Core.Tests/ArousalTests.cs @@ -0,0 +1,187 @@ +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) + { + Emitters = emitters; + Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), + (drive ?? new DriveParameters()) with { ObjectivePull = pull, DrainTrait = drainTrait }, new HoldParameters(), + PainBoxReplay.Hold, PainBoxReplay.Withdraw, + 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 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); + } +} From 3579521d56f1901054f62090171d069c72818028 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:18:42 +0100 Subject: [PATCH 19/47] lodur-target: layers 1 and 3 name the emitters, the load and arousal Co-Authored-By: Claude Sonnet 5.5 --- docs/lodur-target.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/lodur-target.md b/docs/lodur-target.md index b8780f4..211bd46 100644 --- a/docs/lodur-target.md +++ b/docs/lodur-target.md @@ -27,11 +27,13 @@ Named after the god in Voluspa who gives the first humans blood, warmth and good 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, +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. 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 + (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. @@ -41,7 +43,8 @@ Signal flows one way per tick, in this order; each layer has one owner. Layers 1 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; + afferent input, strain from suppressed reflexes, arousal from sensory load; resolve drained by all three and + scaled by the objective'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. Static per-character values are this state with its dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.) From 9842cec85f85230e3274faa50e4d7f9189f8a0c7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:45:29 +0100 Subject: [PATCH 20/47] Perception: refuse an emitter with an unknown channel before any state steps Pins the sense point as the sense region's own, on every axis, with three regions. Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Perception.cs | 12 ++++++++ tests/Lodur.Core.Tests/SensoryTests.cs | 39 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs index 876726b..6f6a60f 100644 --- a/src/Lodur.Core/Perception.cs +++ b/src/Lodur.Core/Perception.cs @@ -162,6 +162,18 @@ namespace Lodur throw new ArgumentException($"x, y and z need {_regions} entries, one per region."); } + 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++) { diff --git a/tests/Lodur.Core.Tests/SensoryTests.cs b/tests/Lodur.Core.Tests/SensoryTests.cs index 343516e..59624a2 100644 --- a/tests/Lodur.Core.Tests/SensoryTests.cs +++ b/tests/Lodur.Core.Tests/SensoryTests.cs @@ -137,4 +137,43 @@ public sealed class SensoryPerceptionTests { 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); } + } } From a0488275c6e0be034b7e95b4a75f63730a91d79c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:45:30 +0100 Subject: [PATCH 21/47] Pin that arousal updates before it drains resolve on the same tick Co-Authored-By: Claude Sonnet 5.5 --- tests/Lodur.Core.Tests/ArousalTests.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/Lodur.Core.Tests/ArousalTests.cs b/tests/Lodur.Core.Tests/ArousalTests.cs index 92d3325..b02c5d9 100644 --- a/tests/Lodur.Core.Tests/ArousalTests.cs +++ b/tests/Lodur.Core.Tests/ArousalTests.cs @@ -122,6 +122,24 @@ public sealed class ArousalTests 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() { From 5d0fec8c94a6dd2bd70adfb8230289e7b853d28c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:52:02 +0100 Subject: [PATCH 22/47] Target r4: one severance owner, will is the budget, sandbox is content; topology scope narrowed to the authored part tree; MVP map Operator rulings lodur:ruling:bds-mvp-scope and bds-sandbox-arenas-will-economy (2026-11-20). Co-Authored-By: Claude Opus 5.5 --- docs/bds-mvp-map.md | 321 +++++++++++++++++++++++++++++++++++++++++++ docs/lodur-target.md | 27 +++- 2 files changed, 341 insertions(+), 7 deletions(-) create mode 100644 docs/bds-mvp-map.md diff --git a/docs/bds-mvp-map.md b/docs/bds-mvp-map.md new file mode 100644 index 0000000..2326073 --- /dev/null +++ b/docs/bds-mvp-map.md @@ -0,0 +1,321 @@ +# 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`. Draft for Self to commit as `Lodur/docs/bds-mvp-map.md`; the target r4 text below goes 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`. + +## 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 + (`HoldAgainstReflex.cs:56-80`); 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 `PoseCycle`. +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 | new; planar session precedent `ymir_box3d.c:694-830` | `ymir-contact-facts` | +| Material id per body (u64, the game's), carried on hit facts | new; Box3D `userMaterialId` on hits (types.h:1131-1161) | `ymir-contact-facts` | +| Raycast (closest hit: lane, stable id, point, normal, fraction) for picking and hitscan | new | `ymir-grab-anchor` | +| Grab anchor: shapeless kinematic body moved by target transform; motor joint (linear/angular spring, max force) | new; probe 6 | `ymir-grab-anchor` | +| Point impulse command | new; 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`; 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 | partial: suppression by resolve `WithdrawalReflex.cs:44` | `lodur-startle-attention`, `lodur-will-mix` | +| Voluntary motor layers: hold pose (exists as `HoldAgainstReflex`), clip player, IK goals (reach, look, aim), grip; mixed by will | 4 | hold exists; 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 | new, mapped elsewhere | `godot-client-v1` (parallel pass) | +| 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`). `HoldAgainstReflex`'s blend (`HoldAgainstReflex.cs:56-80`) 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:** `HoldAgainstReflex.Blend` as the motor owner (in `lodur-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; startle drops it, recovers 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 `PoseCycle` 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, + `HoldAgainstReflex.cs:62`), 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 (proposed text for Self) + +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`, right after rung 4. + +## 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 | +| 1' | `ymir-grab-anchor` | Ymir | kinematic anchor, motor joint, impulse, raycast | ymir-shape-lanes (sibling of 1) | S-M | +| 2 | `ymir-break-and-remove` | Ymir | thresholds, overload facts, remove body/joint, tombstones, removal facts | 1 | M | +| - | `rung3-sensory-load` Soul, `rung4-goal-flip`, `rung3-office-stress`, `rung4-office-flip` | Lodur/BDS | in flight | as admitted | - | +| - | `client-ready-sim`, `godot-client-v1` | BDS/Godot | parallel pass | its own | - | +| 3 | `lodur-startle-attention` | Lodur | startle reflex on onsets; attention scales will | rung4-goal-flip | M | +| 4 | `lodur-physiology` | Lodur | part tree content, HP, wounds, blood, pain, shock, consciousness, capacities, death | 3 | 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-will-mix` | Lodur | voluntary layers weighted by will; HoldAgainstReflex demoted | 3 | M | +| 7 | `lodur-ik-goals` | Lodur | IK goals in body interface; two-bone arm/leg, look, aim | 6 | M | +| 8 | `lodur-reflex-set` | Lodur | flinch-from-touch, brace | 5, 6 | 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 | 6; Q `bds-mvp-clips` | S | +| 11 | `lodur-assist-pin` | Lodur | upright assist as a voluntary layer | 6; 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 6 → 7 → 12), 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: