diff --git a/client/BodyRenderer.cs b/client/BodyRenderer.cs index 6225ffc..0a60f66 100644 --- a/client/BodyRenderer.cs +++ b/client/BodyRenderer.cs @@ -14,9 +14,17 @@ public partial class BodyRenderer : Node3D private readonly Dictionary _scenery = new(); private readonly StandardMaterial3D _material = Look.Matte(Look.Scenery); - public int NodeCount => _puppet.NodeCount + _scenery.Count; + /// Bodies drawn, static and dynamic. + public int BodyCount => _puppet.BodyCount + _scenery.Count; - public MeshInstance3D? NodeFor(ulong stableId) => _puppet.NodeFor(stableId) ?? _scenery.GetValueOrDefault(stableId); + public BaseMaterial3D PuppetMaterial => _puppet.Material; + public BaseMaterial3D SceneryMaterial => _material; + + /// Where body is drawn now, or null if it is not drawn. + public Transform3D? PoseOf(ulong stableId) => _puppet.PoseOf(stableId) ?? (_scenery.TryGetValue(stableId, out var n) ? n.Transform : null); + + /// The same pose as rendered this frame, between the last two ticks (a static body does not move). + public Transform3D? InterpolatedPoseOf(ulong stableId) => _puppet.InterpolatedPoseOf(stableId) ?? PoseOf(stableId); public override void _Ready() => AddChild(_puppet); diff --git a/client/Chamber.cs b/client/Chamber.cs index 34498f6..42cd0b8 100644 --- a/client/Chamber.cs +++ b/client/Chamber.cs @@ -26,12 +26,19 @@ public partial class Chamber : Node3D AddChild(_glow); } - public void Sync(BodyPainBoxSession session) + /// The material of the volume. + public StandardMaterial3D Material => _material; + + /// The glow last drawn, 0 (dark) to 1. + public float Glow { get; private set; } + + public void Sync(BodyPainBoxSession session, double intensity) { var box = session.Chamber; Position = new Vector3(box.CenterX, box.CenterY, box.CenterZ); _volume.Scale = new Vector3(2f * box.HalfX, 2f * box.HalfY, 2f * box.HalfZ); - float glow = (float)Math.Min(1.0, box.Intensity / 1.5); + float glow = (float)Math.Min(1.0, intensity / 1.5); + Glow = glow; _material.AlbedoColor = new Color(Look.Glow, 0.06f + 0.3f * glow); _material.EmissionEnergyMultiplier = 0.1f + 2.5f * glow; _glow.LightEnergy = 3f * glow; diff --git a/client/Hud.cs b/client/Hud.cs index f6ab3ce..ac4a9e8 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -8,14 +8,24 @@ namespace BadDay.Client; /// Readout and controls. Every number comes from the session; every control calls a Main method that calls it. public partial class Hud : CanvasLayer { + private const int LogLines = 6; + private static readonly Color Ink = new(0.92f, 0.92f, 0.9f); + private readonly Main _main; private readonly Label _readout = new(); - private readonly SpinBox _seed = new() { MinValue = 0, MaxValue = 999999999, Step = 1, Value = 1 }; - private readonly HSlider _intensity = new() { MinValue = 0, MaxValue = PainBox.MaxLevel, Step = 0.05, CustomMinimumSize = new Vector2(220, 24) }; private readonly StringBuilder _text = new(); public Hud(Main main) => _main = main; + public SpinBox SeedBox { get; } = new() { MinValue = 0, MaxValue = 999999999, Step = 1, Value = 1 }; + public Button ResetButton { get; } = new() { Text = "Reset" }; + public HSlider IntensitySlider { get; } = new() { MinValue = 0, MaxValue = PainBox.MaxLevel, Step = 0.05, CustomMinimumSize = new Vector2(220, 24) }; + public Button BoxOffButton { get; } = new() { Text = "Box off" }; + public CheckButton SlowToggle { get; } = new() { Text = "Slow motion", Modulate = Ink }; + + /// The readout as drawn. + public string Readout => _readout.Text; + public override void _Ready() { var margin = new MarginContainer(); @@ -27,7 +37,7 @@ public partial class Hud : CanvasLayer var row = new HBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore }; margin.AddChild(row); - _readout.AddThemeColorOverride("font_color", new Color(0.92f, 0.92f, 0.9f)); + _readout.AddThemeColorOverride("font_color", Ink); _readout.AddThemeFontSizeOverride("font_size", 16); _readout.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; _readout.MouseFilter = Control.MouseFilterEnum.Ignore; @@ -37,44 +47,48 @@ public partial class Hud : CanvasLayer row.AddChild(controls); var seedRow = new HBoxContainer(); - seedRow.AddChild(new Label { Text = "Seed", Modulate = new Color(0.92f, 0.92f, 0.9f) }); - seedRow.AddChild(_seed); + seedRow.AddChild(new Label { Text = "Seed", Modulate = Ink }); + seedRow.AddChild(SeedBox); controls.AddChild(seedRow); - controls.AddChild(Button("Reset", () => _main.Reset((ulong)_seed.Value))); + ResetButton.Pressed += () => _main.Reset((ulong)SeedBox.Value); + controls.AddChild(ResetButton); - controls.AddChild(new Label { Text = "Intensity", Modulate = new Color(0.92f, 0.92f, 0.9f) }); - _intensity.Value = _main.Intensity; - _intensity.ValueChanged += v => _main.SetIntensity(v); - controls.AddChild(_intensity); + controls.AddChild(new Label { Text = "Intensity", Modulate = Ink }); + IntensitySlider.Value = _main.Intensity; + IntensitySlider.ValueChanged += v => _main.SetIntensity(v); + controls.AddChild(IntensitySlider); - controls.AddChild(Button("Box off", () => _main.SwitchOff())); - var slow = new CheckButton { Text = "Slow motion", Modulate = new Color(0.92f, 0.92f, 0.9f) }; - slow.Toggled += on => _main.SetSlowMotion(on); - controls.AddChild(slow); + BoxOffButton.Pressed += () => _main.SwitchOff(); + controls.AddChild(BoxOffButton); + SlowToggle.Toggled += on => _main.SetSlowMotion(on); + controls.AddChild(SlowToggle); } public override void _Process(double delta) { + if (_main.Failure is { } failure) + { + _readout.Text = $"Cannot run: {failure}\nReset tries again."; + return; + } + var s = _main.Session; var r = s.Result(); _text.Clear(); _text.Append($"seed {_main.Seed} t {s.TickIndex * BodyPainBox.TickSeconds:F2} s (tick {s.TickIndex})\n"); - _text.Append($"box intensity {s.BoxIntensity:F2} (set {_main.Intensity:F2})\n"); + _text.Append($"box intensity {_main.ShownBoxIntensity:F2} (set {_main.Intensity:F2})\n"); _text.Append($"pain {s.Pain:F2} strain {s.Strain:F2} resolve {s.Resolve:F2}\n"); _text.Append($"goal {s.Goal} flinches {r.Flinches}\n"); _text.Append($"will broke at {Ms(r.TimeToBreakMs)} withdrew {(s.Goal == Lodur.Goal.Withdraw ? "yes" : "no")}\n"); _text.Append($"hand {(s.Hand.InBox ? "in box" : "out of box")} hand out at {Ms(s.HandOutMs)}\n"); _text.Append(s.Finished ? $"outcome {r.Outcome}\n" : "running\n"); - foreach (var line in _main.Log) _text.Append(line).Append('\n'); + var events = _main.Events; + for (int i = System.Math.Max(0, events.Count - LogLines); i < events.Count; i++) + { + _text.Append($"{events[i].Tick * BodyPainBox.TickSeconds,6:F2} s {events[i].Events}\n"); + } _readout.Text = _text.ToString(); } private static string Ms(long? ms) => ms is { } v ? $"{v / 1000.0:F2} s" : "-"; - - private static Button Button(string text, System.Action pressed) - { - var b = new Button { Text = text }; - b.Pressed += pressed; - return b; - } } diff --git a/client/Main.cs b/client/Main.cs index a80980b..8287141 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -7,37 +7,54 @@ using Godot; namespace BadDay.Client; /// -/// The client's root. Godot's physics frame decides when a tick happens (120 Hz, physics interpolation on, Godot's own +/// The client's root. Godot's physics frame decides when a tick happens (physics interpolation on, Godot's own /// physics engine Dummy); decides everything a tick does. This node only steps it, -/// draws it and forwards the player's commands to it. +/// draws it and forwards the player's commands to it. A session that cannot start (the native library is missing, say) +/// is reported once in and the log, and nothing ticks until a Reset succeeds. /// public partial class Main : Node3D { - private const int LogLines = 6; + /// Slow motion runs this fraction of the session steps per real second. + private const double SlowFactor = 0.25; - private readonly List _log = new(); + private readonly List _events = new(); private BodyRenderer _bodies = null!; private Chamber _chamber = null!; private OrbitCamera _camera = null!; private Hud _hud = null!; private BodyPainBoxSession? _session; private double _intensity = new PainBoxParameters().BoxIntensity; - private bool _deltaReported; - public BodyPainBoxSession Session => _session ?? throw new InvalidOperationException("Main has no session before _Ready."); + public BodyPainBoxSession Session => _session ?? throw new InvalidOperationException($"Main has no session ({Failure ?? "before _Ready"})."); public BodyRenderer Bodies => _bodies; + public Chamber Chamber => _chamber; + public Hud Hud => _hud; public ulong Seed { get; private set; } = 1; + /// Why the session could not start, or null. Cleared by the next successful Reset. + public string? Failure { get; private set; } + /// The intensity the box is set to; the next Reset starts with it. public double Intensity => _intensity; - public bool SlowMotion => Engine.TimeScale < 1.0; - public IReadOnlyList Log => _log; + public bool SlowMotion { get; private set; } + + /// Every event the session has reported since the last Reset, oldest first. + public IReadOnlyList Events => _events; + + /// + /// The box's intensity as the player should see it. The session stops writing it once a run ends because the box + /// was switched off, so the last written value would stay on screen; that run ended with the box off. + /// + public double ShownBoxIntensity => + _session is { } s ? (s.Finished && s.Result().Outcome == Outcome.BoxDisabled ? 0.0 : s.BoxIntensity) : 0.0; /// The parameters of a run at the given box intensity: every default except the 1/120 s tick the body needs. public static PainBoxParameters ParametersFor(double intensity) => new() { TickSeconds = BodyPainBox.TickSeconds, BoxIntensity = intensity }; + private static int StepsPerSecond(double speed) => (int)Math.Round(speed / BodyPainBox.TickSeconds); + public override void _Ready() { AddChild(new WorldEnvironment { Environment = Look.Environment() }); @@ -55,7 +72,7 @@ public partial class Main : Node3D public override void _ExitTree() { - Engine.TimeScale = 1.0; + Engine.PhysicsTicksPerSecond = StepsPerSecond(1.0); _session?.Dispose(); _session = null; } @@ -63,12 +80,7 @@ public partial class Main : Node3D public override void _PhysicsProcess(double delta) { if (_session is null) return; - if (Math.Abs(delta - BodyPainBox.TickSeconds) > 1e-9 && !_deltaReported) - { - _deltaReported = true; - GD.PushError($"BadDay: physics delta {delta} is not 1/120; the session steps 1/120 s regardless."); - } - _session.Step(); // never Godot's delta: the ragdoll's gains are tuned at 1/120 + _session.Step(); // one step of 1/120 s per physics frame; never Godot's delta, whatever the frame rate Present(teleport: false); } @@ -77,9 +89,19 @@ public partial class Main : Node3D { _session?.Dispose(); _session = null; - _session = new BodyPainBoxSession(ParametersFor(_intensity), seed); + Failure = null; + _events.Clear(); Seed = seed; - _log.Clear(); + try + { + _session = new BodyPainBoxSession(ParametersFor(_intensity), seed); + } + catch (Exception e) // the session's start can fail in native code (library missing, ABI mismatch): report once, tick nothing + { + Failure = $"{e.GetType().Name}: {e.Message}"; + GD.PushError($"BadDay: cannot start a run: {e}"); + return; + } Present(teleport: true); } @@ -92,22 +114,27 @@ public partial class Main : Node3D public void SwitchOff() => _session?.SwitchOff(); - public void SetSlowMotion(bool on) => Engine.TimeScale = on ? 0.25 : 1.0; + /// + /// Slow motion is fewer session steps per real second: Godot runs its physics frames at a quarter of the rate and each + /// frame still steps the session 1/120 s, so the run is the same run, slower, and interpolation smooths the pose + /// between ticks. (Engine.TimeScale would only scale the delta, which the session never uses.) + /// + public void SetSlowMotion(bool on) + { + SlowMotion = on; + Engine.PhysicsTicksPerSecond = StepsPerSecond(on ? SlowFactor : 1.0); + } private void Present(bool teleport) { var s = Session; _bodies.Sync(s.View, teleport); - _chamber.Sync(s); + _chamber.Sync(s, ShownBoxIntensity); Span events = stackalloc BodyEvent[8]; int n; while ((n = s.DrainEvents(events)) > 0) { - for (int i = 0; i < n; i++) - { - _log.Add($"{events[i].Tick * BodyPainBox.TickSeconds,6:F2} s {events[i].Events}"); - if (_log.Count > LogLines) _log.RemoveAt(0); - } + for (int i = 0; i < n; i++) _events.Add(events[i]); } } } diff --git a/client/Puppet.cs b/client/Puppet.cs index cfc02d4..056e14e 100644 --- a/client/Puppet.cs +++ b/client/Puppet.cs @@ -15,9 +15,16 @@ public partial class Puppet : Node3D private readonly HashSet _seen = new(); private readonly StandardMaterial3D _dynamic = Look.Matte(Look.Figure); - public int NodeCount => _nodes.Count; + public int BodyCount => _nodes.Count; - public MeshInstance3D? NodeFor(ulong stableId) => _nodes.GetValueOrDefault(stableId); + /// The material the puppet is drawn in. + public BaseMaterial3D Material => _dynamic; + + /// Where the puppet draws body now (world), or null if it draws no such body. + public Transform3D? PoseOf(ulong stableId) => _nodes.TryGetValue(stableId, out var n) ? n.Transform : null; + + /// The same pose as it is rendered this frame, between the last two ticks. + public Transform3D? InterpolatedPoseOf(ulong stableId) => _nodes.TryGetValue(stableId, out var n) ? n.GetGlobalTransformInterpolated() : null; /// Makes the nodes match the lanes: creates the missing, frees the gone, then poses every node. skips the interpolation from the previous pose. public void Sync(in Box3DSoaView view, bool teleport = false) diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index c427687..b286e72 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -1,108 +1,251 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; using BadDay.Core; -using BadDay.Client; using BadDay.Ymir; using Godot; -using Ymir.Box3D; namespace BadDay.Client.Tests; /// -/// The headless smoke: runs the real Main scene and checks what the client promises. Exit code 0 passes, 1 fails. +/// The headless smoke: runs the real Main scene, drives it through the HUD's own controls and checks what the client +/// promises against a headless BDS run in the same process. Exit code 0 passes, 1 fails. /// godot --headless --path client res://tests/Smoke.tscn /// public partial class Smoke : Node { private const ulong Seed = 1; - private const long ParityTick = 240; - private const long BoxOffTick = 600; - private const long Watchdog = 2000; + private const double WatchdogSeconds = 150; private readonly List _failures = new(); private Main _main = null!; - private HandSample _reference; - private long _frames; - private bool _parityChecked, _boxOffIssued; + private BodyPainBoxSession? _lastSession; + private long _lastTick; + private bool _done; - public override void _Ready() + private Hud Hud => _main.Hud; + private BodyPainBoxSession Session => _main.Session; + + public override void _Ready() => _ = RunAsync(); + + public override void _Process(double delta) { - try { Arrange(); } - catch (Exception e) { Check(false, e.ToString()); } + if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000) + { + Check(false, $"no result after {WatchdogSeconds} s"); + Finish(); + } } - private void Arrange() + private async Task RunAsync() + { + try + { + _main = GD.Load("res://Main.tscn").Instantiate
(); + AddChild(_main); + if (_main.Failure is { } failure) Check(false, "Main could not start a session: " + failure); + else await Scenario(); + } + catch (Exception e) + { + Check(false, e.ToString()); + } + Finish(); + } + + private async Task Scenario() + { + CheckEngineAndScene(); + + // Slow motion, by wall clock: a quarter of the session steps per real second, the same run. + await Frames(10); + double normal = await StepsPerSecond(1000); + Hud.SlowToggle.ButtonPressed = true; // the real control + double slow = await StepsPerSecond(2000); + Check(slow > 0.15 * normal && slow < 0.4 * normal, $"slow motion runs {slow:F0} steps per second against {normal:F0}; wanted about a quarter"); + Hud.SlowToggle.ButtonPressed = false; + Check(Engine.PhysicsTicksPerSecond == 120, $"slow motion off leaves {Engine.PhysicsTicksPerSecond} physics ticks per second"); + + // The rest runs the physics clock fast; the session still steps 1/120 s per frame. + Engine.PhysicsTicksPerSecond = 1200; + + // Seed 1 at the default intensity against the headless run: events, and the hand at ticks 240 and 1500. + PressReset(1); + var reference = Run(new PainBoxParameters().BoxIntensity, 1, 1500); + await UntilTick(240); + CheckHand(reference.Hand[239], "tick 240"); + CheckPoses("tick 240"); + await UntilTick(1500); + CheckEvents(reference, "seed 1, default intensity"); + CheckHand(reference.Hand[^1], "tick 1500"); + + // The slider sets the next run's intensity; a high one breaks the will, and the run ends. + Hud.IntensitySlider.Value = 6; + Check(_main.Intensity == 6, $"the slider set intensity {_main.Intensity}, not 6"); + PressReset(3); + reference = Run(6, 3, 1500); + await UntilTick(1500); + CheckEvents(reference, "seed 3, intensity 6"); + Check(Session.Finished && _main.Events.Any(e => (e.Events & Lodur.TickEvents.WillBroke) != 0), "intensity 6 did not break the will"); + + // A reset puts every body at its pose now, not on the way from where the last run left it. A reset from the UI + // lands between physics frames, and on a slow physics clock the next render frame comes before the next tick. + Engine.PhysicsTicksPerSecond = 10; + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + PressReset(4); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + foreach (var id in Session.View.StableId.ToArray()) + { + var shown = _main.Bodies.InterpolatedPoseOf(id); + var pose = _main.Bodies.PoseOf(id); + Check(shown is { } a && pose is { } b && a.Origin.DistanceTo(b.Origin) < 1e-2f, $"after Reset body {id} is rendered at {shown?.Origin}, not at {pose?.Origin}"); + } + Engine.PhysicsTicksPerSecond = 1200; + + // Every reset honours its seed, whatever it replaces. + Hud.IntensitySlider.Value = new PainBoxParameters().BoxIntensity; + foreach (ulong seed in new ulong[] { 2, 7, 123456789 }) + { + PressReset(seed); + reference = Run(_main.Intensity, seed, 150); + await UntilTick(150); + Check(Session.Pain == reference.Pain && Session.Strain == reference.Strain, $"seed {seed}: pain {Session.Pain} differs from the headless run's {reference.Pain}"); + CheckHand(reference.Hand[^1], $"seed {seed} tick 150"); + } + + // Many resets without leaking native worlds (the native library caps them near 128). + for (int i = 0; i < 400; i++) + { + PressReset(1000 + (ulong)i); + await Frame(); + } + Check(_main.Seed == 1399, $"after 400 resets the seed is {_main.Seed}"); + + // Box off, through the HUD button, at tick 600: the run ends with the will intact and the screen shows the box off. + PressReset(Seed); + await UntilTick(600); + Check(!Session.Finished, "the run was over before tick 600; the box-off probe needs the will intact"); + Hud.BoxOffButton.EmitSignal(BaseButton.SignalName.Pressed); + await Frame(); + Check(Session.Finished && Session.Result().Outcome == Outcome.BoxDisabled, "Box off did not end the run as BoxDisabled within one tick"); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); // the HUD draws in _Process, after this frame's signal + Check(_main.Chamber.Glow == 0f, $"the chamber still glows ({_main.Chamber.Glow}) with the box off"); + Check(Hud.Readout.Contains("box intensity 0.00"), "the readout does not show the box off: " + Hud.Readout.Split('\n')[1]); + } + + private void CheckEngineAndScene() { Check(Engine.PhysicsTicksPerSecond == 120, $"physics ticks per second is {Engine.PhysicsTicksPerSecond}, not 120"); Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot's 3D physics engine is not Dummy"); - - // The reference: the same run, headless, in this process. - var reference = BodyPainBox.Run(Main.ParametersFor(new PainBoxParameters().BoxIntensity), Seed); - _reference = reference.Hand[(int)ParityTick - 1]; - - _main = GD.Load("res://Main.tscn").Instantiate
(); - AddChild(_main); Check(!_main.GetWorld3D().Space.IsValid, "Godot has a physics space"); - Check(_main.Seed == Seed, "Main did not start from the smoke's seed"); Check(Count(_main, n => n is CollisionObject3D || n.GetClass().StartsWith("Collision")) == 0, "Godot physics nodes are in the scene"); + Check(_main.IsPhysicsInterpolatedAndEnabled() && (bool)ProjectSettings.GetSetting("physics/common/physics_interpolation"), "physics interpolation is off"); + Check(_main.Seed == Seed, "Main did not start from the smoke's seed"); + + // The look: white on dark grey, flat. + var puppet = _main.Bodies.PuppetMaterial.AlbedoColor; + Check(puppet.Luminance > 0.7f && puppet.S < 0.1f, $"the puppet is {puppet}, not white"); + Check(_main.Bodies.SceneryMaterial.AlbedoColor.Luminance < 0.3f, "the floor is not dark"); + var glow = _main.Chamber.Material.AlbedoColor; + Check(glow.V > 0.7f && glow.S < 0.3f, $"the chamber is {glow}, not light"); + var environment = _main.GetChildren().OfType().Single().Environment; + Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey"); } - public override void _PhysicsProcess(double delta) + private void CheckPoses(string when) { - if (_main is null) { Finish(); return; } - _frames++; - var s = _main.Session; - if (!_boxOffIssued && s.TickIndex != _frames - 1 && !_failures.Exists(f => f.StartsWith("ticks"))) // this node runs before Main: frame n sees n-1 steps - Check(false, $"ticks: {s.TickIndex} steps after {_frames - 1} physics frames, not one per frame"); - if (!_parityChecked && s.TickIndex == ParityTick) CheckParityAndRender(s); - if (_parityChecked && !_boxOffIssued && s.TickIndex == BoxOffTick) - { - Check(!s.Finished, $"the run was over before tick {BoxOffTick}; the box-off probe needs the will intact"); - _boxOffIssued = true; - _main.SwitchOff(); // the HUD button's handler - return; - } - if (_boxOffIssued) - { - Check(s.Finished && s.Result().Outcome == Outcome.BoxDisabled, $"box off did not end the run as BoxDisabled within one tick (finished {s.Finished})"); - Finish(); - return; - } - if (_frames > Watchdog) { Check(false, $"no result after {Watchdog} frames (tick {s.TickIndex})"); Finish(); } - } - - private void CheckParityAndRender(BodyPainBoxSession s) - { - _parityChecked = true; - var h = s.Hand; - Check(Bits(h.X) == Bits(_reference.X) && Bits(h.Y) == Bits(_reference.Y) && Bits(h.Z) == Bits(_reference.Z), - $"hand at tick {ParityTick} ({h.X}, {h.Y}, {h.Z}) differs from the headless run ({_reference.X}, {_reference.Y}, {_reference.Z})"); - - var view = s.View; - Check(_main.Bodies.NodeCount == view.Count && Count(_main.Bodies, n => n is MeshInstance3D) == view.Count, - $"{_main.Bodies.NodeCount} nodes for {view.Count} bodies"); + var view = Session.View; + Check(_main.Bodies.BodyCount == view.Count, $"{when}: {_main.Bodies.BodyCount} bodies drawn for {view.Count} lanes"); for (int i = 0; i < view.Count; i++) { - var node = _main.Bodies.NodeFor(view.StableId[i]); - if (node is null) { Check(false, $"no node for stable id {view.StableId[i]}"); continue; } + var id = view.StableId[i]; + if (_main.Bodies.PoseOf(id) is not { } pose) { Check(false, $"{when}: no body drawn for stable id {id}"); continue; } var want = new Vector3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]); - Check(node.Transform.Origin == want, $"body {view.StableId[i]} at {node.Transform.Origin}, lanes say {want}"); + Check(pose.Origin == want, $"{when}: body {id} at {pose.Origin}, lanes say {want}"); var q = new Quaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i]); - Check(Math.Abs(node.Transform.Basis.GetRotationQuaternion().Dot(q)) > 0.99999, $"body {view.StableId[i]} is rotated differently from its lane"); - - float r = view.Size0[i], a = view.Size1[i], b = view.Size2[i]; - var size = (Box3DSoaKind)view.Kind[i] switch - { - Box3DSoaKind.Sphere => new Vector3(2 * r, 2 * r, 2 * r), - Box3DSoaKind.Capsule => new Vector3(2 * r, 2 * (a + r), 2 * r), - _ => new Vector3(2 * r, 2 * a, 2 * b), - }; - Check(node.Mesh.GetAabb().Size.IsEqualApprox(size), $"body {view.StableId[i]} mesh is {node.Mesh.GetAabb().Size}, the lanes say {size}"); + Check(Math.Abs(pose.Basis.GetRotationQuaternion().Dot(q)) > 0.99999, $"{when}: body {id} is rotated differently from its lane"); } } + private void CheckEvents(HeadlessRun reference, string what) + { + var got = _main.Events.Select(e => (e.Tick, e.Events)).ToList(); + var want = reference.Events.Select(e => (e.Tick, e.Events)).ToList(); + Check(want.Count > 0, $"{what}: the headless run reported no events"); + Check(got.SequenceEqual(want), $"{what}: events {Format(got)} differ from the headless run's {Format(want)}"); + } + + private void CheckHand(HandSample want, string when) + { + var h = Session.Hand; + Check(Bits(h.X) == Bits(want.X) && Bits(h.Y) == Bits(want.Y) && Bits(h.Z) == Bits(want.Z), + $"hand at {when} ({h.X}, {h.Y}, {h.Z}) differs from the headless run ({want.X}, {want.Y}, {want.Z})"); + } + + /// Presses the HUD's Reset with the seed typed in its seed box. + private void PressReset(ulong seed) + { + Hud.SeedBox.Value = seed; + Hud.ResetButton.EmitSignal(BaseButton.SignalName.Pressed); + Check(_main.Seed == seed, $"Reset started seed {_main.Seed}, not {seed}"); + _lastSession = null; + } + + /// Waits one physics frame, and checks the session took exactly one step in the frame before it. + private async Task Frame() + { + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + if (_main.Failure is { } failure) throw new InvalidOperationException(failure); + var s = Session; + if (ReferenceEquals(s, _lastSession) && !s.Finished) Check(s.TickIndex == _lastTick + 1, $"{s.TickIndex - _lastTick} steps in one physics frame"); + _lastSession = s; + _lastTick = s.TickIndex; + } + + private async Task Frames(int n) + { + for (int i = 0; i < n; i++) await Frame(); + } + + private async Task UntilTick(long tick) + { + while (Session.TickIndex < tick && !Session.Finished) await Frame(); + } + + /// Session steps per real second over the next . + private async Task StepsPerSecond(ulong milliseconds) + { + ulong t0 = Time.GetTicksMsec(); + long tick0 = Session.TickIndex; + while (Time.GetTicksMsec() - t0 < milliseconds) await Frame(); + return (Session.TickIndex - tick0) * 1000.0 / (Time.GetTicksMsec() - t0); + } + + private readonly record struct HeadlessRun(List Events, List Hand, double Pain, double Strain); + + /// The same run without Godot: stepped until or the end, events drained as the client does. + private static HeadlessRun Run(double intensity, ulong seed, long ticks) + { + using var s = new BodyPainBoxSession(Main.ParametersFor(intensity), seed); + var events = new List(); + var hand = new List(); + var buffer = new BodyEvent[8]; + while (s.TickIndex < ticks && !s.Finished) + { + s.Step(); + hand.Add(s.Hand); + int n; + while ((n = s.DrainEvents(buffer)) > 0) events.AddRange(buffer.Take(n)); + } + return new HeadlessRun(events, hand, s.Pain, s.Strain); + } + private void Finish() { + if (_done) return; + _done = true; foreach (var f in _failures) GD.PrintErr("SMOKE FAIL: " + f); GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})"); GetTree().Quit(_failures.Count == 0 ? 0 : 1); @@ -113,6 +256,9 @@ public partial class Smoke : Node if (!ok) _failures.Add(failure); } + private static string Format(List<(long Tick, Lodur.TickEvents Events)> events) => + string.Join(",", events.Select(e => $"{e.Tick}:{e.Events}")); + private static uint Bits(float f) => BitConverter.SingleToUInt32Bits(f); private static int Count(Node root, Func match)