diff --git a/Eu07.BlackBox.Views/BlackBoxStrings.cs b/Eu07.BlackBox.Views/BlackBoxStrings.cs index a2a46b1..87ad6e1 100644 --- a/Eu07.BlackBox.Views/BlackBoxStrings.cs +++ b/Eu07.BlackBox.Views/BlackBoxStrings.cs @@ -30,7 +30,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.", ["Follow"] = "Follow the train", ["Fit"] = "Whole map", - ["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.", + ["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.", ["Unreadable"] = "Can't read {0}: {1}", ["Reading"] = "Reading {0}…", ["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}", @@ -190,6 +190,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged", ["EventTimetable"] = "Timetable {0}, {1}", ["CabSpeed"] = "Speed", + ["CabWheels"] = "wheels {0:0}", ["CabAiTarget"] = "AI {0:0} km/h", ["CabAcceleration"] = "Along", ["CabLateral"] = "Lateral", @@ -308,7 +309,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.", ["Follow"] = "Śledź pociąg", ["Fit"] = "Cała mapa", - ["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.", + ["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.", ["Unreadable"] = "Nie można odczytać {0}: {1}", ["Reading"] = "Czytanie {0}…", ["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}", @@ -468,6 +469,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia", ["EventTimetable"] = "Rozkład {0}, {1}", ["CabSpeed"] = "Prędkość", + ["CabWheels"] = "koła {0:0}", ["CabAiTarget"] = "AI {0:0} km/h", ["CabAcceleration"] = "Wzdłużne", ["CabLateral"] = "Boczne", diff --git a/Eu07.BlackBox.Views/CabPanel.cs b/Eu07.BlackBox.Views/CabPanel.cs index ed2aafd..79706ca 100644 --- a/Eu07.BlackBox.Views/CabPanel.cs +++ b/Eu07.BlackBox.Views/CabPanel.cs @@ -24,6 +24,7 @@ public sealed class CabPanel : Control private const double LampRow = 14; private const int DoorColumns = 2; private const double DriveRow = 34; + private const double WheelsApartKmh = 1.0; // the wheels shown when they turn this much faster or slower private Recording? _recording; private double _time; @@ -174,8 +175,19 @@ public sealed class CabPanel : Control var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold); context.DrawText(speed, new Point(Pad, 24)); Say($"{kmh} km/h"); - context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21)); + var unit = MapView.Text("km/h", Palette.DimText, 12); + context.DrawText(unit, new Point(Pad + speed.Width + 4, 24 + speed.Height - 21)); double gaugeX = Pad + Math.Max(150, width * 0.42); + // the wheels, when they turn otherwise: slipping, or locked in a skid. Signed both, so wheels slipping ahead + // of a train rolling back show too. Kept off the gauges at the right, as the AI's line is. + if (s.WheelSpeedKmh is { } wheels && Math.Abs(wheels - s.SpeedKmh) >= WheelsApartKmh) + { + double wheelsX = Pad + speed.Width + 4 + unit.Width + 8; + string wheelsText = string.Format(culture, Strings["CabWheels"], Math.Abs(wheels)); + using (context.PushClip(new Rect(wheelsX, 24, Math.Max(0, gaugeX - 8 - wheelsX), 40))) + context.DrawText(MapView.Text(wheelsText, Palette.Warn, 12), new Point(wheelsX, 24 + speed.Height - 21)); + Say(wheelsText); + } if (s.AiValid) { using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40))) @@ -337,7 +349,7 @@ public sealed class CabPanel : Control { context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top)); Say(Strings["CabGroupDoors"]); - var doors = Doors(s); + var doors = Doors(s.AsTheCabSees); double doorColumn = width / DoorColumns; for (int i = 0; i < doors.Length; i++) { diff --git a/Eu07.BlackBox.Views/EventList.cs b/Eu07.BlackBox.Views/EventList.cs index c4be54c..a3786bd 100644 --- a/Eu07.BlackBox.Views/EventList.cs +++ b/Eu07.BlackBox.Views/EventList.cs @@ -316,6 +316,8 @@ public sealed class EventList : ListBox (CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl") ]; + private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight; + /// /// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the /// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the @@ -325,7 +327,8 @@ public sealed class EventList : ListBox { CabSample? last = null; bool movingOpen = false; - foreach (var s in recording.Cab) + // the doors' sides as the driver has them, from the cab the driver is in (CabSample.AsTheCabSees) + foreach (var s in recording.Cab.Select(sample => sample.AsTheCabSees)) { if (last is not { } b || b.Vehicle != s.Vehicle) { @@ -333,8 +336,10 @@ public sealed class EventList : ListBox movingOpen = false; continue; } - bool Came(CabDevices device) => !b.Has(device) && s.Has(device); - bool Went(CabDevices device) => b.Has(device) && !s.Has(device); + // the other end swaps the sides, and tells nothing of the doors; no cab (0) sees them as the front one does + bool sameCab = (b.CabEnd < 0) == (s.CabEnd < 0); + bool Came(CabDevices device) => !b.Has(device) && s.Has(device) && (sameCab || (device & DoorSides) == 0); + bool Went(CabDevices device) => b.Has(device) && !s.Has(device) && (sameCab || (device & DoorSides) == 0); foreach (var (device, key) in Switched) { if (Came(device)) diff --git a/Eu07.BlackBox/BlackBoxReader.cs b/Eu07.BlackBox/BlackBoxReader.cs index 55b4da9..97a0e48 100644 --- a/Eu07.BlackBox/BlackBoxReader.cs +++ b/Eu07.BlackBox/BlackBoxReader.cs @@ -172,6 +172,9 @@ public sealed class BlackBoxReader Extra = new CabExtra((EngineKind)r.U8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.I8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32()) }; + // The speed of the wheels, later again. + if (sample.Extra is not null && r.Remaining >= 4) + sample = sample with { WheelSpeedKmh = r.F32() }; rec.AddCab(sample); break; } diff --git a/Eu07.BlackBox/Records.cs b/Eu07.BlackBox/Records.cs index c02db64..89e44a7 100644 --- a/Eu07.BlackBox/Records.cs +++ b/Eu07.BlackBox/Records.cs @@ -366,8 +366,12 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0, SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0, Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1, - Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null) + Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null, + float? WheelSpeedKmh = null) { + // WheelSpeedKmh: the speed of the wheels as they turn, which the speedometer shows, signed as SpeedKmh; apart + // from it while they slip, 0 while they are locked in a skid. None in a recording made before it. + public bool Has(CabDevices device) => (Devices & device) == device; public bool Has(SecurityFlags flag) => (Security & flag) == flag; @@ -386,6 +390,26 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit /// public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal)); + private const CabDevices LeftDoors = CabDevices.DoorsLeft | CabDevices.DoorPermitLeft; + private const CabDevices RightDoors = CabDevices.DoorsRight | CabDevices.DoorPermitRight; + + /// + /// The doors as the driver has them: the recording holds the left and right of the vehicle, and from its rear + /// cab the driver's left is the vehicle's right, as the simulator works the doors from it. Out of a cab, the + /// vehicle's. + /// + public CabSample AsTheCabSees => + CabEnd >= 0 + ? this + : this with + { + Devices = (Devices & ~(LeftDoors | RightDoors)) + | ((Devices & CabDevices.DoorsLeft) != 0 ? CabDevices.DoorsRight : 0) + | ((Devices & CabDevices.DoorsRight) != 0 ? CabDevices.DoorsLeft : 0) + | ((Devices & CabDevices.DoorPermitLeft) != 0 ? CabDevices.DoorPermitRight : 0) + | ((Devices & CabDevices.DoorPermitRight) != 0 ? CabDevices.DoorPermitLeft : 0) + }; + public bool AiValid => (Flags & CabFlags.AiValid) != 0; public bool InCab => (Flags & CabFlags.InCab) != 0; public float AbsSpeedKmh => Math.Abs(SpeedKmh); diff --git a/StarterNG.Tests/BlackBox/BlackBoxFile.cs b/StarterNG.Tests/BlackBox/BlackBoxFile.cs index b0a49e7..ac39b62 100644 --- a/StarterNG.Tests/BlackBox/BlackBoxFile.cs +++ b/StarterNG.Tests/BlackBox/BlackBoxFile.cs @@ -109,7 +109,7 @@ internal sealed class BlackBoxFile uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0, float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null, short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null, - byte? engine = null, float oilTemperature = 70) => + byte? engine = null, float oilTemperature = 70, float? wheelSpeed = null) => Record(0x20, w => { w.Write(time); @@ -181,6 +181,9 @@ internal sealed class BlackBoxFile w.Write(1.0f); // clutch w.Write(0.0f); // torque converter w.Write(2.5f); // the highest brake cylinder of the train + // the speed of the wheels: a recording made before it ends above + if (wheelSpeed is { } wheels) + w.Write(wheels); } } } diff --git a/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs b/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs index ceed107..cee8efd 100644 --- a/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs +++ b/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs @@ -60,13 +60,15 @@ public class BlackBoxListingTests public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time() { var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc); + // named in the local time they started at, whatever the zone the tests run in + string first = Box("td", early.AddHours(-1)), second = Box("td", early.AddMinutes(30)); var installation = new TestInstallation(new InMemoryFileSystem() .WithFile(Log("a.dat"), "t") - .WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b") - .WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b") + .WithFile(Log(first), "b") + .WithFile(Log(second), "b") .WrittenAt(Log("a.dat"), early) - .WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2)) - .WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1))); + .WrittenAt(Log(first), early.AddSeconds(2)) + .WrittenAt(Log(second), early.AddHours(1))); var sessions = installation.Tapes.Sessions(); @@ -74,12 +76,59 @@ public class BlackBoxListingTests Assert.All(sessions, session => Assert.Null(session.Launch)); // Newest first: the black box on its own, then the run with the tape. Assert.Empty(sessions[0].Tapes); - Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path); + Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path); Assert.Single(sessions[1].Tapes); - Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path); + Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path); Assert.Equal(early, sessions[1].StartedUtc); } + [Fact] + public void The_tape_of_a_vehicle_left_early_in_a_run_with_no_launch_goes_with_its_black_box() + { + // The black box writes the tapes as it goes: that of the vehicle the player left after ten minutes ends + // twenty minutes before the run, that of the next one with it. + var started = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc); + string box = Box("td", started); + var installation = new TestInstallation(new InMemoryFileSystem() + .WithFile(Log("first.dat"), "t") + .WithFile(Log("second.dat"), "t") + .WithFile(Log(box), "b") + .WrittenAt(Log("first.dat"), started.AddMinutes(10)) + .WrittenAt(Log(box), started.AddMinutes(30)) + .WrittenAt(Log("second.dat"), started.AddMinutes(30).AddSeconds(1))); + + var session = Assert.Single(installation.Tapes.Sessions()); + + Assert.Null(session.Launch); + Assert.Equal(new[] { "first", "second" }, session.Tapes.Select(tape => tape.Vehicle).Order()); + Assert.EndsWith(box, Assert.Single(session.BlackBoxes).Path); + } + + [Fact] + public void A_black_box_downloaded_later_takes_in_no_tapes_of_the_runs_after_it() + { + // Shared and downloaded two weeks later, so last written then; a run of its own with no launch noted since. + var shared = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc); + var later = shared.AddDays(7); + string old = Box("td", shared), own = Box("td", later); + var installation = new TestInstallation(new InMemoryFileSystem() + .WithFile(Log(old), "b").WrittenAt(Log(old), shared.AddDays(14)) + .WithFile(Log(own), "b").WrittenAt(Log(own), later.AddMinutes(30)) + .WithFile(Log("ra.dat"), "t").WrittenAt(Log("ra.dat"), later.AddMinutes(30).AddSeconds(1)) + .WithFile(Log("left.dat"), "t").WrittenAt(Log("left.dat"), later.AddMinutes(10))); + + var recordings = StarterNG.Application.HaslerTapes.Recordings(new[] + { + new StarterNG.Application.BlackBoxRecording(Log(old), shared.AddDays(14), 1), + new StarterNG.Application.BlackBoxRecording(Log(own), later.AddMinutes(30), 1), + }); + Assert.EndsWith(own, StarterNG.Application.HaslerTapes.RecordingAt(later.AddMinutes(10), recordings)!.Path); + + var mine = Assert.Single(installation.Tapes.Sessions(), session => session.Tapes.Count > 0); + Assert.Equal(new[] { "left", "ra" }, mine.Tapes.Select(tape => tape.Vehicle).Order()); + Assert.EndsWith(own, Assert.Single(mine.BlackBoxes).Path); + } + [Fact] public void The_black_box_of_a_running_session_is_listed_while_it_is_written() { diff --git a/StarterNG.Tests/BlackBox/BlackBoxSignalsTests.cs b/StarterNG.Tests/BlackBox/BlackBoxSignalsTests.cs index be035bc..9991b6f 100644 --- a/StarterNG.Tests/BlackBox/BlackBoxSignalsTests.cs +++ b/StarterNG.Tests/BlackBox/BlackBoxSignalsTests.cs @@ -125,6 +125,20 @@ public class HeadCodeTests Assert.Null(cab[1].Extra); } + [Fact] + public void The_speed_of_the_wheels_is_read_when_written() + { + var f = new BlackBoxFile().Info(); + // the wheels slipping at 40 km/h + f.Cab(0, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1, wheelSpeed: 55.5f); + f.Cab(0.5, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1); + var cab = BlackBoxReader.Read(f.End(1).Stream()).Cab; + Assert.Equal(55.5f, cab[0].WheelSpeedKmh); + Assert.Equal(40f, cab[0].SpeedKmh); + // an older sample has none + Assert.Null(cab[1].WheelSpeedKmh); + } + [Fact] public void A_vehicle_with_no_lamps_is_not_judged() { diff --git a/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs b/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs index 6102433..09659a1 100644 --- a/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs +++ b/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs @@ -222,6 +222,34 @@ public class BlackBoxViewsTests Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText()); } + [Fact] + public void Wheels_turning_apart_from_the_train_are_said_beside_its_speed() + { + var f = new BlackBoxFile().Info() + .Vehicle(Head, "EU07-005", "ROJ1") + .User(0, Head, true, 1); + // slipping for the first ten seconds, then the wheels as fast as the train, give or take the rounding + for (double t = 0; t <= 20; t += 0.5) + f.Cab(t, Head, 1150 + t * 10, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1, + wheelSpeed: t < 10 ? 55.4f : 40.3f); + var cab = new CabPanel + { + Recording = BlackBoxReader.Read(f.End(20).Stream()), + Strings = new DefaultBlackBoxStrings("en"), + Time = 5 + }; + Controls.Lay(cab, 600, 900); + + Controls.Draw(cab); + Assert.Contains("40 km/h", cab.Said); + Assert.Contains("wheels 55", cab.Said); + + cab.Time = 15; + Controls.Draw(cab); + Assert.Contains("40 km/h", cab.Said); + Assert.DoesNotContain("wheels", cab.Said); + } + [Fact] public void The_cab_stopped_under_the_brakes_and_out_of_the_recording() { diff --git a/StarterNG.Tests/BlackBox/CabDoorsTests.cs b/StarterNG.Tests/BlackBox/CabDoorsTests.cs new file mode 100644 index 0000000..d801d0c --- /dev/null +++ b/StarterNG.Tests/BlackBox/CabDoorsTests.cs @@ -0,0 +1,49 @@ +using Eu07.BlackBox; +using Eu07.BlackBox.Views; + +namespace StarterNG.Tests.BlackBox; + +// The events are coloured with the views' brushes. +[Collection(AvaloniaControls.Name)] +public class CabDoorsTests +{ + private static CabSample Sample(sbyte cab, CabDevices devices) => + default(CabSample) with { CabEnd = cab, Devices = devices | CabDevices.Radio }; + + [Fact] + public void From_the_rear_cab_the_vehicles_right_doors_are_the_drivers_left() + { + var seen = Sample(-1, CabDevices.DoorsRight | CabDevices.DoorPermitRight).AsTheCabSees; + + Assert.True(seen.Has(CabDevices.DoorsLeft)); + Assert.True(seen.Has(CabDevices.DoorPermitLeft)); + Assert.False(seen.Has(CabDevices.DoorsRight)); + Assert.False(seen.Has(CabDevices.DoorPermitRight)); + Assert.True(seen.Has(CabDevices.Radio)); + } + + [Theory] + [InlineData(1)] + [InlineData(0)] + public void From_the_front_cab_or_out_of_one_the_sides_are_the_vehicles(sbyte cab) + { + var sample = Sample(cab, CabDevices.DoorsLeft | CabDevices.DoorPermitRight); + + Assert.Equal(sample, sample.AsTheCabSees); + } + + [Fact] + public void Going_to_the_other_cab_tells_nothing_of_the_doors_and_still_tells_the_switches() + { + var f = new BlackBoxFile().Info().Vehicle(1, "EN57-1001").User(0, 1, true); + // the left doors permitted from the front cab; in the rear one the permit is still on, and the radio turned off + f.Cab(0, 1, 1000, 0, cabEnd: 1, devices: 0x0007 | (uint)(CabDevices.DoorPermitLeft | CabDevices.Radio)); + f.Cab(1, 1, 1000, 0, cabEnd: -1, devices: 0x0007 | (uint)CabDevices.DoorPermitLeft); + + var events = EventList.Collect(BlackBoxReader.Read(f.End(1).Stream()), new DefaultBlackBoxStrings("en")) + .Select(e => e.Text).ToList(); + + Assert.Contains("Radio: off", events); + Assert.DoesNotContain(events, e => e.Contains("doors permitted")); + } +} diff --git a/StarterNG.Tests/ColumnLineTests.cs b/StarterNG.Tests/ColumnLineTests.cs new file mode 100644 index 0000000..d501ad4 --- /dev/null +++ b/StarterNG.Tests/ColumnLineTests.cs @@ -0,0 +1,55 @@ +using Avalonia; +using StarterNG.Views.Tapes; + +namespace StarterNG.Tests; + +/// The line of a tape, drawn a column of pixels at a time and broken off at a gap. +public class ColumnLineTests +{ + private readonly List _drawn = []; + + private ColumnLine Line() => + new(p => _drawn.Add($"begin {p.X} {p.Y}"), p => _drawn.Add($"line {p.X} {p.Y}"), () => _drawn.Add("end")); + + [Fact] + public void A_column_is_entered_where_it_started_and_left_where_it_ended_through_its_lowest_and_highest() + { + var line = Line(); + + // Falling within the column: from its first through its highest and its lowest to its last. + foreach (double v in new[] { 3.0, 1.0, 4.0, 2.0 }) + line.Add(5, v); + // Rising: through its lowest first. + foreach (double v in new[] { 2.0, 4.0, 1.0, 3.0 }) + line.Add(6, v); + line.Break(); + + Assert.Equal(["begin 5 3", "line 5 4", "line 5 1", "line 5 2", + "line 6 2", "line 6 1", "line 6 4", "line 6 3", "end"], _drawn); + } + + [Fact] + public void A_break_ends_the_figure_and_the_next_point_begins_another() + { + var line = Line(); + + line.Add(0, 10); + line.Break(); + line.Add(9, 20); + line.Break(); + + Assert.Equal(["begin 0 10", "line 0 10", "line 0 10", "line 0 10", "end", + "begin 9 20", "line 9 20", "line 9 20", "line 9 20", "end"], _drawn); + } + + [Fact] + public void A_break_with_nothing_drawn_ends_nothing() + { + var line = Line(); + + line.Break(); + line.Break(); + + Assert.Empty(_drawn); + } +} diff --git a/StarterNG.Tests/ConsistOrientationTests.cs b/StarterNG.Tests/ConsistOrientationTests.cs index 558cd37..505d41a 100644 --- a/StarterNG.Tests/ConsistOrientationTests.cs +++ b/StarterNG.Tests/ConsistOrientationTests.cs @@ -6,6 +6,8 @@ using StarterNG.Tests.Fakes; namespace StarterNG.Tests; +// Puts in services of its own: not while the controls read theirs. +[Collection(AvaloniaControls.Name)] public class ConsistOrientationTests { private readonly VehicleCatalog _catalog; diff --git a/StarterNG.Tests/Fakes/ForwardOnlyStream.cs b/StarterNG.Tests/Fakes/ForwardOnlyStream.cs new file mode 100644 index 0000000..509afa6 --- /dev/null +++ b/StarterNG.Tests/Fakes/ForwardOnlyStream.cs @@ -0,0 +1,29 @@ +namespace StarterNG.Tests.Fakes; + +/// A stream read from its start to its end and no other way: no length, no seeking. +internal sealed class ForwardOnlyStream(Stream inner) : Stream +{ + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + + protected override void Dispose(bool disposing) + { + if (disposing) + inner.Dispose(); + base.Dispose(disposing); + } +} diff --git a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs index 22c2868..a6fbba9 100644 --- a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs +++ b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs @@ -20,6 +20,7 @@ public sealed class InMemoryFileSystem : IFileSystem private readonly HashSet _executable; private readonly Dictionary _links; private readonly HashSet _unreadable; + private readonly HashSet _unseekable; private readonly HashSet _unlistable; private readonly Dictionary _written; @@ -32,6 +33,7 @@ public sealed class InMemoryFileSystem : IFileSystem _executable = new HashSet(comparer); _links = new Dictionary(comparer); _unreadable = new HashSet(comparer); + _unseekable = new HashSet(comparer); _unlistable = new HashSet(comparer); _written = new Dictionary(comparer); } @@ -51,6 +53,13 @@ public sealed class InMemoryFileSystem : IFileSystem return this; } + /// The file opens as a stream read only forward, as a pipe or some network shares give it. + public InMemoryFileSystem OpenedForwardOnly(string path) + { + _unseekable.Add(Normalize(path)); + return this; + } + public InMemoryFileSystem AllowReading(string path) { _unreadable.Remove(Normalize(path)); @@ -115,7 +124,11 @@ public sealed class InMemoryFileSystem : IFileSystem public byte[] ReadAllBytes(string path) => Bytes(path); - public Stream OpenRead(string path) => new MemoryStream(Bytes(path), writable: false); + public Stream OpenRead(string path) + { + var stream = new MemoryStream(Bytes(path), writable: false); + return _unseekable.Contains(Normalize(path)) ? new ForwardOnlyStream(stream) : stream; + } public void WriteAllText(string path, string contents) => WithFile(path, contents); diff --git a/StarterNG.Tests/HaslerTapeTests.cs b/StarterNG.Tests/HaslerTapeTests.cs index 6b752b9..18108eb 100644 --- a/StarterNG.Tests/HaslerTapeTests.cs +++ b/StarterNG.Tests/HaslerTapeTests.cs @@ -6,12 +6,12 @@ namespace StarterNG.Tests; public class HaslerTapeTests { - private const string Header = + internal const string Header = "Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " + "BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n"; - private static string Line(double t, double v, double brake, double current, string command = "none", + internal static string Line(double t, double v, double brake, double current, string command = "none", int security = 0) => string.Create(CultureInfo.InvariantCulture, $"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") + @@ -68,6 +68,197 @@ public class HaslerTapeTests Assert.Equal(5, tape.DistanceM, 6); } + [Fact] + public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end() + { + // the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures + string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n"); + static string WithSpeed(string line, double kmh) => + line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n")); + // the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter + string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n", + " 0 1 0.0000 0.0000 0.0000 0.0000\r\n"); + + var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36)); + + Assert.Equal(2, tape.Samples.Count); + Assert.False(tape.Samples[0].SecurityAlarm); + Assert.True(tape.Samples[1].SecurityAlarm); + } + + [Fact] + public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header() + { + var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1)); + + Assert.Equal(2, tape.Samples.Count); + Assert.False(tape.Samples[0].SecurityAlarm); + Assert.True(tape.Samples[1].SecurityAlarm); + } + + [Fact] + public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance() + { + // the player in another vehicle for ten minutes, then back in this one + var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0) + + Line(602, 36, 0, 0) + Line(603, 0, 0, 0)); + + Assert.Equal(603, tape.Duration, 6); + Assert.Equal(600, tape.GapTime, 6); + Assert.Equal(2, tape.RunningTime, 6); + Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping + Assert.Equal(10 + 10 + 5, tape.DistanceM, 6); + Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6); + } + + [Fact] + public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap() + { + // a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after + var text = new System.Text.StringBuilder(Header); + double t = 0; + for (int i = 0; i < 40; i++, t += 0.05) + text.Append(Line(t, 100, 0, 0)); + t += 1.017 - 0.05; + for (int i = 0; i < 40; i++, t += 0.05) + text.Append(Line(t, 100, 0, 0)); + + var tape = HaslerTape.Parse(text.ToString()); + + Assert.Equal(0, tape.GapTime, 6); + Assert.Equal(tape.Duration, tape.RunningTime, 6); + Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6); + } + + [Fact] + public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole() + { + string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400) + + Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0); + var whole = HaslerTape.Parse(text); + + for (int cut = 1; cut < text.Length; cut += 7) + { + var reader = new HaslerTape.Reader(); + reader.Feed(text[..cut]); + reader.Feed(text[cut..]); + Assert.Equal(whole.Samples, reader.Tape(final: true).Samples); + } + } + + [Fact] + public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed() + { + var reader = new HaslerTape.Reader(); + string line = Line(1, 36, 0, 0); + reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]); + + Assert.Single(reader.Tape(final: false).Samples); + Assert.Single(reader.Tape(final: false).Samples); + reader.Feed(line[20..]); + Assert.Equal(2, reader.Tape(final: false).Samples.Count); + } + + [Fact] + public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole() + { + string path = TestInstallation.At("physicslog", "EU07-424.dat"); + var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)); + var tapes = new TestInstallation(files).Tapes; + var file = Assert.Single(tapes.List()); + + Assert.Single(tapes.Load(file, follow: false)!.Samples); + files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0)); + Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count); + + // begun anew, and already longer than was read: its time goes back + files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0)); + var tape = tapes.Load(file, follow: true)!; + Assert.Equal(4, tape.Samples.Count); + Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6)); + + // begun anew, and shorter + files.WithFile(path, Header + Line(0, 18, 0, 0)); + Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6); + } + + [Fact] + public void A_log_begun_anew_over_the_end_that_was_read_is_read_whole_once_its_time_goes_back() + { + // the command is free text, here long enough that the end kept of the read part holds no time + string command = new('x', 400); + string path = TestInstallation.At("physicslog", "EU07-424.dat"); + var files = new InMemoryFileSystem().WithFile(path, Header + Line(3, 36, 0, 0, command)); + var tapes = new TestInstallation(files).Tapes; + var file = Assert.Single(tapes.List()); + Assert.Equal(3, Assert.Single(tapes.Load(file, follow: false)!.Samples).Time, 6); + + // begun anew: where the read part ended it reads as it did, but the lines added go back to the start + files.WithFile(path, Header + Line(0, 36, 0, 0, command) + Line(1, 36, 0, 0, command) + Line(2, 36, 0, 0, command)); + var tape = tapes.Load(file, follow: true)!; + + Assert.Equal([0.0, 1.0, 2.0], tape.Samples.Select(s => s.Time)); + } + + [Fact] + public void A_tape_that_cannot_be_read_is_none_and_told_and_is_read_whole_once_it_can() + { + string path = TestInstallation.At("physicslog", "EU07-424.dat"); + var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)); + var installation = new TestInstallation(files); + var tapes = installation.Tapes; + var file = Assert.Single(tapes.List()); + tapes.Load(file, follow: false); + + files.FailReading(path); + Assert.Null(tapes.Load(file, follow: true)); + Assert.Contains("EU07-424.dat", installation.Log.Text); + + files.AllowReading(path).WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0)); + Assert.All(tapes.Load(file, follow: true)!.Samples, s => Assert.Equal(72, s.SpeedKmh, 6)); + } + + [Fact] + public void A_file_read_only_forward_is_read_whole_each_time() + { + string path = TestInstallation.At("physicslog", "EU07-424.dat"); + var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)).OpenedForwardOnly(path); + var tapes = new TestInstallation(files).Tapes; + var file = Assert.Single(tapes.List()); + + Assert.Single(tapes.Load(file, follow: true)!.Samples); + files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0)); + Assert.Equal(2, tapes.Load(file, follow: true)!.Samples.Count); + } + + [Fact] + public void Empty_lines_in_a_log_are_passed_over() + { + var tape = HaslerTape.Parse(Header + "\r\n" + Line(0, 36, 0, 0) + " \r\n" + Line(1, 36, 0, 0)); + + Assert.Equal(2, tape.Samples.Count); + } + + [Fact] + public void Forgetting_another_file_keeps_the_followed_tape_and_its_own_lets_it_go() + { + string Lines(int firstSpeed, int count) => + Header + Line(0, firstSpeed, 0, 0) + string.Concat(Enumerable.Range(1, count).Select(t => Line(t, 36, 0, 0))); + string path = TestInstallation.At("physicslog", "EU07-424.dat"); + var files = new InMemoryFileSystem().WithFile(path, Lines(36, 20)); + var tapes = new TestInstallation(files).Tapes; + var file = Assert.Single(tapes.List()); + tapes.Load(file, follow: false); + + // the first line changed, as long as it was and far from the end: a tape still followed doesn't read it again + files.WithFile(path, Lines(72, 21)); + tapes.Forget(TestInstallation.At("physicslog", "EU07-111.dat")); + Assert.Equal(36, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6); + + tapes.Forget(file.Path); + Assert.Equal(72, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6); + } + [Fact] public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance() { diff --git a/StarterNG.Tests/HaslerTapeWindowTests.cs b/StarterNG.Tests/HaslerTapeWindowTests.cs new file mode 100644 index 0000000..ac93640 --- /dev/null +++ b/StarterNG.Tests/HaslerTapeWindowTests.cs @@ -0,0 +1,96 @@ +using Avalonia.Controls; +using Avalonia.LogicalTree; +using StarterNG.Application; +using StarterNG.Domain.Tapes; +using StarterNG.Tests.Fakes; +using StarterNG.Views.Tapes; + +namespace StarterNG.Tests; + +/// The tapes' window over the tapes of an installation of its own, read as it is opened. +[Collection(AvaloniaControls.Name)] +public class HaslerTapeWindowTests +{ + private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc); + + static HaslerTapeWindowTests() => HeadlessDrawing.Ensure(); + + private static AppServices Services(InMemoryFileSystem files) + { + var installation = new TestInstallation(files); + installation.Clock.Now = Launched; + return AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment); + } + + // The window reads the tapes off the UI thread and shows them on it: what it shows is waited for. + private static void Until(Func shown) => + Assert.True(SpinWait.SpinUntil(() => + { + Controls.Settle(); + return shown(); + }, TimeSpan.FromSeconds(5))); + + private static Button Button(Window window, string key) => + window.GetLogicalDescendants().OfType