diff --git a/src/BadDay.Cli/Program.cs b/src/BadDay.Cli/Program.cs index 9babd4b..ef64860 100644 --- a/src/BadDay.Cli/Program.cs +++ b/src/BadDay.Cli/Program.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using BadDay.Core; using BadDay.Ymir; @@ -16,6 +17,7 @@ public static class Program baddaysim sweep --seed N --count M [options] seeds N..N+M-1, break-time summary baddaysim office --seed N [office options] the office: stressors fill the stress bar, the will breaks, the rage follows + baddaysim office --seed N --body [office options] the same run on the Ymir ragdoll: rage time and strikes baddaysim office-sweep --seed N --count M [office options] options (all numbers, seconds unless noted): @@ -98,7 +100,7 @@ public static class Program private static int ExecuteOffice(bool sweep, ulong seed, Dictionary opts, System.IO.TextWriter output) { - if (opts.ContainsKey("body")) throw new ArgumentException("--body applies to run"); + if (opts.ContainsKey("body") && sweep) throw new ArgumentException("--body applies to run and office"); if (opts.ContainsKey("pay")) throw new ArgumentException("--pay applies to run and sweep; the office takes --pull"); var defaults = new StressParameters(); var p = defaults with @@ -107,6 +109,7 @@ public static class Program MaxSeconds = Num(opts, "max", defaults.MaxSeconds), SampleEverySeconds = Num(opts, "every", defaults.SampleEverySeconds), }; + if (opts.ContainsKey("body") && opts.ContainsKey("silence")) throw new ArgumentException("--silence does not apply to --body"); var silences = new List(); if (opts.TryGetValue("silence", out var list)) { @@ -118,6 +121,24 @@ public static class Program } } + if (opts.ContainsKey("body")) + { + var b = OfficeBody.Run(p with { TickSeconds = OfficeBody.TickSeconds }, seed); + output.WriteLine(OfficeTitle); + output.Write(b.Run.Render()); + output.WriteLine(b.Run.Summary()); + if (b.RageTick is { } rage) + { + int end = b.HandL.Count; + output.WriteLine($"rage from {b.Run.Timeline.First(e => e.Kind == StressEntryKind.GoalChanged).TimeMs} ms for " + + $"{((end - rage) / (double)OfficeBody.Hz).ToString("F1", CultureInfo.InvariantCulture)} s; strikes {b.Strikes(rage, end)} " + + $"(left {OfficeBody.CountStrikes(b.HandL, rage, end)}, right {OfficeBody.CountStrikes(b.HandR, rage, end)}), " + + $"{b.Strikes(0, rage)} before it"); + } + else output.WriteLine($"no rage: the will held to {b.Run.EndMs} ms"); + return 0; + } + if (!sweep) { var r = StressSimulation.Run(p, seed, silences); diff --git a/src/BadDay.Core/Setting.cs b/src/BadDay.Core/Setting.cs index cd9f4fb..96bb8b3 100644 --- a/src/BadDay.Core/Setting.cs +++ b/src/BadDay.Core/Setting.cs @@ -25,4 +25,17 @@ public sealed record Setting(IReadOnlyList Emitters) new NamedEmitter("desk-phone", new Emitter(Channel.Audio, 0f, 0f, 0f, 10f)), new NamedEmitter("desktop", new Emitter(Channel.Interrupt, 0f, 0f, 0f, 10f)), }); + + /// The same emitters moved by (, , ): a body that senses somewhere other than the origin wants the room around it. + public Setting Shifted(float dx, float dy, float dz) + { + var moved = new NamedEmitter[Emitters.Count]; + for (int i = 0; i < moved.Length; i++) + { + var e = Emitters[i].Emitter; + e.X += dx; e.Y += dy; e.Z += dz; + moved[i] = Emitters[i] with { Emitter = e }; + } + return new Setting(moved); + } } diff --git a/src/BadDay.Ymir/OfficeBody.cs b/src/BadDay.Ymir/OfficeBody.cs new file mode 100644 index 0000000..554ce16 --- /dev/null +++ b/src/BadDay.Ymir/OfficeBody.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BadDay.Core; +using Lodur; +using Lodur.Body.Ymir; +using Ymir.Box3D; + +namespace BadDay.Ymir; + +/// A point in the world, metres. +public readonly record struct BodyPoint(float X, float Y, float Z); + +/// +/// The office on the body: the same timeline as the headless run, plus what only a body has. +/// , and hold the point after every step; the index is the tick. +/// +public sealed record OfficeBodyResult( + StressResult Run, IReadOnlyList HandL, IReadOnlyList HandR, IReadOnlyList Pelvis) +{ + /// The tick the rage took over (the GoalChanged row); null if the will held. + public int? RageTick => Run.Timeline.Any(e => e.Kind == StressEntryKind.GoalChanged) + ? (int)Math.Round(Run.Timeline.First(e => e.Kind == StressEntryKind.GoalChanged).TimeMs * OfficeBody.Hz / 1000.0) + : null; + + /// Strikes by both hands from tick up to , see . + public int Strikes(int from, int to) => OfficeBody.CountStrikes(HandL, from, to) + OfficeBody.CountStrikes(HandR, from, to); +} + +/// +/// Office Fella on the seated puppet: 's world, the desk's emitters moved to where the head +/// sits and sensed there, and the same the headless run drives. Per step: the body reports its +/// points, the session decides (Lodur's Actor commits the Brain's goals, ), the ragdoll is driven, +/// the world steps. The run ends as the session ends, the release after the rage takes over. +/// +public static class OfficeBody +{ + public const int Hz = 120; + + /// The ragdoll's gains are tuned at 120 Hz. + public const double TickSeconds = 1.0 / Hz; + + /// A strike begins when a hand's forward (+z) speed passes this, m/s [P]. + public const float StrikeSpeed = 1.0f; + + /// A strike is over when the forward speed falls back under this fraction of . + public const float StrikeEnds = 0.5f; + + /// + /// The office puppet's poses [P]. Composed: every muscle at the creation pose, arms down. Rage: each arm winds up (the + /// elbow folded, the fist at the chest) and strikes (the shoulder forward, the elbow straight), left then right. + /// + public static OfficePoses Poses { get; } = BuildPoses(); + + /// Runs the office on the puppet to the end of the release; the tick rate must be 1/120 s. + public static OfficeBodyResult Run(StressParameters p, ulong seed) + { + if (Math.Abs(p.TickSeconds - TickSeconds) > 1e-12) + { + throw new ArgumentException($"The body run steps at 1/120 s; got TickSeconds {p.TickSeconds}."); + } + + var needs = SeatedPuppet.Needs; + using var world = new Box3DSoaWorld(capacity: needs.Bodies, jointCapacity: needs.Joints); + var ragdoll = SeatedPuppet.Build(world); + var x = new float[HumanoidRagdoll.RegionCount]; + var y = new float[HumanoidRagdoll.RegionCount]; + var z = new float[HumanoidRagdoll.RegionCount]; + ragdoll.ReadRegions(x, y, z); + int head = (int)Region.Head; + // The desk's emitters sit where the head does and are sensed there. + var session = new StressSession(p with { Setting = p.Setting.Shifted(x[head], y[head], z[head]) }, seed, + HumanoidRagdoll.RegionCount, Poses, head); + + var strengths = new float[HumanoidRagdoll.MuscleCount]; + var targets = new Quat[HumanoidRagdoll.MuscleCount]; + var handL = new List(); + var handR = new List(); + var pelvis = new List(); + int pelvisLane = ragdoll.BodyLane(Limb.Pelvis); + while (!session.Finished) + { + ragdoll.ReadRegions(x, y, z); + session.Tick(x, y, z, strengths, targets); + ragdoll.Drive(strengths, targets); + world.Step((float)p.TickSeconds, SeatedPuppet.Substeps); + + ragdoll.ReadRegions(x, y, z); + handL.Add(new BodyPoint(x[(int)Region.HandL], y[(int)Region.HandL], z[(int)Region.HandL])); + handR.Add(new BodyPoint(x[(int)Region.HandR], y[(int)Region.HandR], z[(int)Region.HandR])); + var v = world.View; + pelvis.Add(new BodyPoint(v.PositionX[pelvisLane], v.PositionY[pelvisLane], v.PositionZ[pelvisLane])); + } + return new OfficeBodyResult(session.Result(), handL, handR, pelvis); + } + + /// + /// Strikes in 's steps from up to : forward (+z) speed + /// excursions, each from passing to falling under of it, so a strike + /// that wobbles at its peak counts once. + /// + public static int CountStrikes(IReadOnlyList hand, int from, int to) + { + int strikes = 0; + bool inStrike = false; + for (int i = Math.Max(from, 1); i < Math.Min(to, hand.Count); i++) + { + float forward = (hand[i].Z - hand[i - 1].Z) * Hz; + if (!inStrike && forward >= StrikeSpeed) { inStrike = true; strikes++; } + else if (inStrike && forward < StrikeSpeed * StrikeEnds) inStrike = false; + } + return strikes; + } + + private static OfficePoses BuildPoses() + { + Quat[] Pose() { var q = new Quat[HumanoidRagdoll.MuscleCount]; Array.Fill(q, Quat.Identity); return q; } + + var composed = Pose(); + var keys = new[] { Pose(), Pose(), Pose(), Pose() }; + // Key order: wind-up left, strike left, wind-up right, strike right. The arm not striking stays wound up. + foreach (var k in keys) { Arm(k, left: true, strike: false); Arm(k, left: false, strike: false); } + Arm(keys[1], left: true, strike: true); + Arm(keys[3], left: false, strike: true); + return new OfficePoses(composed, Pose(), keys); + } + + private static void Arm(Quat[] pose, bool left, bool strike) + { + pose[(int)(left ? Muscle.ShoulderL : Muscle.ShoulderR)] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? -1.5f : -0.5f); + pose[(int)(left ? Muscle.ElbowL : Muscle.ElbowR)] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? 0f : -2.2f); + } +} diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs index ec06252..31c9235 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -760,6 +760,41 @@ public static class Program Check(brain.Goals[OfficeBrain.ComposureIndex].Pull == p.Cause.ObjectivePull && brain.Goals[OfficeBrain.RageIndex].Pull == 0.0, "the pulls are not the cause's and zero"); }), + ("office body: the rage is visible: both hands move at least 3x faster, and over 0.5 m/s, in the 2 s after the switch than in the 2 s before, the pelvis stays within 1 cm, and two runs agree", () => + { + var p = new StressParameters { TickSeconds = OfficeBody.TickSeconds }; + var a = OfficeBody.Run(p, 1); + var b = OfficeBody.Run(p, 1); + Check(a.Run.Render() == b.Run.Render() && a.HandL.SequenceEqual(b.HandL) && a.HandR.SequenceEqual(b.HandR) && a.Pelvis.SequenceEqual(b.Pelvis), "two body runs differ"); + Check(a.Run.Outcome == Outcome.WillBroke && a.RageTick is not null, $"outcome {a.Run.Outcome}"); + int sw = a.RageTick!.Value; + Check(a.HandL.Count == sw + 6 * Hz + 1, $"the run has {a.HandL.Count} steps, the switch is at {sw}"); + double Rms(IReadOnlyList h, int from, int to) + { + double sum = 0; + for (int i = from + 1; i < to; i++) + { + double dx = h[i].X - h[i - 1].X, dy = h[i].Y - h[i - 1].Y, dz = h[i].Z - h[i - 1].Z; + sum += (dx * dx + dy * dy + dz * dz) * Hz * Hz; + } + return Math.Sqrt(sum / (to - from - 1)); + } + foreach (var (name, hand) in new[] { ("left", a.HandL), ("right", a.HandR) }) + { + double before = Rms(hand, sw - 2 * Hz, sw), after = Rms(hand, sw, sw + 2 * Hz); + Check(after >= 3 * before && after > 0.5, $"{name} hand: {after:F3} m/s after the switch, {before:F3} m/s before"); + } + Check(a.Strikes(0, sw) == 0 && a.Strikes(sw, a.HandL.Count) >= 8, $"strikes: {a.Strikes(0, sw)} before the switch, {a.Strikes(sw, a.HandL.Count)} after"); + float drift = a.Pelvis.Max(q => MathF.Sqrt(MathF.Pow(q.X - a.Pelvis[0].X, 2) + MathF.Pow(q.Y - a.Pelvis[0].Y, 2) + MathF.Pow(q.Z - a.Pelvis[0].Z, 2))); + Check(drift < 0.01f, $"the pelvis moved {drift:F4} m"); + }), + + ("office body: the desk's emitters are sensed at the head, so the body breaks within 5 s of the headless run", () => + { + var body = OfficeBody.Run(new StressParameters { TickSeconds = OfficeBody.TickSeconds }, 1).Run; + var headless = Office(new StressParameters(), 1); + Check(Math.Abs(body.TimeToBreakMs!.Value - headless.TimeToBreakMs!.Value) < 5000, $"body {body.TimeToBreakMs} ms, headless {headless.TimeToBreakMs} ms"); + }), }; private static readonly float[] Point = new float[1], Strengths = new float[1];