Ragdoll keeps its airway sensor handles: TakeDrawn splits a breath's pooled draw by each opening's reading and LowestOpening names where liquid leaves

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 06:31:41 +01:00
commit a1028222d3
2 changed files with 220 additions and 37 deletions

View file

@ -21,7 +21,10 @@ namespace Lodur.Body.Ymir
private readonly Box3DSoaWorld _world;
private readonly int[] _bodyLane;
private readonly int[] _jointLane;
private readonly int[] _sensorLane;
// The airway sensors, one per plan opening, when Build created them (a world with no particle system has none); Ragdoll is their one owner. Ask and taken are TakeDrawn's scratch.
private readonly Box3DSoaConstraintHandle[] _sensors;
private readonly float[] _ask, _taken;
private bool _hasSensors;
private readonly MuscleGains[] _gains;
// Subtree mass and mass-weighted position per part: scratch rebuilt every Drive, never read across ticks.
private readonly float[] _mass, _momentX, _momentY, _momentZ;
@ -35,8 +38,9 @@ namespace Lodur.Body.Ymir
Plan = plan;
_bodyLane = new int[plan.Parts.Count];
_jointLane = new int[plan.Joints.Count];
_sensorLane = new int[plan.AirwayOpenings.Count];
Array.Fill(_sensorLane, -1);
_sensors = new Box3DSoaConstraintHandle[plan.AirwayOpenings.Count];
_ask = new float[plan.AirwayOpenings.Count];
_taken = new float[plan.AirwayOpenings.Count];
_gains = new MuscleGains[plan.Joints.Count];
_mass = new float[plan.Parts.Count];
_momentX = new float[plan.Parts.Count];
@ -111,9 +115,8 @@ namespace Lodur.Body.Ymir
sensors[k] = (r._bodyLane[a.Part], a.Offset, a.Radius);
}
var handles = new Box3DSoaConstraintHandle[sensors.Length];
world.CreateSensors(sensors, handles);
for (var k = 0; k < handles.Length; k++) r._sensorLane[k] = handles[k].Lane;
world.CreateSensors(sensors, r._sensors);
r._hasSensors = true;
}
return r;
@ -289,14 +292,71 @@ namespace Lodur.Body.Ymir
/// </summary>
public void ReadAirway(Span<float> live, Span<float> pooled, Span<float> drop, (float X, float Y, float Z) down)
{
var n = _sensorLane.Length;
var n = _sensors.Length;
if (live.Length != n || pooled.Length != n || drop.Length != n) throw new ArgumentException($"live, pooled and drop need {n} entries, one per airway opening.");
var (dx, dy, dz) = Unit(down);
var deepest = DeepestSump(dx, dy, dz);
var v = _world.View;
for (var k = 0; k < n; k++)
{
live[k] = _hasSensors ? v.SensorLiquidVolume[_sensors[k].Lane] : 0f;
pooled[k] = _hasSensors ? v.SensorWetVolume[_sensors[k].Lane] : 0f;
drop[k] = OpeningDrop(k, dx, dy, dz, deepest);
}
}
/// <summary>
/// Takes what a breath drew from the pool: <paramref name="drawnPooled"/> (Physiology's DrawnPooled, world m^3) split over the openings by each one's pooled reading at the last step's end
/// (exact, because Physiology's weighted sum is linear in the openings), and removed from the wet patches each opening reads. Returns the summed volume that left the world's patches, m^3:
/// 0 for a <paramref name="drawnPooled"/> of 0 or less, a world with no sensors or no pooled reading; float rounding can leave it below the ask. Readings change at the next step's end. Allocates nothing.
/// </summary>
public double TakeDrawn(double drawnPooled)
{
if (!_hasSensors || !(drawnPooled > 0d)) return 0d;
var v = _world.View;
var sum = 0d;
for (var k = 0; k < _sensors.Length; k++) sum += v.SensorWetVolume[_sensors[k].Lane];
if (!(sum > 0d)) return 0d;
for (var k = 0; k < _sensors.Length; k++) _ask[k] = (float)(drawnPooled * v.SensorWetVolume[_sensors[k].Lane] / sum);
_world.TakeWet(_sensors, _ask, _taken);
var taken = 0d;
for (var k = 0; k < _taken.Length; k++) taken += _taken[k];
return taken;
}
/// <summary>
/// The plan airway opening whose rim lies lowest along <paramref name="down"/> (the largest drop of <see cref="ReadAirway"/>, the first on a tie): where liquid leaves
/// (ruling bds-drain-head-decides, the head's pose alone decides). Refuses a zero <paramref name="down"/>. Allocates nothing.
/// </summary>
public int LowestOpening((float X, float Y, float Z) down)
{
var (dx, dy, dz) = Unit(down);
var deepest = DeepestSump(dx, dy, dz);
var best = 0;
var bestDrop = float.NegativeInfinity;
for (var k = 0; k < _sensors.Length; k++)
{
var drop = OpeningDrop(k, dx, dy, dz, deepest);
if (drop > bestDrop)
{
bestDrop = drop;
best = k;
}
}
return best;
}
private static (float X, float Y, float Z) Unit((float X, float Y, float Z) down)
{
var dl = MathF.Sqrt(down.X * down.X + down.Y * down.Y + down.Z * down.Z);
if (!(dl > 0f) || !float.IsFinite(dl)) throw new ArgumentException("down needs a nonzero finite direction.", nameof(down));
var dx = down.X / dl;
var dy = down.Y / dl;
var dz = down.Z / dl;
return (down.X / dl, down.Y / dl, down.Z / dl);
}
/// <summary>The deepest plan airway sump's position along the unit direction d.</summary>
private float DeepestSump(float dx, float dy, float dz)
{
var v = _world.View;
var deepest = float.NegativeInfinity;
for (var m = 0; m < Plan.AirwaySumps.Count; m++)
@ -307,32 +367,32 @@ namespace Lodur.Body.Ymir
deepest = MathF.Max(deepest, (v.PositionX[i] + rx) * dx + (v.PositionY[i] + ry) * dy + (v.PositionZ[i] + rz) * dz);
}
for (var k = 0; k < n; k++)
return deepest;
}
/// <summary>Opening k's lowest rim point's drop below <paramref name="deepest"/> along the unit direction d.</summary>
private float OpeningDrop(int k, float dx, float dy, float dz, float deepest)
{
var v = _world.View;
var a = Plan.AirwayOpenings[k];
var i = _bodyLane[a.Part];
var o = a.Offset;
var q = new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]);
q.Rotate(o.X, o.Y, o.Z, out var cx, out var cy, out var cz);
var centre = (v.PositionX[i] + cx) * dx + (v.PositionY[i] + cy) * dy + (v.PositionZ[i] + cz) * dz;
var ol = MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z);
var rim = a.Radius;
if (ol > 0f)
{
var lane = _sensorLane[k];
live[k] = lane < 0 ? 0f : v.SensorLiquidVolume[lane];
pooled[k] = lane < 0 ? 0f : v.SensorWetVolume[lane];
var a = Plan.AirwayOpenings[k];
var i = _bodyLane[a.Part];
var o = a.Offset;
var q = new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]);
q.Rotate(o.X, o.Y, o.Z, out var cx, out var cy, out var cz);
var centre = (v.PositionX[i] + cx) * dx + (v.PositionY[i] + cy) * dy + (v.PositionZ[i] + cz) * dz;
var ol = MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z);
var rim = a.Radius;
if (ol > 0f)
{
q.Rotate(o.X / ol, o.Y / ol, o.Z / ol, out var nx, out var ny, out var nz);
var along = dx * nx + dy * ny + dz * nz;
var px = dx - along * nx;
var py = dy - along * ny;
var pz = dz - along * nz;
rim *= MathF.Sqrt(px * px + py * py + pz * pz);
}
drop[k] = centre + rim - deepest;
q.Rotate(o.X / ol, o.Y / ol, o.Z / ol, out var nx, out var ny, out var nz);
var along = dx * nx + dy * ny + dz * nz;
var px = dx - along * nx;
var py = dy - along * ny;
var pz = dz - along * nz;
rim *= MathF.Sqrt(px * px + py * py + pz * pz);
}
return centre + rim - deepest;
}
}
}

View file

@ -28,10 +28,10 @@ public sealed class AirwayTests
private static readonly int Mouth = Plan.AirwayIndex("Mouth");
private static readonly int Nose = Plan.AirwayIndex("Nose");
private static Box3DSoaWorld ParticleWorld(int sensors, float gravityZ = 0f)
private static Box3DSoaWorld ParticleWorld(int sensors, float gravityZ = 0f, bool extra = false)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
return new Box3DSoaWorld(bodies, gravityY: 0f, gravityZ: gravityZ, jointCapacity: joints,
return new Box3DSoaWorld(bodies + (extra ? 1 : 0), gravityY: 0f, gravityZ: gravityZ, jointCapacity: joints + (extra ? 1 : 0),
particles: new Box3DSoaParticleCapacities(16, 16, 16, 16, 64, 2, 16, 8, sensors));
}
@ -180,7 +180,7 @@ public sealed class AirwayTests
}
/// <summary>The humanoid on a ground slab, limp, shoved by a seeded torque on pelvis and torso for six steps, then six seconds: the largest drop over its openings and the torso's face direction y.</summary>
private static (float Drop, float TorsoFaceY) Fall(ulong seed)
private static (float Drop, float TorsoFaceY) Fall(ulong seed, Action<Ragdoll>? atRest = null)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies + 1, jointCapacity: joints);
@ -210,6 +210,7 @@ public sealed class AirwayTests
var t = doll.BodyLane(Plan.PartIndex("Torso"));
new Quat(v.RotationX[t], v.RotationY[t], v.RotationZ[t], v.RotationW[t]).Rotate(0f, 0f, 1f, out _, out var faceY, out _);
atRest?.Invoke(doll);
var drop = DropOf(doll, (0f, -1f, 0f));
return (MathF.Max(drop[Mouth], drop[Nose]), faceY);
}
@ -268,6 +269,128 @@ public sealed class AirwayTests
Assert.Equal(-0.0167f, drop[Mouth], 0.002f);
}
/// <summary>Gravity toward the face (-z); one drop of each given radius rests against the head at each given opening and settles: the pooled patches at those openings.</summary>
private static (Box3DSoaWorld World, Ragdoll Doll) Pooled(params (int Opening, float Radius)[] drops)
{
var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors, gravityZ: -1f, extra: true);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var head = doll.BodyLane(Plan.PartIndex("Head"));
var hv = world.View;
var anchor = world.AddStaticBox(2, (hv.PositionX[head], hv.PositionY[head], hv.PositionZ[head] - 0.3f), (0.05f, 0.05f, 0.05f), friction: 0.8f);
world.AddJoint(Box3DSoaJointKind.Weld, anchor, head, (hv.PositionX[head], hv.PositionY[head], hv.PositionZ[head] - 0.1f), (0f, 1f, 0f));
world.CreateParticles([.. drops.Select(d => new Box3DSoaParticleDesc(Outside(world, doll, d.Opening, d.Radius), 8000f * d.Radius * d.Radius * d.Radius, d.Radius, FluidPhase))]);
var settled = new bool[drops.Length];
for (var i = 0; i < 120 && settled.Contains(false); i++)
{
world.Step(Dt, 4);
for (var p = 0; p < drops.Length; p++)
{
if (settled[p] || world.View.SupportBody[p] != head) continue;
world.Settle([new Box3DSoaParticleHandle(p, world.View.ParticleGeneration[p])]);
settled[p] = true;
}
}
Assert.DoesNotContain(false, settled);
world.Step(Dt, 4);
return (world, doll);
}
[Fact]
public void A_take_removes_what_was_drawn_from_the_mouths_pool()
{
var (world, doll) = Pooled((Mouth, R));
using var _ = world;
var before = Read(doll).Pooled[Mouth];
Assert.Equal(DropVolume, before, 9);
var ask = (double)before / 4d;
var taken = doll.TakeDrawn(ask);
Assert.Equal(ask, taken, ask * 1e-6);
world.Step(Dt, 4);
Assert.Equal(before - taken, Read(doll).Pooled[Mouth], before * 1e-5);
}
[Fact]
public void The_take_splits_by_the_openings_readings()
{
var (world, doll) = Pooled((Mouth, 0.005f), (Nose, 0.0075f));
using var _ = world;
var (_, before) = Read(doll);
Assert.True(before[Mouth] > 0f && before[Nose] > 1.5f * before[Mouth], $"readings {before[Mouth]} {before[Nose]}");
var sum = (double)before[Mouth] + before[Nose];
var x = sum / 10d;
var taken = doll.TakeDrawn(x);
Assert.Equal(x, taken, x * 1e-5);
world.Step(Dt, 4);
var (_, after) = Read(doll);
Assert.Equal(x * before[Mouth] / sum, before[Mouth] - after[Mouth], x * 1e-3);
Assert.Equal(x * before[Nose] / sum, before[Nose] - after[Nose], x * 1e-3);
}
[Fact]
public void A_dry_airway_or_a_world_without_particles_takes_nothing()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.Step(Dt, 4);
var (live, pooled) = Read(doll);
Assert.Equal(0.0, doll.TakeDrawn(1e-6));
world.Step(Dt, 4);
var (live2, pooled2) = Read(doll);
Assert.Equal(live, live2);
Assert.Equal(pooled, pooled2);
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var bare = new Box3DSoaWorld(bodies, jointCapacity: joints);
var bareDoll = Ragdoll.Build(bare, Plan, (0f, 0f), firstStableId: 100);
Assert.Equal(0.0, bareDoll.TakeDrawn(1e-6));
Assert.Equal(0.0, doll.TakeDrawn(-1.0));
}
[Fact]
public void Liquid_leaves_by_the_lowest_opening()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
Assert.Equal(Mouth, doll.LowestOpening((0f, -1f, 0f)));
var prone = DropOf(doll, (0f, 0f, 1f)); // face down the two rims are 0.2 mm apart (the nose's lower): the opening is the larger drop, not a fixed one
Assert.Equal(prone[Nose] > prone[Mouth] ? Nose : Mouth, doll.LowestOpening((0f, 0f, 1f)));
Assert.Equal(Mouth, doll.LowestOpening((0f, 0f, -1f)));
Assert.Equal(Nose, doll.LowestOpening((0f, 1f, 0f)));
// A head turned pi about x (a lone box with both openings and a sump at its centre) seen from above.
var head = new PartDef("Head", Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 1f, 0f), Quat.FromAxisAngle(1f, 0f, 0f, MathF.PI), 1000f, 0.5f, 0f);
var turned = new BodyPlan([head], [], [], [.. Plan.AirwayOpenings.Select(o => o with { Part = 0 })], [new AirwaySumpDef("Sump", 0, (0f, 0f, 0f))]);
var (bodies, joints, _) = Ragdoll.Needs(turned);
using var flipped = new Box3DSoaWorld(bodies, gravityY: 0f, jointCapacity: joints);
var flippedDoll = Ragdoll.Build(flipped, turned, (0f, 0f), firstStableId: 100);
Assert.Equal(Nose, flippedDoll.LowestOpening((0f, -1f, 0f)));
Assert.Equal(Mouth, flippedDoll.LowestOpening((0f, 1f, 0f)));
// Side-lying limp falls: the largest of DropOf, and not always the creation pose's opening.
var seen = new HashSet<int>();
foreach (var seed in new ulong[] { 6, 10, 11, 18, 39, 66, 92, 120, 133, 151, 171, 208 })
Fall(seed, d =>
{
var drop = DropOf(d, (0f, -1f, 0f));
var expect = drop[Nose] > drop[Mouth] ? Nose : Mouth;
Assert.Equal(expect, d.LowestOpening((0f, -1f, 0f)));
seen.Add(expect);
});
Assert.NotEmpty(seen);
}
[Fact]
public void TakeDrawn_allocates_nothing()
{
var (world, doll) = Pooled((Mouth, 0.005f), (Nose, 0.005f));
using var _ = world;
doll.TakeDrawn(1e-12);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 100; i++) doll.TakeDrawn(1e-12);
Assert.Equal(before, GC.GetAllocatedBytesForCurrentThread());
}
[Fact]
public void A_side_lying_limp_humanoid_drains()
{