From fdbfd2cf196de9f30e7aec5731679ad3d325d6af Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 25 Nov 2026 23:11:54 +0100 Subject: [PATCH] Physiology oxygen: Breathing capacity, blood and brain oxygen stores, hypoxia curve; Heart no longer Vital The bloodLoss argument threaded through Capacity and Fold becomes one driver array (BloodLoss, BrainOxygen); organism effects may target any capacity and use any non-affliction driver. Gases run on the Acute clock from PhysiologyInput(Arousal, Effort), which the Actor reports from its drive and last tick's strengths. Constants are literature-shaped placeholders (rulings bds-asphyxia-real-time, bds-heart-stop-stagger). Co-Authored-By: Claude Sonnet 5.5 --- src/Lodur.Core/Actor.cs | 9 +- src/Lodur.Core/Physiology.cs | 101 +++++++++--- src/Lodur.Core/PhysiologyPlan.cs | 52 ++++-- src/Lodur.Core/PhysiologyPlans.cs | 14 +- .../Lodur.Core.Tests/ActorPhysiologyTests.cs | 28 +++- tests/Lodur.Core.Tests/OxygenTests.cs | 155 ++++++++++++++++++ tests/Lodur.Core.Tests/PhysiologyFixtures.cs | 10 +- tests/Lodur.Core.Tests/PhysiologyPlanTests.cs | 19 ++- .../Lodur.Core.Tests/PhysiologyPlansTests.cs | 7 +- tests/Lodur.Core.Tests/PhysiologyTests.cs | 2 +- 10 files changed, 343 insertions(+), 54 deletions(-) create mode 100644 tests/Lodur.Core.Tests/OxygenTests.cs diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs index fbf1885..a7c19af 100644 --- a/src/Lodur.Core/Actor.cs +++ b/src/Lodur.Core/Actor.cs @@ -36,6 +36,8 @@ namespace Lodur private readonly WithdrawalReflex[] _reflexes; private readonly Physiology? _physiology; private bool _diedReported; + // The mean of the strengths written on the last tick, after the ceiling, 0..1: the exertion the physiology is told about. + private double _effort; private DriveState _drive = DriveState.Fresh; private long _tick; private int _goal; @@ -187,7 +189,7 @@ namespace Lodur // The physiology steps first, on the drive as the last tick left it, and its consciousness is the slot's only writer. if (!_physiology.Dead) { - _physiology.Step(_dt); + _physiology.Step(_dt, new PhysiologyInput(_drive.Arousal, _effort)); _drive.Consciousness = _physiology.Consciousness; } @@ -287,10 +289,15 @@ namespace Lodur if (_physiology != null) { // The only scaling of strength: each muscle (plan joint m) is held to its ceiling. + var sum = 0.0; for (var m = 0; m < strengths.Length; m++) { strengths[m] *= (float)_physiology.MotorCeiling(m); + sum += strengths[m]; } + + var mean = strengths.Length > 0 ? sum / strengths.Length : 0.0; + _effort = mean < 0.0 ? 0.0 : mean > 1.0 ? 1.0 : mean; } _tick++; diff --git a/src/Lodur.Core/Physiology.cs b/src/Lodur.Core/Physiology.cs index c66756f..4d7ea78 100644 --- a/src/Lodur.Core/Physiology.cs +++ b/src/Lodur.Core/Physiology.cs @@ -6,11 +6,14 @@ namespace Lodur /// Why a body died; the first rule that held at the end of the step that killed it (ruling bds-death). public enum DeathCause { None, VitalTissue, BloodLoss, Consciousness } + /// What the stepping Actor reports each step, each in [0, 1]: Arousal is the sensory load carried over time, Effort the mean strength it asked of the muscles. The default is rest. + public readonly record struct PhysiologyInput(double Arousal, double Effort); + /// - /// The body's physiology: tissue integrity, bound afflictions, blood, the capacities they fold into, the motor ceiling and death. + /// The body's physiology: tissue integrity, bound afflictions, blood and its oxygen, the capacities they fold into, the motor ceiling and death. /// Harm enters only through ; time through . Integrity is derived from the severities of the /// Injures afflictions bound to a tissue (part HP is never stored), and capacities, bleed and the motor ceiling are recomputed each step; - /// nobody writes them. Content owns every label and number (). Everything is allocated in the constructor. + /// nobody writes them; the gases are integrated by Step and nobody writes those either. Content owns every label and number (). Everything is allocated in the constructor. /// public sealed class Physiology { @@ -25,8 +28,9 @@ namespace Lodur private readonly TissueDef[] _tissues; private readonly double[] _injury; private readonly double[] _integrity; - private readonly double _consciousnessWeight; - private readonly double _pumpingWeight; + private readonly double[] _capacityWeight; // per capacity, indexed by EffectTarget (Consciousness, BloodPumping, Breathing) + private readonly RespirationDef _respiration; + private readonly double[] _drivers; // the organism's driver values as the step began, indexed by EffectDriver private readonly double[] _motorWeight; // per part private readonly int[] _slotDef; // -1: free private readonly int[] _slotPart; @@ -38,6 +42,9 @@ namespace Lodur private double _volume; private double _consciousness; private double _pumping = 1.0; + private double _breathing = 1.0; + private double _bloodOxygen = 1.0; + private double _brainOxygen = 1.0; private long _steps; private bool _bound; @@ -49,7 +56,10 @@ namespace Lodur _nominal = plan.Blood.NominalVolume; _lethalLoss = plan.Blood.LethalLossFraction; _regen = plan.Blood.RegenPerSecond; + _respiration = plan.Respiration; _volume = _nominal; + _capacityWeight = new double[CapacityCount]; + _drivers = new double[Enum.GetValues(typeof(EffectDriver)).Length]; _defs = new AfflictionDef[plan.Afflictions.Count]; for (var i = 0; i < _defs.Length; i++) _defs[i] = plan.Afflictions[i]; @@ -80,13 +90,14 @@ namespace Lodur var t = stack[l]; _tissues[_partStart[p] + l] = t; _integrity[_partStart[p] + l] = 1.0; - _consciousnessWeight += t.Consciousness; - _pumpingWeight += t.BloodPumping; + _capacityWeight[(int)EffectTarget.Consciousness] += t.Consciousness; + _capacityWeight[(int)EffectTarget.BloodPumping] += t.BloodPumping; + _capacityWeight[(int)EffectTarget.Breathing] += t.Breathing; _motorWeight[p] += t.Motor; } } - if (!(_consciousnessWeight > 0.0)) throw new ArgumentException("no tissue carries consciousness."); + if (!(_capacityWeight[(int)EffectTarget.Consciousness] > 0.0)) throw new ArgumentException("no tissue carries consciousness."); _motor = new double[body.Joints.Count]; for (var j = 0; j < _motor.Length; j++) { @@ -132,6 +143,15 @@ namespace Lodur /// The heart's capacity to drive what bleeds, 0..1; 0 once dead. public double BloodPumping => Dead ? 0.0 : _pumping; + /// The lungs' capacity to ventilate, 0..1; 0 once dead. An empty Breathing weight reads 1, as BloodPumping does. + public double Breathing => Dead ? 0.0 : _breathing; + + /// The blood's oxygen store, 0..1, starting full; integrated by . + public double BloodOxygen => _bloodOxygen; + + /// The brain's oxygen, 0..1, starting full: it relaxes toward what the pumping delivers from the blood store. Content turns it into consciousness. + public double BrainOxygen => _brainOxygen; + /// The tissue's remaining fraction, 0..1, as of the last step. public double Integrity(int part, int layer) => _integrity[Flat(part, layer)]; @@ -199,10 +219,16 @@ namespace Lodur /// /// Advances by dt seconds of the caller's clock: afflictions age and change severity (healed ones free their slot), integrity, - /// capacities, bleeding and regrowth follow, then death is judged once. A dead physiology does not change. + /// capacities, bleeding and regrowth follow, then the gases on the Acute clock, the motor ceilings, and death is judged once. + /// A dead physiology does not change. A non-finite input, or one outside [0, 1], is refused before anything changes. /// - public void Step(double dt) + public void Step(double dt, in PhysiologyInput input = default) { + if (!(input.Arousal >= 0.0 && input.Arousal <= 1.0 && input.Effort >= 0.0 && input.Effort <= 1.0)) + { + throw new ArgumentException("the input's arousal and effort must be finite and in [0, 1]."); + } + if (Dead) return; var slowDt = dt * _slowScale; @@ -226,10 +252,12 @@ namespace Lodur for (var i = 0; i < _integrity.Length; i++) _integrity[i] = Clamp01(1.0 - _injury[i] / _tissues[i].Hp); - // 3. Capacities: the weighted mean integrity, then every effect's offsets, then its factors. The blood loss they read is the volume the step began with. - var bloodLoss = BloodLoss; - _consciousness = Capacity(EffectTarget.Consciousness, bloodLoss); - _pumping = Capacity(EffectTarget.BloodPumping, bloodLoss); + // 3. Capacities: the weighted mean integrity, then every effect's offsets, then its factors. The blood loss and brain oxygen they read are the values the step began with. + _drivers[(int)EffectDriver.BloodLoss] = BloodLoss; + _drivers[(int)EffectDriver.BrainOxygen] = _brainOxygen; + _consciousness = Capacity(EffectTarget.Consciousness); + _pumping = Capacity(EffectTarget.BloodPumping); + _breathing = Capacity(EffectTarget.Breathing); // 4. Bleeding: each affliction's bleed effects, through its tissue's vascularity and the pumping. Array.Clear(_bleed, 0, _bleed.Length); @@ -238,7 +266,7 @@ namespace Lodur { if (_slotDef[s] < 0) continue; double offset = 0.0, factor = 1.0; - Fold(_defs[_slotDef[s]].Effects, EffectTarget.Bleed, _slotSeverity[s], _slotAge[s], bloodLoss, ref offset, ref factor); + Fold(_defs[_slotDef[s]].Effects, EffectTarget.Bleed, _slotSeverity[s], _slotAge[s], ref offset, ref factor); var rate = Math.Max(0.0, offset * factor) * _tissues[_slotTissue[s]].Vascularity * _pumping; _bleed[_slotPart[s]] += rate; totalBleed += rate; @@ -252,7 +280,14 @@ namespace Lodur _volume = Math.Min(_nominal, _volume + _regen * _nominal * slowDt); } - // 6. Motor ceilings: the child part's motor-weighted integrity, folded with its live afflictions' motor effects, times consciousness. + // 6. The gases, on the Acute clock (ruling bds-asphyxia-real-time): the blood store refills by ventilation and is used by exertion; + // the brain relaxes toward what the pumping delivers. Placeholder constants live in content (RespirationDef). + var r = _respiration; + var use = r.BasalUsePerSecond * (1.0 + r.ArousalUse * input.Arousal + r.EffortUse * input.Effort); + _bloodOxygen = Clamp01(_bloodOxygen + dt * (r.UptakePerSecond * _breathing * (1.0 - _bloodOxygen) - use)); + _brainOxygen = Clamp01(_brainOxygen + (_pumping * _bloodOxygen - _brainOxygen) * (1.0 - Math.Exp(-dt / r.BrainSeconds))); + + // 7. Motor ceilings: the child part's motor-weighted integrity, folded with its live afflictions' motor effects, times consciousness. for (var j = 0; j < _motor.Length; j++) { var part = _body.Joints[j].Child; @@ -268,14 +303,14 @@ namespace Lodur { if (_slotDef[s] >= 0 && _slotPart[s] == part) { - Fold(_defs[_slotDef[s]].Effects, EffectTarget.Motor, _slotSeverity[s], _slotAge[s], bloodLoss, ref offset, ref factor); + Fold(_defs[_slotDef[s]].Effects, EffectTarget.Motor, _slotSeverity[s], _slotAge[s], ref offset, ref factor); } } _motor[j] = Clamp01((mean / _motorWeight[part] + offset) * factor) * _consciousness; } - // 7. Death, once, for every cause; the first rule that holds names it. + // 8. Death, once, for every cause; the first rule that holds names it. var cause = DeathCause.None; for (var i = 0; i < _tissues.Length && cause == DeathCause.None; i++) { @@ -294,16 +329,25 @@ namespace Lodur _steps++; } - private double Capacity(EffectTarget target, double bloodLoss) + private const int CapacityCount = 3; + + private static double Weight(in TissueDef t, EffectTarget target) => target switch { - var weightSum = target == EffectTarget.Consciousness ? _consciousnessWeight : _pumpingWeight; + EffectTarget.Consciousness => t.Consciousness, + EffectTarget.BloodPumping => t.BloodPumping, + _ => t.Breathing, + }; + + private double Capacity(EffectTarget target) + { + var weightSum = _capacityWeight[(int)target]; var mean = 1.0; if (weightSum > 0.0) { var acc = 0.0; for (var i = 0; i < _tissues.Length; i++) { - var w = target == EffectTarget.Consciousness ? _tissues[i].Consciousness : _tissues[i].BloodPumping; + var w = Weight(_tissues[i], target); if (w > 0.0) acc += w * _integrity[i]; } @@ -313,29 +357,34 @@ namespace Lodur double offset = 0.0, factor = 1.0; for (var i = 0; i < _organism.Length; i++) { - Fold(_organism[i], target, 0.0, 0.0, bloodLoss, ref offset, ref factor); + Fold(_organism[i], target, 0.0, 0.0, ref offset, ref factor); } for (var s = 0; s < _slotDef.Length; s++) { - if (_slotDef[s] >= 0) Fold(_defs[_slotDef[s]].Effects, target, _slotSeverity[s], _slotAge[s], bloodLoss, ref offset, ref factor); + if (_slotDef[s] >= 0) Fold(_defs[_slotDef[s]].Effects, target, _slotSeverity[s], _slotAge[s], ref offset, ref factor); } return Clamp01((mean + offset) * factor); } - private static void Fold(IReadOnlyList effects, EffectTarget target, double severity, double age, double bloodLoss, ref double offset, ref double factor) + private void Fold(IReadOnlyList effects, EffectTarget target, double severity, double age, ref double offset, ref double factor) { for (var i = 0; i < effects.Count; i++) { - Fold(effects[i], target, severity, age, bloodLoss, ref offset, ref factor); + Fold(effects[i], target, severity, age, ref offset, ref factor); } } - private static void Fold(Effect e, EffectTarget target, double severity, double age, double bloodLoss, ref double offset, ref double factor) + private void Fold(Effect e, EffectTarget target, double severity, double age, ref double offset, ref double factor) { if (e.Target != target) return; - var x = e.Driver == EffectDriver.Severity ? severity : e.Driver == EffectDriver.Age ? age : bloodLoss; + var x = e.Driver switch + { + EffectDriver.Severity => severity, + EffectDriver.Age => age, + _ => _drivers[(int)e.Driver], + }; var v = e.Eval(x); if (e.Op == EffectOp.Offset) offset += v; else factor *= v; diff --git a/src/Lodur.Core/PhysiologyPlan.cs b/src/Lodur.Core/PhysiologyPlan.cs index 4cb7df4..cb753e8 100644 --- a/src/Lodur.Core/PhysiologyPlan.cs +++ b/src/Lodur.Core/PhysiologyPlan.cs @@ -6,14 +6,20 @@ namespace Lodur /// The clock a process runs on: Acute on the caller's seconds, Slow on those times the session's slow scale (ruling bds-physiology-clock). public enum PhysiologyClock { Acute, Slow } - /// What an effect shapes. One mechanism reads each: capacities (Consciousness, BloodPumping), an affliction's bleed rate, a part's motor ceiling. - public enum EffectTarget { Consciousness, BloodPumping, Bleed, Motor } + /// + /// What an effect shapes. One mechanism reads each: capacities (Consciousness, BloodPumping, Breathing, the last read by gas exchange as + /// ventilation), an affliction's bleed rate, a part's motor ceiling. The three capacities come first and their order is the capacity index. + /// + public enum EffectTarget { Consciousness, BloodPumping, Breathing, Bleed, Motor } /// How an effect's value joins its target: summed into the offsets, or multiplied into the factors. public enum EffectOp { Offset, Factor } - /// What an effect's curve is read at: its affliction's severity or age (in its clock's seconds), or the organism's blood loss. - public enum EffectDriver { Severity, Age, BloodLoss } + /// + /// What an effect's curve is read at: its affliction's severity or age (in its clock's seconds), or an organism value as the step began: + /// the blood loss or the brain oxygen. Severity and Age belong to an affliction alone; BloodLoss and BrainOxygen index the organism's driver array. + /// + public enum EffectDriver { Severity, Age, BloodLoss, BrainOxygen } /// /// The material of a layer simulated as a particle sheet. is the particle spacing in m. The compliances are @@ -24,13 +30,13 @@ namespace Lodur /// /// One tissue layer of a part. , and are - /// function weights, a closed set with one reader each: a capacity is the weighted mean integrity of the tissues that carry its weight. + /// function weights, a closed set with one reader each ( is the lungs' share of ventilation): a capacity is the weighted mean integrity of the tissues that carry its weight. /// A Vital tissue at integrity 0 kills. A stack is shells ( above 0, in m) outside-in, then cores (Thickness 0: /// bone, organs, a muscle with no sheet); the cores fill what the shells leave of the part's shape. is the /// material of a shell simulated as a particle sheet; null means it is not. /// public readonly record struct TissueDef( - string Label, double Hp, double Vascularity, bool Vital = false, double Consciousness = 0.0, double BloodPumping = 0.0, double Motor = 0.0) + string Label, double Hp, double Vascularity, bool Vital = false, double Consciousness = 0.0, double BloodPumping = 0.0, double Motor = 0.0, double Breathing = 0.0) { public double Thickness { get; init; } public SheetDef? Sheet { get; init; } @@ -42,6 +48,14 @@ namespace Lodur /// The blood: nominal volume in m^3, the lost fraction that kills, and the regrowth per slow second as a fraction of nominal. public readonly record struct BloodDef(double NominalVolume, double LethalLossFraction, double RegenPerSecond); + /// + /// The gases, all on the Acute clock (ruling bds-asphyxia-real-time): the blood oxygen store S refills at + /// x ventilation x (1 - S) per second and is used at x + /// (1 + x arousal + x effort); the brain oxygen relaxes toward BloodPumping x S + /// with time constant . Both stores run 0..1. + /// + public readonly record struct RespirationDef(double UptakePerSecond, double BasalUsePerSecond, double ArousalUse, double EffortUse, double BrainSeconds); + /// /// A piecewise-linear curve in its driver, clamped at the ends. An equal-x pair is a step: at that x the later value holds /// (a stage begins at its threshold). Effects only shape values a mechanism reads; they never write state. @@ -77,8 +91,8 @@ namespace Lodur public readonly record struct AfflictionDef(string Label, PhysiologyClock Clock, double SeverityRate, bool Injures, IReadOnlyList Effects); /// - /// Physiology as content: tissue stacks per body part, the afflictions that can be bound, the organism-wide effects of blood - /// loss, the blood and the size of the affliction table. Validated at construction; resolved against a by , the one (label, side) join, which and the sheet builder both call. + /// Physiology as content: tissue stacks per body part, the afflictions that can be bound, the organism-wide effects of the organism's blood + /// loss and brain oxygen, the blood, the respiration and the size of the affliction table. Validated at construction; resolved against a by , the one (label, side) join, which and the sheet builder both call. /// public sealed class PhysiologyPlan { @@ -86,7 +100,7 @@ namespace Lodur public PhysiologyPlan( IReadOnlyList parts, IReadOnlyList afflictions, IReadOnlyList organismEffects, - BloodDef blood, int afflictionSlots) + BloodDef blood, RespirationDef respiration, int afflictionSlots) { var ownedParts = new List(parts.Count); foreach (var p in parts) @@ -104,6 +118,7 @@ namespace Lodur Afflictions = ownedAfflictions.AsReadOnly(); OrganismEffects = Own(organismEffects); Blood = blood; + Respiration = respiration; AfflictionSlots = afflictionSlots; Validate(); } @@ -112,6 +127,7 @@ namespace Lodur public IReadOnlyList Afflictions { get; } public IReadOnlyList OrganismEffects { get; } public BloodDef Blood { get; } + public RespirationDef Respiration { get; } public int AfflictionSlots { get; } public int AfflictionIndex(string label) => @@ -180,7 +196,7 @@ namespace Lodur if (!seen.Add(t.Label)) throw new ArgumentException($"{where}: the label is not unique within the part."); if (!(IsFinite(t.Hp) && t.Hp > 0.0)) throw new ArgumentException($"{where}: Hp is not finite and above 0."); if (!(IsFinite(t.Vascularity) && t.Vascularity >= 0.0)) throw new ArgumentException($"{where}: vascularity is not finite and at least 0."); - if (!(IsFinite(t.Consciousness) && t.Consciousness >= 0.0 && IsFinite(t.BloodPumping) && t.BloodPumping >= 0.0 && IsFinite(t.Motor) && t.Motor >= 0.0)) + if (!(IsFinite(t.Consciousness) && t.Consciousness >= 0.0 && IsFinite(t.BloodPumping) && t.BloodPumping >= 0.0 && IsFinite(t.Motor) && t.Motor >= 0.0 && IsFinite(t.Breathing) && t.Breathing >= 0.0)) { throw new ArgumentException($"{where}: a function weight is not finite and at least 0."); } @@ -220,20 +236,28 @@ namespace Lodur foreach (var e in OrganismEffects) { ValidateEffect(e, "an organism effect"); - if (e.Target != EffectTarget.Consciousness && e.Target != EffectTarget.BloodPumping) + if (e.Target != EffectTarget.Consciousness && e.Target != EffectTarget.BloodPumping && e.Target != EffectTarget.Breathing) { - throw new ArgumentException("an organism effect targets only Consciousness or BloodPumping."); + throw new ArgumentException("an organism effect targets only a capacity: Consciousness, BloodPumping or Breathing."); } - if (e.Driver != EffectDriver.BloodLoss) + if (e.Driver == EffectDriver.Severity || e.Driver == EffectDriver.Age) { - throw new ArgumentException("an organism effect is driven only by BloodLoss."); + throw new ArgumentException("an organism effect is not driven by Severity or Age: those belong to an affliction."); } } if (!(IsFinite(Blood.NominalVolume) && Blood.NominalVolume > 0.0)) throw new ArgumentException("blood: the nominal volume is not finite and above 0."); if (!(Blood.LethalLossFraction > 0.0 && Blood.LethalLossFraction <= 1.0)) throw new ArgumentException("blood: the lethal loss fraction is not in (0, 1]."); if (!(IsFinite(Blood.RegenPerSecond) && Blood.RegenPerSecond >= 0.0)) throw new ArgumentException("blood: the regrowth is not finite and at least 0."); + var r = Respiration; + if (!(IsFinite(r.UptakePerSecond) && r.UptakePerSecond >= 0.0 && IsFinite(r.BasalUsePerSecond) && r.BasalUsePerSecond >= 0.0 + && IsFinite(r.ArousalUse) && r.ArousalUse >= 0.0 && IsFinite(r.EffortUse) && r.EffortUse >= 0.0)) + { + throw new ArgumentException("respiration: a rate is not finite and at least 0."); + } + + if (!(IsFinite(r.BrainSeconds) && r.BrainSeconds > 0.0)) throw new ArgumentException("respiration: BrainSeconds is not finite and above 0."); if (AfflictionSlots < 1) throw new ArgumentException("the affliction table needs at least one slot."); } diff --git a/src/Lodur.Core/PhysiologyPlans.cs b/src/Lodur.Core/PhysiologyPlans.cs index a6c1201..5fc72b4 100644 --- a/src/Lodur.Core/PhysiologyPlans.cs +++ b/src/Lodur.Core/PhysiologyPlans.cs @@ -32,7 +32,7 @@ namespace Lodur /// /// The 19-part humanoid of : tissue stacks outside-in with RimWorld's human part HP (fat and bone are stack thickness and core, not particles), the - /// blood, the stages of blood loss, and the Cut and Bruise afflictions. Numbers not cited are play-tuned placeholders. + /// blood, the stages of blood loss, the hypoxia curve and the respiration, and the Cut and Bruise afflictions. Numbers not cited are play-tuned placeholders; the respiration constants (uptake, basal and exertion use, brain lag) are literature-shaped placeholders. /// public static PhysiologyPlan Humanoid() { @@ -42,8 +42,8 @@ namespace Lodur Stack("Pelvis", Side.Center, Skin(10), Fat(10), MuscleSheet(30), Bone("Pelvis", 25), new TissueDef("Gut", 20, GutV)); Stack("Torso", Side.Center, Skin(10), Fat(10), MuscleSheet(40), Bone("Ribcage", 25), - new TissueDef("Heart", 15, HeartV, Vital: true, BloodPumping: 1.0), - new TissueDef("LungLeft", 15, LungV), new TissueDef("LungRight", 15, LungV), + new TissueDef("Heart", 15, HeartV, BloodPumping: 1.0), + new TissueDef("LungLeft", 15, LungV, Breathing: 1.0), new TissueDef("LungRight", 15, LungV, Breathing: 1.0), new TissueDef("Liver", 20, LiverV), new TissueDef("KidneyLeft", 15, KidneyV), new TissueDef("KidneyRight", 15, KidneyV)); // The neck's muscle carries the Neck joint's motor weight: the head has to be a joint child with a muscle (spec discrepancy, report deviation). Stack("Head", Side.Center, Skin(5), Fat(5), Muscle(25), Bone("Skull", 25), new TissueDef("Brain", 10, BrainV, Vital: true, Consciousness: 1.0)); @@ -63,6 +63,11 @@ namespace Lodur var bloodLoss = Curve(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss, (0.0, 0.0), (0.15, 0.0), (0.15, -0.1), (0.30, -0.1), (0.30, -0.2), (0.45, -0.2), (0.45, -0.4), (0.60, -0.4), (0.60, -0.9), (1.0, -0.9)); + // Brain oxygen to consciousness: flat 1 above 0.70 so a healthy body reads exactly 1, falling to 0 at 0.10. A stopped heart or a smothering + // reaches it through the stores. (placeholder, fitted to ~75 s unconscious while struggling and death at 134-360 s, PMC8928428 and Szpilman NEJM 2012; + // 6-10 s after cerebral circulation stops, Rossen, Kabat and Anderson 1943; rulings bds-asphyxia-real-time, bds-heart-stop-stagger) + var hypoxia = Curve(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, (0.10, 0.0), (0.35, 0.1), (0.70, 1.0)); + var afflictions = new[] { // Acute: a wound bleeds, clots and heals in real seconds whatever the slow scale (ruling bds-physiology-clock). 1 mL/s per HP of severity @@ -76,7 +81,8 @@ namespace Lodur }; // ATLS class IV past 40% loss (research df-and-atls) puts the lethal fraction at 0.5 (play-tuned); regrowth is RimWorld's 0.333 per slow day. - return new PhysiologyPlan(parts, afflictions, new[] { bloodLoss }, new BloodDef(0.005, 0.5, 0.333 / Day), 64); + return new PhysiologyPlan(parts, afflictions, new[] { bloodLoss, hypoxia }, new BloodDef(0.005, 0.5, 0.333 / Day), + new RespirationDef(1.0, 0.002, 0.5, 4.0, 9.5), 64); } } } diff --git a/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs b/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs index 426f0db..a7a6e12 100644 --- a/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs +++ b/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs @@ -126,6 +126,30 @@ public sealed class ActorPhysiologyTests Assert.Equal(TickEvents.None, Tick(a, 0.0, s, new Quat[2])); } + [Fact] + public void The_actor_reports_its_last_ticks_strength_as_effort() + { + double Oxygen(float hold) + { + var brain = new Brain + { + Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = hold } } } }, + }; + var p = Make3(); + Assert.True(p.Afflict(Af("Choke"), 0, 0, 1e9)); + var a = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, physiology: p); + var s = new float[2]; + var q = new Quat[2]; + for (var i = 0; i < 3000; i++) Tick(a, 0.0, s, q); + Assert.False(p.Dead); + return p.BloodOxygen; + } + + var strong = Oxygen(0.7f); + var idle = Oxygen(0.0f); + Assert.True(strong < idle, $"strong {strong}, idle {idle}"); + } + [Fact] public void A_healthy_physiology_changes_nothing_bit_for_bit() { @@ -154,13 +178,15 @@ public sealed class ActorPhysiologyTests [Fact] public void A_tick_with_a_physiology_and_eight_bleeding_afflictions_allocates_nothing() { - var p = new Physiology(Body3(), Plan3(blood: new BloodDef(1000.0, 0.5, 1e-4)), 20); + var p = new Physiology(Body3(), Plan3(blood: new BloodDef(1000.0, 0.5, 1e-4), slots: 9, organism: new[] { Hypoxia }), 20); for (var i = 0; i < 4; i++) { Assert.True(p.Afflict(Af("Bleeder"), 1 + i % 2, 0, 0.5 + 0.1 * i)); Assert.True(p.Afflict(Af("Clot"), 0, RootMuscle, 1.0)); } + Assert.True(p.Afflict(Af("Choke"), 0, 0, 0.8)); // the gases run and the hypoxia curve reads, through the warm-up and into the measured ticks + var a = Make(p); var s = new float[2]; var q = new Quat[2]; diff --git a/tests/Lodur.Core.Tests/OxygenTests.cs b/tests/Lodur.Core.Tests/OxygenTests.cs new file mode 100644 index 0000000..651e573 --- /dev/null +++ b/tests/Lodur.Core.Tests/OxygenTests.cs @@ -0,0 +1,155 @@ +using Lodur; +using static Lodur.Core.Tests.PhysioFixtures; + +namespace Lodur.Core.Tests; + +/// +/// Blood and brain oxygen: the stores, the Breathing capacity and the content that turns brain oxygen into consciousness. The windows are the +/// literature the content constants are fitted to (placeholders, rulings bds-asphyxia-real-time and bds-heart-stop-stagger). +/// +public sealed class OxygenTests +{ + private const double Dt = 1.0 / 120.0; + + private static readonly BodyPlan Body = BodyPlans.Humanoid(); + + private static Physiology Spawn() => new(Body, PhysiologyPlans.Humanoid(), 20); + + /// The humanoid's content with a smothering that never lifts added to its afflictions. + private static Physiology Smothered() + { + var h = PhysiologyPlans.Humanoid(); + var choke = new AfflictionDef("Choke", PhysiologyClock.Acute, -1.0 / 40.0, false, + new[] { new Effect(EffectTarget.Breathing, EffectOp.Factor, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 0.0) }) }); + var defs = new List(h.Afflictions) { choke }; + var plan = new PhysiologyPlan(h.Parts, defs, h.OrganismEffects, h.Blood, h.Respiration, h.AfflictionSlots); + var p = new Physiology(Body, plan, 20); + Assert.True(p.Afflict(plan.AfflictionIndex("Choke"), Body.PartIndex("Torso"), 0, 1e9)); + return p; + } + + /// Steps with the given arousal; effort is the consciousness the last step left (a struggle that fades with the motor ceiling) unless fixed. Returns the second consciousness first fell to 0.1 or below and the second of death (-1 for neither). + private static (double Out, double Dead) Run(Physiology p, double arousal, double? effort, double seconds) + { + double outAt = -1.0, deadAt = -1.0, c = 1.0; + var steps = (long)(seconds / Dt); + for (long i = 0; i < steps && !p.Dead; i++) + { + p.Step(Dt, new PhysiologyInput(arousal, effort ?? c)); + c = p.Consciousness; + var t = (i + 1) * Dt; + if (outAt < 0.0 && c <= 0.1) outAt = t; + if (p.Dead) deadAt = t; + } + + return (outAt, deadAt); + } + + [Fact] + public void A_whole_humanoid_at_rest_keeps_its_oxygen_and_full_consciousness() + { + var p = Spawn(); + for (var i = 0; i < (int)(600.0 / Dt); i++) + { + p.Step(Dt); + Assert.Equal(1.0, p.Consciousness); + } + + Assert.True(p.BloodOxygen >= 0.99, $"blood oxygen {p.BloodOxygen}"); + Assert.True(p.BrainOxygen >= 0.99, $"brain oxygen {p.BrainOxygen}"); + Assert.Equal(1.0, p.Breathing); + } + + [Fact] + public void A_struggling_smothered_humanoid_is_out_in_60_to_90_s_and_dead_in_134_to_360_s() + { + var p = Smothered(); + var (outAt, deadAt) = Run(p, 1.0, null, 400.0); + Assert.InRange(outAt, 60.0, 90.0); + Assert.InRange(deadAt, 134.0, 360.0); + Assert.Equal(DeathCause.Consciousness, p.Cause); + } + + [Fact] + public void Calm_is_slower_than_struggling() + { + var struggling = Run(Smothered(), 1.0, null, 400.0); + var calm = Run(Smothered(), 0.0, 0.0, 1200.0); + Assert.True(calm.Out > struggling.Out, $"calm {calm.Out} s, struggling {struggling.Out} s"); + } + + [Fact] + public void A_destroyed_heart_staggers_for_seconds_and_kills_through_consciousness() + { + var p = Spawn(); + var torso = Body.PartIndex("Torso"); + Assert.True(p.Afflict(PhysiologyPlans.Humanoid().AfflictionIndex("Cut"), torso, p.TissueIndex(torso, "Heart"), 16)); + p.Step(Dt); + Assert.False(p.Dead); + Assert.Equal(DeathCause.None, p.Cause); + Assert.Equal(0.0, p.BloodPumping); + + var (outAt, deadAt) = Run(p, 0.0, 0.0, 60.0); + Assert.InRange(outAt + Dt, 6.0, 12.0); + Assert.True(deadAt > outAt, $"out {outAt} s, dead {deadAt} s"); + Assert.Equal(DeathCause.Consciousness, p.Cause); + } + + [Fact] + public void One_lung_lost_still_breathes() + { + var p = Spawn(); + var torso = Body.PartIndex("Torso"); + Assert.True(p.Afflict(PhysiologyPlans.Humanoid().AfflictionIndex("Bruise"), torso, p.TissueIndex(torso, "LungLeft"), 16)); + double c = 1.0; + for (var i = 0; i < (int)(300.0 / Dt); i++) + { + p.Step(Dt, new PhysiologyInput(1.0, c)); + c = p.Consciousness; + Assert.True(c >= 0.9, $"consciousness {c} at step {i}"); + } + + Assert.InRange(p.Breathing, 0.5, 0.52); // the bruise heals a little on the slow clock + Assert.False(p.Dead); + } + + [Fact] + public void A_lifted_smothering_refills() + { + var p = Make(organism: new[] { Hypoxia }); + Assert.True(p.Afflict(Af("Choke"), 0, 0, 1.0)); // lifts at 40 s + double c = 1.0, lowest = 1.0; + for (var i = 0; i < (int)(39.0 / Dt); i++) + { + p.Step(Dt, new PhysiologyInput(1.0, c)); + c = p.Consciousness; + lowest = Math.Min(lowest, c); + } + + Assert.True(lowest < 1.0, "the smothering never dimmed the brain"); + Assert.Equal(0.0, p.Breathing); + for (var i = 0; i < (int)(31.0 / Dt); i++) + { + p.Step(Dt, new PhysiologyInput(1.0, c)); + c = p.Consciousness; + } + + Assert.Equal(1.0, c); + Assert.False(p.Dead); + } + + [Fact] + public void An_input_outside_zero_to_one_or_not_finite_is_refused_before_anything_changes() + { + var p = Spawn(); + foreach (var bad in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity }) + { + Assert.Throws(() => p.Step(Dt, new PhysiologyInput(bad, 0.0))); + Assert.Throws(() => p.Step(Dt, new PhysiologyInput(0.0, bad))); + } + + Assert.Equal(1.0, p.BloodOxygen); + p.Step(Dt, new PhysiologyInput(1.0, 1.0)); + Assert.True(p.BloodOxygen < 1.0); + } +} diff --git a/tests/Lodur.Core.Tests/PhysiologyFixtures.cs b/tests/Lodur.Core.Tests/PhysiologyFixtures.cs index 9d59337..aeb36da 100644 --- a/tests/Lodur.Core.Tests/PhysiologyFixtures.cs +++ b/tests/Lodur.Core.Tests/PhysiologyFixtures.cs @@ -35,6 +35,8 @@ internal static class PhysioFixtures Def("Staunch", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Bleed, EffectOp.Offset, -1e-3)), Def("Fading", -0.1, false, PhysiologyClock.Acute, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-5) })), Def("SlowBleeder", 0, false, PhysiologyClock.Slow, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-3) })), + // A test smothering: ventilation is zero until it lifts, 40 s at severity 1. + Def("Choke", -1.0 / 40.0, false, PhysiologyClock.Acute, Const(EffectTarget.Breathing, EffectOp.Factor, 0.0)), }; public static int Af(string label) @@ -45,6 +47,12 @@ internal static class PhysioFixtures public static BloodDef DefaultBlood => new(0.005, 0.5, 0.0); + /// The same literature-shaped placeholders as the humanoid's content. + public static RespirationDef DefaultRespiration => new(1.0, 0.002, 0.5, 4.0, 9.5); + + /// The humanoid's hypoxia curve: brain oxygen to consciousness, flat 1 above 0.70. + public static Effect Hypoxia => new(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, new[] { (0.10, 0.0), (0.35, 0.1), (0.70, 1.0) }); + /// Root: brain (weight 1), heart (pumping 1, vital unless asked otherwise), a muscle; A and B: a muscle each. Every tissue has Hp 10. public static PhysiologyPlan Plan3(bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null) { @@ -57,7 +65,7 @@ internal static class PhysioFixtures var limb = new[] { new TissueDef("muscle", 10, 1, Motor: 1) }; return new PhysiologyPlan( new[] { new PartTissuesDef("Root", Side.Center, stack), new PartTissuesDef("A", Side.Center, limbA ?? limb), new PartTissuesDef("B", Side.Center, limb) }, - Defs, organism ?? Array.Empty(), blood ?? DefaultBlood, slots); + Defs, organism ?? Array.Empty(), blood ?? DefaultBlood, DefaultRespiration, slots); } public static Physiology Make(double slowScale = 20.0, bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null) => diff --git a/tests/Lodur.Core.Tests/PhysiologyPlanTests.cs b/tests/Lodur.Core.Tests/PhysiologyPlanTests.cs index 03acc4d..89d4fed 100644 --- a/tests/Lodur.Core.Tests/PhysiologyPlanTests.cs +++ b/tests/Lodur.Core.Tests/PhysiologyPlanTests.cs @@ -12,12 +12,14 @@ public sealed class PhysiologyPlanTests private static BloodDef GoodBlood => new(0.005, 0.5, 0.001); + private static RespirationDef GoodRespiration => new(1.0, 0.002, 0.5, 4.0, 9.5); + private static PhysiologyPlan Plan( IReadOnlyList? tissues = null, IReadOnlyList? afflictions = null, - IReadOnlyList? organism = null, BloodDef? blood = null, int slots = 4) => + IReadOnlyList? organism = null, BloodDef? blood = null, int slots = 4, RespirationDef? respiration = null) => new(new[] { new PartTissuesDef("A", Side.Center, tissues ?? new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1) }) }, afflictions ?? new[] { new AfflictionDef("a", PhysiologyClock.Acute, 0, true, Array.Empty()) }, - organism ?? Array.Empty(), blood ?? GoodBlood, slots); + organism ?? Array.Empty(), blood ?? GoodBlood, respiration ?? GoodRespiration, slots); private static void Refuses(Action build) => Assert.Throws(build); @@ -91,6 +93,15 @@ public sealed class PhysiologyPlanTests Refuses(() => Plan(organism: new[] { Fx(d: EffectDriver.Age) })); Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Bleed) })); // a target only an affliction has Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Motor) })); + Refuses(() => Plan(new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1, Breathing: -1) })); + Refuses(() => Plan(new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1, Breathing: double.NaN) })); + + Refuses(() => Plan(respiration: GoodRespiration with { UptakePerSecond = -1 })); + Refuses(() => Plan(respiration: GoodRespiration with { BasalUsePerSecond = -1 })); + Refuses(() => Plan(respiration: GoodRespiration with { ArousalUse = double.NaN })); + Refuses(() => Plan(respiration: GoodRespiration with { EffortUse = double.PositiveInfinity })); + Refuses(() => Plan(respiration: GoodRespiration with { BrainSeconds = 0 })); + Refuses(() => Plan(respiration: GoodRespiration with { BrainSeconds = double.NaN })); Refuses(() => Plan(blood: GoodBlood with { NominalVolume = 0 })); Refuses(() => Plan(blood: GoodBlood with { NominalVolume = double.NaN })); @@ -113,8 +124,10 @@ public sealed class PhysiologyPlanTests [Fact] public void An_affliction_may_use_every_driver_and_the_boundary_values_of_the_rules_are_accepted() { - var effects = new[] { Fx(EffectTarget.Bleed, EffectDriver.Severity), Fx(EffectTarget.Motor, EffectDriver.Age), Fx(EffectTarget.Consciousness, EffectDriver.BloodLoss), Fx(curve: new[] { (1.0, 0.0), (1.0, 1.0) }) }; + var effects = new[] { Fx(EffectTarget.Bleed, EffectDriver.Severity), Fx(EffectTarget.Motor, EffectDriver.Age), Fx(EffectTarget.Consciousness, EffectDriver.BloodLoss), Fx(EffectTarget.Consciousness, EffectDriver.BrainOxygen), Fx(curve: new[] { (1.0, 0.0), (1.0, 1.0) }) }; Plan(afflictions: new[] { new AfflictionDef("a", PhysiologyClock.Slow, -1, false, effects) }, blood: GoodBlood with { LethalLossFraction = 1, RegenPerSecond = 0 }, slots: 1); + Plan(organism: new[] { Fx(EffectTarget.Breathing, EffectDriver.BrainOxygen) }); // organism: a capacity driven by a store + Plan(organism: new[] { Fx(EffectTarget.BloodPumping, EffectDriver.BloodLoss) }); } [Fact] diff --git a/tests/Lodur.Core.Tests/PhysiologyPlansTests.cs b/tests/Lodur.Core.Tests/PhysiologyPlansTests.cs index fa8a9ef..608ae29 100644 --- a/tests/Lodur.Core.Tests/PhysiologyPlansTests.cs +++ b/tests/Lodur.Core.Tests/PhysiologyPlansTests.cs @@ -25,7 +25,7 @@ public sealed class PhysiologyPlansTests } [Fact] - public void The_brain_on_the_head_and_the_heart_on_the_torso_are_vital_and_a_skull_is_not() + public void The_brain_is_vital_the_heart_is_not_and_a_skull_is_not() { var head = Body.PartIndex("Head"); var torso = Body.PartIndex("Torso"); @@ -38,7 +38,8 @@ public sealed class PhysiologyPlansTests var heart = Spawn(); Assert.True(heart.Afflict(Cut, torso, heart.TissueIndex(torso, "Heart"), 16)); heart.Step(0.01); - Assert.Equal(DeathCause.VitalTissue, heart.Cause); + Assert.False(heart.Dead); // a stopped heart kills through brain oxygen and consciousness (ruling bds-heart-stop-stagger) + Assert.Equal(DeathCause.None, heart.Cause); var skull = Spawn(); Assert.True(skull.Afflict(Bruise, head, skull.TissueIndex(head, "Skull"), 26)); @@ -49,7 +50,7 @@ public sealed class PhysiologyPlansTests var lung = Spawn(); Assert.True(lung.Afflict(Bruise, torso, lung.TissueIndex(torso, "LungLeft"), 16)); lung.Step(0.01); - Assert.False(lung.Dead); // an organ with no vital flag yet; the airway cut gives lungs their function + Assert.False(lung.Dead); // a lung carries Breathing, not a vital flag; one lost still breathes } [Fact] diff --git a/tests/Lodur.Core.Tests/PhysiologyTests.cs b/tests/Lodur.Core.Tests/PhysiologyTests.cs index 97a007e..9acf3ab 100644 --- a/tests/Lodur.Core.Tests/PhysiologyTests.cs +++ b/tests/Lodur.Core.Tests/PhysiologyTests.cs @@ -21,7 +21,7 @@ public sealed class PhysiologyTests private static PartTissuesDef Stack(string part, params TissueDef[] tissues) => new(part, Side.Center, tissues); private static PhysiologyPlan Over(params PartTissuesDef[] parts) => - new(parts, Array.Empty(), Array.Empty(), DefaultBlood, 4); + new(parts, Array.Empty(), Array.Empty(), DefaultBlood, DefaultRespiration, 4); private static readonly TissueDef BrainT = new("brain", 10, 1, Consciousness: 1); private static readonly TissueDef MuscleT = new("muscle", 10, 1, Motor: 1);