From 1ef630b1b691cf9a4c7395ba41eadac34ad9b641 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:05:05 +0100 Subject: [PATCH 01/20] fix(tapes): the alerter of a physics log is read where its header puts it The simulator's log has had a column of the vehicle's speed at its end since 2026-11 (master), and the alerter, counted six columns from the end past the free-text command, was read from the wheel slip instead. Its place from the end is taken from the "Security" heading of the file's header, and only a log with no header falls back to the old 25 columns. --- StarterNG.Tests/HaslerTapeTests.cs | 18 ++++++++++++++++++ StarterNG/Domain/Tapes/HaslerTape.cs | 16 +++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/StarterNG.Tests/HaslerTapeTests.cs b/StarterNG.Tests/HaslerTapeTests.cs index 6b752b9..582fbaa 100644 --- a/StarterNG.Tests/HaslerTapeTests.cs +++ b/StarterNG.Tests/HaslerTapeTests.cs @@ -68,6 +68,24 @@ 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 The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance() { diff --git a/StarterNG/Domain/Tapes/HaslerTape.cs b/StarterNG/Domain/Tapes/HaslerTape.cs index ec11775..ffaf607 100644 --- a/StarterNG/Domain/Tapes/HaslerTape.cs +++ b/StarterNG/Domain/Tapes/HaslerTape.cs @@ -29,13 +29,16 @@ public readonly record struct TapeSample( public sealed class HaslerTape { // Columns counted from the start; the security flag is counted from the end, past - // the command, which is free text. The header says m/s and MPa, the values are km/h and bar. + // the command, which is free text, as far from the end as the header has it: the + // simulator adds a new column at the end (the vehicle's speed, 2026-10). The header + // says m/s and MPa, the values are km/h and bar. private const int TimeColumn = 0; private const int VelocityColumn = 1; private const int BrakePressColumn = 8; private const int PipePressColumn = 9; private const int MotorCurrentColumn = 10; - private const int SecurityFromEnd = 6; + private const string SecurityHeading = "Security"; + private const int SecurityFromEndOf25 = 6; // a log with no header to tell: the columns up to the water's temperature private const int MinimumColumns = 17; public HaslerTape(IReadOnlyList samples) @@ -77,9 +80,16 @@ public sealed class HaslerTape double distance = 0; TapeSample? previous = null; + int securityFromEnd = SecurityFromEndOf25; foreach (var raw in text.Split('\n')) { var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + int heading = Array.IndexOf(columns, SecurityHeading); + if (heading >= 0) + { + securityFromEnd = columns.Length - heading; + continue; + } if (columns.Length < MinimumColumns || !Number(columns[TimeColumn], out double time) || !Number(columns[VelocityColumn], out double velocity)) @@ -88,7 +98,7 @@ public sealed class HaslerTape Number(columns[BrakePressColumn], out double brake); Number(columns[PipePressColumn], out double pipe); Number(columns[MotorCurrentColumn], out double current); - bool security = columns[^SecurityFromEnd] == "1"; + bool security = securityFromEnd <= columns.Length && columns[^securityFromEnd] == "1"; double speed = Math.Abs(velocity); if (previous is { } p) From 4429eff4efe208df88d491a448c1a0d09ea831d6 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:05:06 +0100 Subject: [PATCH 02/20] feat(tapes): tape recording turns the black box on, not the physics log of every vehicle The simulator now records the black box on its own ("blackbox yes") and writes the .dat tapes of the vehicles the player was in when it closes, so the tapes no longer need "physicslog yes", which keeps a log of every vehicle of the scenery open and written twenty times a second (some 500 files on Tomaszewo, past what the runtime allowed). - The settings have a box of their own for the black box and its tapes, next to the physics log of every vehicle, which stays for diagnostics. - "Turn on recording" of the tapes' window turns the black box on. - The key is read as the simulator reads it: with no line of its own it goes with the physics log. It is written where it says more than the physics log or where the file has it already, so an ini without it stays so. - A launch is noted for the tapes with either one on; "live" follows a tape only with the physics log, as the black box writes its tapes at the end, and its tip says so. --- Eu07.BlackBox.Views/BlackBoxStrings.cs | 4 +- StarterNG.Tests/SettingsStoreTests.cs | 82 +++++++++++++++++++ StarterNG.Tests/StartSimulationTests.cs | 12 +++ StarterNG/Application/StartSimulation.cs | 2 +- .../Domain/Settings/SimulatorSettings.cs | 7 ++ .../Settings/SettingsSerializer.cs | 7 ++ StarterNG/MainWindow.axaml.cs | 2 +- StarterNG/Views/Settings.axaml | 3 + StarterNG/Views/Settings.axaml.cs | 3 + StarterNG/Views/Tapes/HaslerTapeWindow.cs | 14 ++-- StarterNG/startercfg/lang/cz.xml | 5 +- StarterNG/startercfg/lang/en.xml | 7 +- StarterNG/startercfg/lang/hu.xml | 5 +- StarterNG/startercfg/lang/pl.xml | 7 +- StarterNG/startercfg/lang/ru.xml | 5 +- 15 files changed, 149 insertions(+), 16 deletions(-) diff --git a/Eu07.BlackBox.Views/BlackBoxStrings.cs b/Eu07.BlackBox.Views/BlackBoxStrings.cs index 645599d..dd94933 100644 --- a/Eu07.BlackBox.Views/BlackBoxStrings.cs +++ b/Eu07.BlackBox.Views/BlackBoxStrings.cs @@ -26,7 +26,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["Pause"] = "Pause", ["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}", @@ -297,7 +297,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["Pause"] = "Pauza", ["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}", diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 66ce35c..1abd865 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1302,4 +1302,86 @@ public class SettingsStoreTests Assert.False(store.LoadFailed); Assert.Equal(60, store.Settings.FieldOfView); } + + [Theory] + [InlineData("physicslog yes\n", true)] + [InlineData("physicslog no\n", false)] + [InlineData("physicslog yes\nblackbox no\n", false)] + [InlineData("physicslog no\nblackbox yes\n", true)] + public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); + + installation.SettingsStore.Load(); + + Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox); + } + + [Fact] + public void Tapes_turned_on_write_the_black_box_and_leave_the_physics_log_off() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.BlackBox = true; + + installation.SettingsStore.Save(); + + Assert.Equal("blackbox yes", LineFor(installation, "blackbox")); + Assert.Equal("physicslog no", LineFor(installation, "physicslog")); + } + + [Fact] + public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.Width = 1600; + + installation.SettingsStore.Save(); + + Assert.Null(LineFor(installation, "blackbox")); + } + + [Theory] + [InlineData("physicslog yes\nblackbox yes\n")] + [InlineData("physicslog no\nblackbox yes\n")] + public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.BlackBox = false; + installation.SettingsStore.Settings.PhysicsLog = false; + + installation.SettingsStore.Save(); + + Assert.Equal("blackbox no", LineFor(installation, "blackbox")); + Assert.Equal("physicslog no", LineFor(installation, "physicslog")); + } + + [Fact] + public void The_physics_log_turned_off_keeps_the_tapes_it_brought() + { + // an ini of before the black box had a key: the tapes came with the physics log + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.PhysicsLog = false; + + installation.SettingsStore.Save(); + + Assert.Equal("blackbox yes", LineFor(installation, "blackbox")); + } + + [Fact] + public void A_black_box_line_written_once_goes_away_when_it_says_no_more() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.BlackBox = true; + installation.SettingsStore.Save(); + + installation.SettingsStore.Settings.BlackBox = false; + installation.SettingsStore.Save(); + + Assert.Null(LineFor(installation, "blackbox")); + } } diff --git a/StarterNG.Tests/StartSimulationTests.cs b/StarterNG.Tests/StartSimulationTests.cs index 359c73c..973683b 100644 --- a/StarterNG.Tests/StartSimulationTests.cs +++ b/StarterNG.Tests/StartSimulationTests.cs @@ -40,6 +40,18 @@ public class StartSimulationTests Assert.Contains($"vehicle\t{driven}\tPKP/EP07\tep07.mmd", noted); } + [Fact] + public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes_at_the_end() + { + var (start, _, installation) = Rig(files => files.WithExecutable(Build), sceneryClock: "07:52"); + installation.SettingsStore.Settings.BlackBox = true; + + start.Execute(freeFly: false, saveSettings: false); + + string noted = installation.Files.ReadAllText(TestInstallation.At("physicslog", "starter-launch.txt")); + Assert.Contains("clock\t07:52", noted); + } + [Fact] public void Without_the_physics_log_nothing_is_noted() { diff --git a/StarterNG/Application/StartSimulation.cs b/StarterNG/Application/StartSimulation.cs index 6cacc79..cd310e1 100644 --- a/StarterNG/Application/StartSimulation.cs +++ b/StarterNG/Application/StartSimulation.cs @@ -144,7 +144,7 @@ public sealed class StartSimulation if (saveSettings) _settings.CaptureAndSave(); - if (_settings.Settings.PhysicsLog) + if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox) _tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle); string[] arguments = freeFly || string.IsNullOrEmpty(vehicle) diff --git a/StarterNG/Domain/Settings/SimulatorSettings.cs b/StarterNG/Domain/Settings/SimulatorSettings.cs index d600399..8e34200 100644 --- a/StarterNG/Domain/Settings/SimulatorSettings.cs +++ b/StarterNG/Domain/Settings/SimulatorSettings.cs @@ -133,6 +133,13 @@ public sealed class SimulatorSettings public bool EnableTraction = true; public bool LiveTraction = true; public bool PhysicsLog; + /// + /// The black box of the session, and with it the tapes (.dat) of the vehicles the player was in, written when the + /// simulator closes: the tapes without the log of every vehicle. With no entry of its own it goes with the physics log. + /// + public bool BlackBox; + /// Whether eu07.ini had a line of its own for the black box when read: it is kept saying what is wanted. + public bool BlackBoxInIni; public bool DebugLog = true; public bool MultipleLogs; public bool DisplaySimulation = true; diff --git a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs index ab66b2f..0d7227b 100644 --- a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs +++ b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs @@ -157,6 +157,9 @@ public sealed class SettingsSerializer s.EnableTraction = c.GetBool("enabletraction", true); s.LiveTraction = c.GetBool("livetraction", true); s.PhysicsLog = c.GetBool("physicslog", false); + // the simulator records the black box along with the physics log when the ini says nothing of it + s.BlackBoxInIni = c.Has("blackbox"); + s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog; int debugLog = c.GetInt("debuglog", 3); s.DebugLog = (debugLog & 1) != 0; s.DebugLogVisible = (debugLog & 2) != 0; @@ -370,6 +373,10 @@ public sealed class SettingsSerializer c.SetBool("enabletraction", s.EnableTraction); c.SetBool("livetraction", s.LiveTraction); c.SetBool("physicslog", s.PhysicsLog); + // written where it says more than the physics log, or where the file has it already: an ini without it + // stays so, and a line written once and no longer saying more goes away on the next save + if (s.BlackBoxInIni || s.BlackBox != s.PhysicsLog) + c.SetBool("blackbox", s.BlackBox); c.SetInt("debuglog", (s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits); c.SetBool("multiplelogs", s.MultipleLogs); diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 2a203ad..4388013 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -709,7 +709,7 @@ public partial class MainWindow : Window /// private static void FollowLastRun() { - if (AppServices.Current.Settings.PhysicsLog) + if (AppServices.Current.Settings.PhysicsLog || AppServices.Current.Settings.BlackBox) _ = Task.Run(AppServices.Current.Tapes.FollowLastRun); } diff --git a/StarterNG/Views/Settings.axaml b/StarterNG/Views/Settings.axaml index f6cd705..b49cc4d 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -553,6 +553,9 @@ + + + diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index aecbad4..bebe2b1 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -329,6 +329,7 @@ public partial class Settings : UserControl, ISettingsCapture WhileLoading(() => { SpeedometerTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLog; + BlackBoxCb.IsChecked = AppServices.Current.Settings.BlackBox; SimLogsCb.IsChecked = AppServices.Current.Settings.DebugLog; }); @@ -441,6 +442,7 @@ public partial class Settings : UserControl, ISettingsCapture PantographBreakCb.IsChecked = s.EnableTraction; OverheadOnlyCb.IsChecked = s.LiveTraction; SpeedometerTapesCb.IsChecked = s.PhysicsLog; + BlackBoxCb.IsChecked = s.BlackBox; SimLogsCb.IsChecked = s.DebugLog; KeepLogsCb.IsChecked = s.MultipleLogs; DisplaySimulationCb.IsChecked = s.DisplaySimulation; @@ -874,6 +876,7 @@ public partial class Settings : UserControl, ISettingsCapture s.EnableTraction = IsChecked(PantographBreakCb); s.LiveTraction = IsChecked(OverheadOnlyCb); s.PhysicsLog = IsChecked(SpeedometerTapesCb); + s.BlackBox = IsChecked(BlackBoxCb); s.DebugLog = IsChecked(SimLogsCb); s.MultipleLogs = IsChecked(KeepLogsCb); s.DisplaySimulation = IsChecked(DisplaySimulationCb); diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index 2ad9942..bef75b2 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -163,7 +163,7 @@ public sealed class HaslerTapeWindow : Window Content = _view }; - _recordingOff = Strip("HaslerRecordingOff", "HaslerRecordingEnable", settings => settings.PhysicsLog = true); + _recordingOff = Strip("HaslerRecordingOff", "HaslerRecordingEnable", settings => settings.BlackBox = true); _logOff = Strip("HaslerLogOff", "HaslerLogEnable", settings => settings.DebugLog = true); var folder = ToolButton(App.Loc["HaslerOpenFolder"]); @@ -229,14 +229,18 @@ public sealed class HaslerTapeWindow : Window private void ShowWhatIsKnown() { var settings = AppServices.Current.Settings; - _recordingOff.IsVisible = !settings.PhysicsLog; - _logOff.IsVisible = settings.PhysicsLog && !settings.DebugLog; + bool recording = settings.PhysicsLog || settings.BlackBox; + _recordingOff.IsVisible = !recording; + _logOff.IsVisible = recording && !settings.DebugLog; - bool canFollow = _running && _tapes.DrivenVehicle is not null; + // the black box alone writes the tapes when the simulator closes: only the physics log grows while it runs + bool canFollow = _running && settings.PhysicsLog && _tapes.DrivenVehicle is not null; _live.IsEnabled = canFollow; if (!canFollow) _live.IsChecked = false; - ToolTip.SetTip(_live, App.Loc[canFollow ? "HaslerLiveTip" : "HaslerLiveIdle"]); + ToolTip.SetTip(_live, App.Loc[canFollow ? "HaslerLiveTip" + : _running && !settings.PhysicsLog ? "HaslerLiveAtClose" + : "HaslerLiveIdle"]); } private DockPanel Strip(string textKey, string buttonKey, Action enable) diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 0bb1d32..674e288 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -497,7 +497,9 @@ Zvýšená přesnost fyziky Možnost zlomení pantografu Napájení jen pod trolejí - Ukládat pásky rychloměru + Nahrávat černou skříňku a pásky rychloměru + Nahrává jízdu do jednoho souboru ve složce physicslog/ a po zavření simulátoru zapíše pásky (.dat) vozidel, ve kterých jste byli. + Ukládat fyzikální log všech vozidel Ukládat log simulace Zachovat předchozí logy Zobrazit simulaci @@ -844,6 +846,7 @@ vlak {0} Řízené dříve Funguje, když běží relace spuštěná ze starteru. + Černá skříňka zapíše pásky po zavření simulátoru. Živě funguje s fyzikálním logem. Log simulátoru je vypnutý: starter nevidí přesedání. Zapnout log Vozidlo ze startu diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index e0a4ba1..53f5576 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -516,8 +516,10 @@ Disabling protects the pantograph from breaking on faulty overhead line geometry. Powered only under overhead line When disabled, a raised pantograph can power the vehicle even without touching the wire. - Save physics parameters log - Writes a detailed trip log to the physicslog/ folder. + Record the black box and the speedometer tapes + Records the session to one file in the physicslog/ folder and, when the simulator closes, writes the tapes (.dat) of the vehicles you were in. + Save the physics log of every vehicle + Writes the log of every vehicle of the scenery to the physicslog/ folder as it runs, 20 times a second. For diagnostics: on a large scenery that is hundreds of open files. Save simulation log Keep previous logs Creates a separate log file for each scenery instead of overwriting errors.txt. @@ -1073,6 +1075,7 @@ train {0} Driven earlier Works while a session started from the starter runs. + The black box writes the tapes when the simulator closes. Live works with the physics log. The simulator's log is off: the starter does not see changes of vehicle. Turn the log on Vehicle at the start diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 4c1a4dc..04e7cd2 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -497,7 +497,9 @@ Növelt fizikai pontosság Áramszedő törésének lehetősége Táplálás csak felsővezeték alatt - Sebességmérő-szalagok mentése + Fekete doboz és sebességmérő-szalagok rögzítése + A menetet egy fájlba rögzíti a physicslog/ mappában, és a szimulátor bezárásakor kiírja azoknak a járműveknek a szalagjait (.dat), amelyekben ültél. + Minden jármű fizikai naplójának mentése Szimulációs napló mentése Korábbi naplók megtartása Szimuláció megjelenítése @@ -844,6 +846,7 @@ vonat {0} Korábban vezetett Az indítóból indított munkamenet alatt működik. + A fekete doboz a szimulátor bezárásakor írja ki a szalagokat. Az élő nézet a fizikai naplóval működik. A szimulátor naplója ki van kapcsolva: az indító nem látja a járműváltást. Napló bekapcsolása Indulási jármű diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 3713dd5..d8e8edf 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -516,8 +516,10 @@ Wyłączenie chroni pantograf przed uszkodzeniem przy błędnej geometrii sieci. Zasilanie tylko pod siecią trakcyjna Gdy wyłączone, podniesiony pantograf zasila pojazd nawet bez kontaktu z drutem. - Zapisuj log parametrów fizycznych - Zapisuje szczegółowy log jazdy do folderu physicslog/. + Zapisuj czarną skrzynkę i taśmy prędkościomierza + Nagrywa przejazd do jednego pliku w folderze physicslog/, a po zamknięciu symulatora zapisuje taśmy (.dat) pojazdów, w których byłeś. + Zapisuj log parametrów fizycznych wszystkich pojazdów + Zapisuje na bieżąco log każdego pojazdu scenerii do folderu physicslog/, 20 razy na sekundę. Do diagnostyki: na dużej scenerii to setki otwartych plików. Zapisuj log z symulacji Zachowuj poprzednie logi Tworzy osobny plik logu dla każdej scenerii zamiast nadpisywać errors.txt. @@ -895,6 +897,7 @@ pociąg {0} Prowadzony wcześniej Działa, gdy trwa sesja uruchomiona ze Startera. + Czarna skrzynka zapisuje taśmy po zamknięciu symulatora. Na żywo działa z logiem parametrów fizycznych. Log symulatora jest wyłączony: Starter nie widzi przesiadek. Włącz log Pojazd ze startu diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index c73f842..a4639d9 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -497,7 +497,9 @@ Повышенная точность физики Возможность излома пантографа Питание только под контактной сетью - Сохранять ленты скоростемера + Записывать чёрный ящик и ленты скоростемера + Записывает поездку в один файл в папке physicslog/, а при закрытии симулятора сохраняет ленты (.dat) тех единиц, в которых вы были. + Сохранять физический лог всех единиц Сохранять журнал симуляции Сохранять предыдущие журналы Показывать симуляцию @@ -844,6 +846,7 @@ поезд {0} Управлялся ранее Работает, пока идёт сеанс, запущенный из стартера. + Чёрный ящик сохраняет ленты при закрытии симулятора. Режим «вживую» работает с физическим логом. Журнал симулятора выключен: стартер не видит пересадок. Включить журнал Транспорт на старте From 45105e7b9c0d26e0d457b47966cbd548afd1e1b9 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:50:02 +0100 Subject: [PATCH 03/20] fix(tapes): a command is not taken for the header, and a gap in a tape is neither driving nor distance - The header is the line that doesn't start with a figure. A line whose command, which is free text, says "Security" was taken for it, moving the alerter's column and dropping the line. - A tape the black box writes goes on after a gap when the player comes back to its vehicle. A step of more than twenty usual steps between two lines (a second at least) is time not recorded: no distance over it, and neither running nor standing time; the average with the stops leaves it out too. --- StarterNG.Tests/HaslerTapeTests.cs | 25 +++++++++ StarterNG/Domain/Tapes/HaslerTape.cs | 79 +++++++++++++++++++--------- 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/StarterNG.Tests/HaslerTapeTests.cs b/StarterNG.Tests/HaslerTapeTests.cs index 582fbaa..8858f7c 100644 --- a/StarterNG.Tests/HaslerTapeTests.cs +++ b/StarterNG.Tests/HaslerTapeTests.cs @@ -86,6 +86,31 @@ public class HaslerTapeTests 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 The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance() { diff --git a/StarterNG/Domain/Tapes/HaslerTape.cs b/StarterNG/Domain/Tapes/HaslerTape.cs index ffaf607..35e16c7 100644 --- a/StarterNG/Domain/Tapes/HaslerTape.cs +++ b/StarterNG/Domain/Tapes/HaslerTape.cs @@ -41,14 +41,23 @@ public sealed class HaslerTape private const int SecurityFromEndOf25 = 6; // a log with no header to tell: the columns up to the water's temperature private const int MinimumColumns = 17; + private const double MinimumGapSeconds = 1.0; + private const int GapSteps = 20; + public HaslerTape(IReadOnlyList samples) { Samples = samples; foreach (var s in samples) MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh); + double gap = GapAbove(samples); for (int i = 1; i < samples.Count; i++) - if (samples[i].SpeedKmh > 0.5) - RunningTime += samples[i].Time - samples[i - 1].Time; + { + double step = samples[i].Time - samples[i - 1].Time; + if (step > gap) + GapTime += step; + else if (samples[i].SpeedKmh > 0.5) + RunningTime += step; + } } public IReadOnlyList Samples { get; } @@ -63,54 +72,76 @@ public sealed class HaslerTape public double MaxSpeedKmh { get; } - /// Seconds on the move; the rest of was spent standing. + /// Seconds on the move; the rest of was spent standing, or not recorded. public double RunningTime { get; } - public double StandingTime => Duration - RunningTime; + /// Seconds of not recorded: the gaps, see . + public double GapTime { get; } + + public double StandingTime => Duration - RunningTime - GapTime; /// Mean speed while moving. public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0; /// Mean speed over the whole recording, stops included - the commercial speed. - public double AverageWithStopsKmh => Duration > 0 ? DistanceM / Duration * 3.6 : 0; + public double AverageWithStopsKmh => Duration - GapTime > 0 ? DistanceM / (Duration - GapTime) * 3.6 : 0; + + /// + /// A step between two lines longer than this is time not recorded, the player in another vehicle before + /// coming back to this one: neither driving nor standing, and no distance. The lines come every 0.05 s of + /// simulated time or so; it is twenty of their usual steps, a second at least. + /// + public static double GapAbove(IReadOnlyList samples) + { + if (samples.Count < 2) + return MinimumGapSeconds; + var steps = new double[samples.Count - 1]; + for (int i = 1; i < samples.Count; i++) + steps[i - 1] = samples[i].Time - samples[i - 1].Time; + Array.Sort(steps); + return Math.Max(MinimumGapSeconds, GapSteps * steps[steps.Length / 2]); + } public static HaslerTape Parse(string text) { var samples = new List(); - double distance = 0; - TapeSample? previous = null; int securityFromEnd = SecurityFromEndOf25; foreach (var raw in text.Split('\n')) { var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); - int heading = Array.IndexOf(columns, SecurityHeading); - if (heading >= 0) + if (columns.Length == 0) + continue; + if (!Number(columns[TimeColumn], out double time)) { - securityFromEnd = columns.Length - heading; + // the header; a line of figures may have the word too, in the free text of its command + int heading = Array.IndexOf(columns, SecurityHeading); + if (heading >= 0) + securityFromEnd = columns.Length - heading; continue; } - if (columns.Length < MinimumColumns - || !Number(columns[TimeColumn], out double time) - || !Number(columns[VelocityColumn], out double velocity)) - continue; // the header, or a line cut short by a simulator still writing + if (columns.Length < MinimumColumns || !Number(columns[VelocityColumn], out double velocity)) + continue; // a line cut short by a simulator still writing Number(columns[BrakePressColumn], out double brake); Number(columns[PipePressColumn], out double pipe); Number(columns[MotorCurrentColumn], out double current); bool security = securityFromEnd <= columns.Length && columns[^securityFromEnd] == "1"; - double speed = Math.Abs(velocity); - if (previous is { } p) - { - if (time < p.Time) - continue; - distance += (p.SpeedKmh + speed) / 2 / 3.6 * (time - p.Time); - } + if (samples.Count > 0 && time < samples[^1].Time) + continue; + samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security)); + } - var sample = new TapeSample(time, speed, distance, brake, pipe, current, security); - samples.Add(sample); - previous = sample; + // the distance, trapezoid by trapezoid, none over the gaps + double gap = GapAbove(samples), distance = 0; + for (int i = 1; i < samples.Count; i++) + { + var (before, sample) = (samples[i - 1], samples[i]); + double step = sample.Time - before.Time; + if (step <= gap) + distance += (before.SpeedKmh + sample.SpeedKmh) / 2 / 3.6 * step; + samples[i] = sample with { DistanceM = distance }; } return new HaslerTape(samples); From 1398545ff2f20614397acb79041a360efd280a6c Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:50:03 +0100 Subject: [PATCH 04/20] feat(tapes): "live" follows the tapes of the black box, which it writes as the simulator runs The simulator's black box writes the tapes of the player's vehicles every two seconds now, like the physics logs, which no longer keep their files open. - "Live" follows the player's tape with either one on; the tip that it waited for the closing is gone. - The descriptions of the two settings say how they write now, in the five languages. - A tape of a run the starter didn't launch goes with the black box recording when it was written: the tape of a vehicle the player left ends before the run does, and could be taken for a run of its own. --- .../BlackBox/BlackBoxListingTests.cs | 22 +++++++++++++++ StarterNG.Tests/StartSimulationTests.cs | 2 +- StarterNG/Application/HaslerTapes.cs | 27 ++++++++++++++----- StarterNG/Views/Tapes/HaslerTapeWindow.cs | 8 +++--- StarterNG/startercfg/lang/cz.xml | 3 +-- StarterNG/startercfg/lang/en.xml | 5 ++-- StarterNG/startercfg/lang/hu.xml | 3 +-- StarterNG/startercfg/lang/pl.xml | 5 ++-- StarterNG/startercfg/lang/ru.xml | 3 +-- 9 files changed, 54 insertions(+), 24 deletions(-) diff --git a/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs b/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs index ceed107..15af89f 100644 --- a/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs +++ b/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs @@ -80,6 +80,28 @@ public class BlackBoxListingTests 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 The_black_box_of_a_running_session_is_listed_while_it_is_written() { diff --git a/StarterNG.Tests/StartSimulationTests.cs b/StarterNG.Tests/StartSimulationTests.cs index 973683b..b291945 100644 --- a/StarterNG.Tests/StartSimulationTests.cs +++ b/StarterNG.Tests/StartSimulationTests.cs @@ -41,7 +41,7 @@ public class StartSimulationTests } [Fact] - public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes_at_the_end() + public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes() { var (start, _, installation) = Rig(files => files.WithExecutable(Build), sceneryClock: "07:52"); installation.SettingsStore.Settings.BlackBox = true; diff --git a/StarterNG/Application/HaslerTapes.cs b/StarterNG/Application/HaslerTapes.cs index a49baf8..9ef1d65 100644 --- a/StarterNG/Application/HaslerTapes.cs +++ b/StarterNG/Application/HaslerTapes.cs @@ -35,6 +35,7 @@ public sealed class HaslerTapes { private const int RememberedLaunches = 30; private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2); + private static readonly TimeSpan TapesAfterBlackBox = TimeSpan.FromSeconds(10); private readonly IFileSystem _files; private readonly IGamePaths _paths; @@ -244,8 +245,9 @@ public sealed class HaslerTapes /// /// The runs the tapes came from, the running or latest one first. A tape belongs /// to the last launch before it was written, unless a run the starter didn't launch - /// began between them; one with no launch goes with those written about the same - /// time, as a run writes them all at its end. + /// began between them; one with no launch goes with the black box recording when it + /// was written, or else with those written about the same time, as a run writes its + /// logs until it ends. /// public IReadOnlyList Sessions() { @@ -278,11 +280,14 @@ public sealed class HaslerTapes boxesBehind.GetValueOrDefault(launch, new List()))); } - // What no launch covers goes together by when it was written: a run writes it all at its end. + // What no launch covers goes together by when it was written: a run writes its logs until it ends. A tape + // written while a black box recorded is of its run, though: the black box writes the tapes of the player's + // vehicles as it goes, and that of a vehicle the player left ends before the run does. + var looseBoxes = boxes.Where(b => LaunchOf(b, launches) is null).ToList(); var loose = tapes.Where(t => tapeLaunch[t] is null) - .Select(t => (Written: t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null)) - .Concat(boxes.Where(b => LaunchOf(b, launches) is null) - .Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b))) + .Select(t => (Written: RecordingAt(t.LastWriteUtc, looseBoxes)?.LastWriteUtc ?? t.LastWriteUtc, + Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null)) + .Concat(looseBoxes.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b))) .OrderBy(file => file.Written); var run = new List(); var runBoxes = new List(); @@ -315,6 +320,16 @@ public sealed class HaslerTapes } } + /// + /// The black box that was recording at the moment, the tapes being written last, a moment after it is closed. + /// Of more, the one that stopped nearest to it. + /// + private static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable boxes) => + boxes.Where(box => NamedBy(box.Path) is { } named && named.StartedUtc <= momentUtc + && momentUtc <= box.LastWriteUtc + TapesAfterBlackBox) + .OrderBy(box => (box.LastWriteUtc - momentUtc).Duration()) + .FirstOrDefault(); + private TapeFile ReadTape(string path) => new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path)); diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index bef75b2..e917a3d 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -233,14 +233,12 @@ public sealed class HaslerTapeWindow : Window _recordingOff.IsVisible = !recording; _logOff.IsVisible = recording && !settings.DebugLog; - // the black box alone writes the tapes when the simulator closes: only the physics log grows while it runs - bool canFollow = _running && settings.PhysicsLog && _tapes.DrivenVehicle is not null; + // the physics logs and the black box's tapes both grow while the simulator runs, every two seconds + bool canFollow = _running && recording && _tapes.DrivenVehicle is not null; _live.IsEnabled = canFollow; if (!canFollow) _live.IsChecked = false; - ToolTip.SetTip(_live, App.Loc[canFollow ? "HaslerLiveTip" - : _running && !settings.PhysicsLog ? "HaslerLiveAtClose" - : "HaslerLiveIdle"]); + ToolTip.SetTip(_live, App.Loc[canFollow ? "HaslerLiveTip" : "HaslerLiveIdle"]); } private DockPanel Strip(string textKey, string buttonKey, Action enable) diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 674e288..3454476 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -498,7 +498,7 @@ Možnost zlomení pantografu Napájení jen pod trolejí Nahrávat černou skříňku a pásky rychloměru - Nahrává jízdu do jednoho souboru ve složce physicslog/ a po zavření simulátoru zapíše pásky (.dat) vozidel, ve kterých jste byli. + Nahrává jízdu do jednoho souboru ve složce physicslog/ a průběžně, každé 2 s, zapisuje pásky (.dat) vozidel, ve kterých jste. Ukládat fyzikální log všech vozidel Ukládat log simulace Zachovat předchozí logy @@ -846,7 +846,6 @@ vlak {0} Řízené dříve Funguje, když běží relace spuštěná ze starteru. - Černá skříňka zapíše pásky po zavření simulátoru. Živě funguje s fyzikálním logem. Log simulátoru je vypnutý: starter nevidí přesedání. Zapnout log Vozidlo ze startu diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index 53f5576..00d18b2 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -517,9 +517,9 @@ Powered only under overhead line When disabled, a raised pantograph can power the vehicle even without touching the wire. Record the black box and the speedometer tapes - Records the session to one file in the physicslog/ folder and, when the simulator closes, writes the tapes (.dat) of the vehicles you were in. + Records the session to one file in the physicslog/ folder and writes the tapes (.dat) of the vehicles you are in as it goes, every 2 s. Save the physics log of every vehicle - Writes the log of every vehicle of the scenery to the physicslog/ folder as it runs, 20 times a second. For diagnostics: on a large scenery that is hundreds of open files. + Writes the log of every vehicle of the scenery to the physicslog/ folder: a line every 0.05 s, added every 2 s. For diagnostics: on a large scenery that is hundreds of files. Save simulation log Keep previous logs Creates a separate log file for each scenery instead of overwriting errors.txt. @@ -1075,7 +1075,6 @@ train {0} Driven earlier Works while a session started from the starter runs. - The black box writes the tapes when the simulator closes. Live works with the physics log. The simulator's log is off: the starter does not see changes of vehicle. Turn the log on Vehicle at the start diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 04e7cd2..4f18345 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -498,7 +498,7 @@ Áramszedő törésének lehetősége Táplálás csak felsővezeték alatt Fekete doboz és sebességmérő-szalagok rögzítése - A menetet egy fájlba rögzíti a physicslog/ mappában, és a szimulátor bezárásakor kiírja azoknak a járműveknek a szalagjait (.dat), amelyekben ültél. + A menetet egy fájlba rögzíti a physicslog/ mappában, és menet közben, 2 másodpercenként kiírja azoknak a járműveknek a szalagjait (.dat), amelyekben ülsz. Minden jármű fizikai naplójának mentése Szimulációs napló mentése Korábbi naplók megtartása @@ -846,7 +846,6 @@ vonat {0} Korábban vezetett Az indítóból indított munkamenet alatt működik. - A fekete doboz a szimulátor bezárásakor írja ki a szalagokat. Az élő nézet a fizikai naplóval működik. A szimulátor naplója ki van kapcsolva: az indító nem látja a járműváltást. Napló bekapcsolása Indulási jármű diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index d8e8edf..bdbec33 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -517,9 +517,9 @@ Zasilanie tylko pod siecią trakcyjna Gdy wyłączone, podniesiony pantograf zasila pojazd nawet bez kontaktu z drutem. Zapisuj czarną skrzynkę i taśmy prędkościomierza - Nagrywa przejazd do jednego pliku w folderze physicslog/, a po zamknięciu symulatora zapisuje taśmy (.dat) pojazdów, w których byłeś. + Nagrywa przejazd do jednego pliku w folderze physicslog/ i na bieżąco, co 2 s, zapisuje taśmy (.dat) pojazdów, w których jesteś. Zapisuj log parametrów fizycznych wszystkich pojazdów - Zapisuje na bieżąco log każdego pojazdu scenerii do folderu physicslog/, 20 razy na sekundę. Do diagnostyki: na dużej scenerii to setki otwartych plików. + Zapisuje log każdego pojazdu scenerii do folderu physicslog/: wiersz co 0,05 s, dopisywany co 2 s. Do diagnostyki: na dużej scenerii to setki plików. Zapisuj log z symulacji Zachowuj poprzednie logi Tworzy osobny plik logu dla każdej scenerii zamiast nadpisywać errors.txt. @@ -897,7 +897,6 @@ pociąg {0} Prowadzony wcześniej Działa, gdy trwa sesja uruchomiona ze Startera. - Czarna skrzynka zapisuje taśmy po zamknięciu symulatora. Na żywo działa z logiem parametrów fizycznych. Log symulatora jest wyłączony: Starter nie widzi przesiadek. Włącz log Pojazd ze startu diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index a4639d9..bcdc7d4 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -498,7 +498,7 @@ Возможность излома пантографа Питание только под контактной сетью Записывать чёрный ящик и ленты скоростемера - Записывает поездку в один файл в папке physicslog/, а при закрытии симулятора сохраняет ленты (.dat) тех единиц, в которых вы были. + Записывает поездку в один файл в папке physicslog/ и по ходу, каждые 2 с, сохраняет ленты (.dat) тех единиц, в которых вы находитесь. Сохранять физический лог всех единиц Сохранять журнал симуляции Сохранять предыдущие журналы @@ -846,7 +846,6 @@ поезд {0} Управлялся ранее Работает, пока идёт сеанс, запущенный из стартера. - Чёрный ящик сохраняет ленты при закрытии симулятора. Режим «вживую» работает с физическим логом. Журнал симулятора выключен: стартер не видит пересадок. Включить журнал Транспорт на старте From 7823bb8d0941819b823dc73d8bbad87944d836a1 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:50:03 +0100 Subject: [PATCH 05/20] feat(blackbox): the speed of the wheels read from the cab record, shown when they slip or skid The simulator adds the speed of the wheels at the end of the cab record. It is read when there, and the cab panel shows it next to the vehicle's speed when the two are a km/h apart or more: the wheels slipping, or locked in a skid. --- Eu07.BlackBox.Views/BlackBoxStrings.cs | 2 ++ Eu07.BlackBox.Views/CabPanel.cs | 8 +++++++- Eu07.BlackBox/BlackBoxReader.cs | 3 +++ Eu07.BlackBox/Records.cs | 6 +++++- StarterNG.Tests/BlackBox/BlackBoxFile.cs | 5 ++++- StarterNG.Tests/BlackBox/BlackBoxSignalsTests.cs | 14 ++++++++++++++ 6 files changed, 35 insertions(+), 3 deletions(-) diff --git a/Eu07.BlackBox.Views/BlackBoxStrings.cs b/Eu07.BlackBox.Views/BlackBoxStrings.cs index dd94933..c31ad20 100644 --- a/Eu07.BlackBox.Views/BlackBoxStrings.cs +++ b/Eu07.BlackBox.Views/BlackBoxStrings.cs @@ -183,6 +183,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventSecurityBraking"] = "BRAKING BY {0}", ["EventTimetable"] = "Timetable {0}, {1}", ["CabSpeed"] = "Speed", + ["CabWheels"] = "wheels {0:0}", ["CabAiTarget"] = "AI {0:0} km/h", ["CabAcceleration"] = "Along", ["CabLateral"] = "Lateral", @@ -454,6 +455,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}", ["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 f896579..b5f9c50 100644 --- a/Eu07.BlackBox.Views/CabPanel.cs +++ b/Eu07.BlackBox.Views/CabPanel.cs @@ -22,6 +22,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; @@ -92,7 +93,12 @@ public sealed class CabPanel : Control var speed = MapView.Text(s.AbsSpeedKmh.ToString("0", culture), judgement is SpeedJudgement.Over ? Palette.Bad : judgement is SpeedJudgement.Slightly ? Palette.Warn : Palette.Text, 36, FontWeight.SemiBold); context.DrawText(speed, new Point(Pad, 24)); - 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)); + // the wheels, when they turn otherwise: slipping, or locked in a skid + if (s.WheelSpeedKmh is { } wheels && Math.Abs(Math.Abs(wheels) - s.AbsSpeedKmh) >= WheelsApartKmh) + context.DrawText(MapView.Text(string.Format(culture, Strings["CabWheels"], Math.Abs(wheels)), Palette.Warn, 12), + new Point(Pad + speed.Width + 4 + unit.Width + 8, 24 + speed.Height - 21)); double gaugeX = Pad + Math.Max(150, width * 0.42); if (s.AiValid) { 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 a5046af..91df8d0 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; 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/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() { From 06513537f0297499fa23fb1d04996df718aafe33 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:34:53 +0100 Subject: [PATCH 06/20] fix(tapes): a tape followed live reads only what was added, and a stall, a shared black box or a gap are told right At a higher time speed the simulator's log grows many times faster, and the live view read and split the whole file every two seconds. A followed tape now keeps its reader and reads only the bytes added; one begun anew (shorter, its end no longer what was read, or its time going back) is read whole. From the review: a gap is over two seconds, above the frame the simulator holds to a second, so a stall is driving or standing; a black box's time ends by the start of the next one, as a downloaded one was last written later; the summary shows what was recorded and what wasn't, and the trace breaks off at a gap; the cab panel's wheels compare signed speeds and stay clear of the gauges; each box's name is parsed once per listing. --- Eu07.BlackBox.Views/CabPanel.cs | 13 +- .../BlackBox/BlackBoxListingTests.cs | 39 +++++- StarterNG.Tests/HaslerTapeTests.cs | 71 +++++++++++ StarterNG/Application/HaslerTapes.cs | 103 +++++++++++++--- StarterNG/Domain/Tapes/HaslerTape.cs | 115 ++++++++++++++---- StarterNG/Views/Tapes/HaslerTapeWindow.cs | 9 +- StarterNG/Views/Tapes/TapeView.cs | 14 +++ StarterNG/startercfg/lang/cz.xml | 1 + StarterNG/startercfg/lang/en.xml | 1 + StarterNG/startercfg/lang/hu.xml | 1 + StarterNG/startercfg/lang/pl.xml | 1 + StarterNG/startercfg/lang/ru.xml | 1 + 12 files changed, 315 insertions(+), 54 deletions(-) diff --git a/Eu07.BlackBox.Views/CabPanel.cs b/Eu07.BlackBox.Views/CabPanel.cs index b5f9c50..e6cdfb1 100644 --- a/Eu07.BlackBox.Views/CabPanel.cs +++ b/Eu07.BlackBox.Views/CabPanel.cs @@ -95,11 +95,16 @@ public sealed class CabPanel : Control context.DrawText(speed, new Point(Pad, 24)); var unit = MapView.Text("km/h", Palette.DimText, 12); context.DrawText(unit, new Point(Pad + speed.Width + 4, 24 + speed.Height - 21)); - // the wheels, when they turn otherwise: slipping, or locked in a skid - if (s.WheelSpeedKmh is { } wheels && Math.Abs(Math.Abs(wheels) - s.AbsSpeedKmh) >= WheelsApartKmh) - context.DrawText(MapView.Text(string.Format(culture, Strings["CabWheels"], Math.Abs(wheels)), Palette.Warn, 12), - new Point(Pad + speed.Width + 4 + unit.Width + 8, 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; + using (context.PushClip(new Rect(wheelsX, 24, Math.Max(0, gaugeX - 8 - wheelsX), 40))) + context.DrawText(MapView.Text(string.Format(culture, Strings["CabWheels"], Math.Abs(wheels)), Palette.Warn, 12), + new Point(wheelsX, 24 + speed.Height - 21)); + } if (s.AiValid) { using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40))) diff --git a/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs b/StarterNG.Tests/BlackBox/BlackBoxListingTests.cs index 15af89f..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,9 +76,9 @@ 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); } @@ -102,6 +104,31 @@ public class BlackBoxListingTests 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/HaslerTapeTests.cs b/StarterNG.Tests/HaslerTapeTests.cs index 8858f7c..15e2934 100644 --- a/StarterNG.Tests/HaslerTapeTests.cs +++ b/StarterNG.Tests/HaslerTapeTests.cs @@ -111,6 +111,77 @@ public class HaslerTapeTests 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 The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance() { diff --git a/StarterNG/Application/HaslerTapes.cs b/StarterNG/Application/HaslerTapes.cs index 9ef1d65..c183ebe 100644 --- a/StarterNG/Application/HaslerTapes.cs +++ b/StarterNG/Application/HaslerTapes.cs @@ -284,8 +284,9 @@ public sealed class HaslerTapes // written while a black box recorded is of its run, though: the black box writes the tapes of the player's // vehicles as it goes, and that of a vehicle the player left ends before the run does. var looseBoxes = boxes.Where(b => LaunchOf(b, launches) is null).ToList(); + var recordings = Recordings(looseBoxes); var loose = tapes.Where(t => tapeLaunch[t] is null) - .Select(t => (Written: RecordingAt(t.LastWriteUtc, looseBoxes)?.LastWriteUtc ?? t.LastWriteUtc, + .Select(t => (Written: RecordingAt(t.LastWriteUtc, recordings)?.LastWriteUtc ?? t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null)) .Concat(looseBoxes.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b))) .OrderBy(file => file.Written); @@ -320,15 +321,38 @@ public sealed class HaslerTapes } } + /// + /// When each black box recorded, its name read once: from the start its name has, to when it was last written, + /// and the tapes a moment after. No longer than until the next one started, though: a box downloaded or copied + /// later was last written then, not when it stopped, and would take in the tapes of the runs since. + /// + public static IReadOnlyList<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> Recordings(IEnumerable boxes) + { + var named = boxes.Select(box => (Box: box, Named: NamedBy(box.Path))) + .Where(each => each.Named is not null) + .Select(each => (each.Box, FromUtc: each.Named!.Value.StartedUtc)) + .OrderBy(each => each.FromUtc) + .ToList(); + var recordings = new List<(BlackBoxRecording, DateTime, DateTime)>(named.Count); + for (int i = 0; i < named.Count; i++) + { + var to = named[i].Box.LastWriteUtc + TapesAfterBlackBox; + if (i + 1 < named.Count && named[i + 1].FromUtc < to) + to = named[i + 1].FromUtc; + recordings.Add((named[i].Box, named[i].FromUtc, to)); + } + return recordings; + } + /// /// The black box that was recording at the moment, the tapes being written last, a moment after it is closed. /// Of more, the one that stopped nearest to it. /// - private static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable boxes) => - boxes.Where(box => NamedBy(box.Path) is { } named && named.StartedUtc <= momentUtc - && momentUtc <= box.LastWriteUtc + TapesAfterBlackBox) - .OrderBy(box => (box.LastWriteUtc - momentUtc).Duration()) - .FirstOrDefault(); + public static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> recordings) => + recordings.Where(each => each.FromUtc <= momentUtc && momentUtc <= each.ToUtc) + .OrderBy(each => (each.Box.LastWriteUtc - momentUtc).Duration()) + .Select(each => each.Box) + .FirstOrDefault(); private TapeFile ReadTape(string path) => new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path)); @@ -426,19 +450,64 @@ public sealed class HaslerTapes return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded); } - public HaslerTape? Load(TapeFile file) + // the tape followed as the simulator writes it: what of its file was read, and where it ended + private readonly object _followedLock = new(); + private (string Path, long Read, byte[] Tail, HaslerTape.Reader Reader)? _followed; + // what of the end of the read part is kept, to tell the file still has it: one begun anew doesn't + private const int FollowedTail = 256; + + public HaslerTape? Load(TapeFile file) => Load(file, follow: false); + + private static byte[] Bytes(Stream stream, long from, long to) { - try + stream.Seek(from, SeekOrigin.Begin); + var bytes = new byte[to - from]; + stream.ReadExactly(bytes); + return bytes; + } + + /// + /// The tape of the file. Followed, the one read last and grown since: only what was added is read, so a log + /// written fast, at a higher time speed, is kept up with; a line not ended yet waits for the next time. Not + /// followed, or another file, or one shorter than was read - begun anew - it is read whole, and kept to be + /// followed from there. + /// + public HaslerTape? Load(TapeFile file, bool follow) + { + lock (_followedLock) { - // Through OpenRead, which does not mind the simulator still writing the file. - using var stream = _files.OpenRead(file.Path); - using var reader = new StreamReader(stream, Encoding.ASCII); - return HaslerTape.Parse(reader.ReadToEnd()); - } - catch (Exception ex) - { - _log.Log($"reading {file.Path}", ex); - return null; + try + { + // Through OpenRead, which does not mind the simulator still writing the file. + using var stream = _files.OpenRead(file.Path); + if (!stream.CanSeek) + { + _followed = null; + using var whole = new StreamReader(stream, Encoding.ASCII); + return HaslerTape.Parse(whole.ReadToEnd()); + } + + long length = stream.Length; + // the same file grown, its end as it was read: else another, or begun anew, read whole + if (!follow || _followed is not { } followed || followed.Path != file.Path || length < followed.Read + || !Bytes(stream, followed.Read - followed.Tail.Length, followed.Read).AsSpan().SequenceEqual(followed.Tail)) + followed = (file.Path, 0, Array.Empty(), new HaslerTape.Reader()); + followed.Reader.Feed(Encoding.ASCII.GetString(Bytes(stream, followed.Read, length))); + // the time went back in what was added: the log begun anew and already longer than was read + if (followed.Read > 0 && followed.Reader.WentBack) + { + followed = (file.Path, 0, Array.Empty(), new HaslerTape.Reader()); + followed.Reader.Feed(Encoding.ASCII.GetString(Bytes(stream, 0, length))); + } + _followed = (file.Path, length, Bytes(stream, Math.Max(0, length - FollowedTail), length), followed.Reader); + return followed.Reader.Tape(final: !follow); + } + catch (Exception ex) + { + _followed = null; + _log.Log($"reading {file.Path}", ex); + return null; + } } } } diff --git a/StarterNG/Domain/Tapes/HaslerTape.cs b/StarterNG/Domain/Tapes/HaslerTape.cs index 35e16c7..820ddc8 100644 --- a/StarterNG/Domain/Tapes/HaslerTape.cs +++ b/StarterNG/Domain/Tapes/HaslerTape.cs @@ -41,15 +41,22 @@ public sealed class HaslerTape private const int SecurityFromEndOf25 = 6; // a log with no header to tell: the columns up to the water's temperature private const int MinimumColumns = 17; - private const double MinimumGapSeconds = 1.0; + // above the longest step the simulator makes at once (its frame is held to a second) and a line's interval: a + // stall of the simulator, a dragged window say, is time driven or stood, not a gap + private const double MinimumGapSeconds = 2.0; private const int GapSteps = 20; - public HaslerTape(IReadOnlyList samples) + public HaslerTape(IReadOnlyList samples) : this(samples, GapAbove(samples)) + { + } + + // the gap already found, by the reader: the steps are sorted once, not again here + private HaslerTape(IReadOnlyList samples, double gap) { Samples = samples; foreach (var s in samples) MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh); - double gap = GapAbove(samples); + GapSeconds = gap; for (int i = 1; i < samples.Count; i++) { double step = samples[i].Time - samples[i - 1].Time; @@ -78,6 +85,9 @@ public sealed class HaslerTape /// Seconds of not recorded: the gaps, see . public double GapTime { get; } + /// A step between two lines longer than this is a gap: of this tape. + public double GapSeconds { get; } + public double StandingTime => Duration - RunningTime - GapTime; /// Mean speed while moving. @@ -89,7 +99,7 @@ public sealed class HaslerTape /// /// A step between two lines longer than this is time not recorded, the player in another vehicle before /// coming back to this one: neither driving nor standing, and no distance. The lines come every 0.05 s of - /// simulated time or so; it is twenty of their usual steps, a second at least. + /// simulated time or so; it is twenty of their usual steps, two seconds at least. /// public static double GapAbove(IReadOnlyList samples) { @@ -104,47 +114,102 @@ public sealed class HaslerTape public static HaslerTape Parse(string text) { - var samples = new List(); + var reader = new Reader(); + reader.Feed(text); + return reader.Tape(final: true); + } - int securityFromEnd = SecurityFromEndOf25; - foreach (var raw in text.Split('\n')) + /// + /// A tape read as it is written: each piece of the file given once, in order, so a log the simulator keeps + /// adding to - fast, at a higher time speed - is not read and split from its start every time it grows. A line + /// not ended yet waits for the rest. + /// + public sealed class Reader + { + private readonly List _samples = new(); + private readonly System.Text.StringBuilder _unended = new(); + private int _securityFromEnd = SecurityFromEndOf25; + + public void Feed(string text) + { + WentBack = false; + int start = 0; + for (int end = text.IndexOf('\n'); end >= 0; end = text.IndexOf('\n', start)) + { + if (_unended.Length > 0) + { + _unended.Append(text, start, end - start); + Keep(_unended.ToString(), _samples); + _unended.Clear(); + } + else + Keep(text.Substring(start, end - start), _samples); + start = end + 1; + } + _unended.Append(text, start, text.Length - start); + } + + /// + /// The tape of what was read. Final, the end of the file: a last line with no end is read too, though + /// only for this tape; otherwise it may be cut short by a simulator still writing, and waits. + /// + public HaslerTape Tape(bool final) + { + var read = _samples; + if (final && _unended.Length > 0) + { + read = new List(_samples); + Keep(_unended.ToString(), read); + } + // the distance, trapezoid by trapezoid, none over the gaps + var samples = new List(read.Count); + double gap = GapAbove(read), distance = 0; + for (int i = 0; i < read.Count; i++) + { + var sample = read[i]; + if (i > 0) + { + var before = read[i - 1]; + double step = sample.Time - before.Time; + if (step <= gap) + distance += (before.SpeedKmh + sample.SpeedKmh) / 2 / 3.6 * step; + } + samples.Add(sample with { DistanceM = distance }); + } + return new HaslerTape(samples, gap); + } + + private void Keep(string raw, List samples) { var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); if (columns.Length == 0) - continue; + return; if (!Number(columns[TimeColumn], out double time)) { // the header; a line of figures may have the word too, in the free text of its command int heading = Array.IndexOf(columns, SecurityHeading); if (heading >= 0) - securityFromEnd = columns.Length - heading; - continue; + _securityFromEnd = columns.Length - heading; + return; } if (columns.Length < MinimumColumns || !Number(columns[VelocityColumn], out double velocity)) - continue; // a line cut short by a simulator still writing + return; // a line cut short by a simulator still writing Number(columns[BrakePressColumn], out double brake); Number(columns[PipePressColumn], out double pipe); Number(columns[MotorCurrentColumn], out double current); - bool security = securityFromEnd <= columns.Length && columns[^securityFromEnd] == "1"; + bool security = _securityFromEnd <= columns.Length && columns[^_securityFromEnd] == "1"; if (samples.Count > 0 && time < samples[^1].Time) - continue; + { + WentBack = true; + return; + } samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security)); } - // the distance, trapezoid by trapezoid, none over the gaps - double gap = GapAbove(samples), distance = 0; - for (int i = 1; i < samples.Count; i++) - { - var (before, sample) = (samples[i - 1], samples[i]); - double step = sample.Time - before.Time; - if (step <= gap) - distance += (before.SpeedKmh + sample.SpeedKmh) / 2 / 3.6 * step; - samples[i] = sample with { DistanceM = distance }; - } - - return new HaslerTape(samples); + /// In the last piece fed, a line whose time was before the last one's, left out: maybe the log begun anew. + public bool WentBack { get; private set; } } /// Index of the last sample at or before the given time or distance. diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index e917a3d..d5dc3c2 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -631,7 +631,9 @@ public sealed class HaslerTapeWindow : Window _loading = true; try { - var tape = await Task.Run(() => _tapes.Load(file)); + // the same tape grown, as the simulator writes it: only what was added is read + bool follow = file.Path == _shown?.Path && file.Size >= _shown.Size; + var tape = await Task.Run(() => _tapes.Load(file, follow)); bool another = file.Path != _shown?.Path; _shown = file; _tapeless = null; @@ -646,10 +648,13 @@ public sealed class HaslerTapeWindow : Window _view.Tape = tape; ShowMark(scrollTo: another && !scrollToEnd); - _summary.Text = string.Format(App.Loc["HaslerSummary"], file.Vehicle, TapeFigures.Clock(tape.Duration), + // what was recorded is running and standing; a gap, the player in another vehicle, is neither + _summary.Text = string.Format(App.Loc["HaslerSummary"], file.Vehicle, TapeFigures.Clock(tape.Duration - tape.GapTime), TapeFigures.Clock(tape.RunningTime), TapeFigures.Clock(tape.StandingTime), tape.DistanceM / 1000.0, tape.MaxSpeedKmh, tape.AverageSpeedKmh, tape.AverageWithStopsKmh); + if (tape.GapTime > 0) + _summary.Text += " · " + string.Format(App.Loc["HaslerGap"], TapeFigures.Clock(tape.GapTime)); if (_context?.Scenery is { } scenery) _summary.Text += " · " + string.Format(App.Loc["HaslerScenario"], scenery); if (_context?.Train is { } train) diff --git a/StarterNG/Views/Tapes/TapeView.cs b/StarterNG/Views/Tapes/TapeView.cs index 88446c2..727fc30 100644 --- a/StarterNG/Views/Tapes/TapeView.cs +++ b/StarterNG/Views/Tapes/TapeView.cs @@ -247,8 +247,22 @@ public abstract class TapeView : Control } } + double? before = null; foreach (var s in tape.Samples) { + // A gap, the player in another vehicle, is not drawn as if the train drove or stood through it: the + // line breaks off there. + if (before is { } previous && s.Time - previous > tape.GapSeconds) + { + Flush(); + column = int.MinValue; + if (begun) + { + g.EndFigure(false); + begun = false; + } + } + before = s.Time; int c = (int)Math.Round(XOf(s)); double value = y(s); if (c != column) diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 3454476..3bd9b22 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -98,6 +98,7 @@ hodina neznámá, čas se počítá od startu simulace Pásku {0} se nepodařilo přečíst. {0} · zaznamenáno {1} (jízda {2}, stání {3}) · dráha {4:0.00} km · Vmax {5:0} km/h · průměr za jízdy {6:0} km/h · průměr se zastávkami {7:0} km/h + nezaznamenáno {0} {0} · {1:0.0} km · {2:0} km/h · válce {3:0.0} bar · proud {4} Válce HP diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index 00d18b2..3c10bf1 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -98,6 +98,7 @@ hour unknown, time counted from the start of the simulation Could not read the tape {0}. {0} · recorded {1} (running {2}, standing {3}) · distance {4:0.00} km · Vmax {5:0} km/h · running average {6:0} km/h · average with stops {7:0} km/h + not recorded {0} {0} · {1:0.0} km · {2:0} km/h · cylinders {3:0.0} bar · current {4} Cylinders BP diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 4f18345..2b4cf38 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -98,6 +98,7 @@ az óra ismeretlen, az idő a szimuláció kezdetétől számít A(z) {0} szalag nem olvasható. {0} · rögzítve {1} (menet {2}, állás {3}) · út {4:0.00} km · Vmax {5:0} km/h · menetátlag {6:0} km/h · átlag megállásokkal {7:0} km/h + nem rögzítve {0} {0} · {1:0.0} km · {2:0} km/h · hengerek {3:0.0} bar · áram {4} Hengerek Fővez. diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index bdbec33..8d02a3f 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -98,6 +98,7 @@ godzina nieznana, czas liczony od startu symulacji Nie udało się odczytać taśmy {0}. {0} · zarejestrowano {1} (jazda {2}, postój {3}) · droga {4:0.00} km · Vmax {5:0} km/h · Vśr jazdy {6:0} km/h · Vśr z postojami {7:0} km/h + nie zarejestrowano {0} {0} · {1:0.0} km · {2:0} km/h · cylindry {3:0.0} bar · prąd {4} Cylindry PG diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index bcdc7d4..2bca963 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -98,6 +98,7 @@ час неизвестен, время считается от начала симуляции Не удалось прочитать ленту {0}. {0} · записано {1} (движение {2}, стоянка {3}) · путь {4:0.00} км · Vmax {5:0} км/ч · средняя в движении {6:0} км/ч · средняя со стоянками {7:0} км/ч + не записано {0} {0} · {1:0.0} км · {2:0} км/ч · цилиндры {3:0.0} бар · ток {4} Цилиндры ТМ From b2fd53f7bc65bc689d099e0cb88e70e5fc3f23e5 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:46:26 +0100 Subject: [PATCH 07/20] fix(blackbox): the doors' sides as the driver has them, from the rear cab swapped The recording holds the left and right of the vehicle, and from its rear cab the driver's left doors are the vehicle's right, as the simulator works them. The cab panel and the events showed the vehicle's sides, so after a change of direction to the other cab the doors opened on the wrong side. A change of the cab tells nothing of the doors in the events. --- Eu07.BlackBox.Views/CabPanel.cs | 2 +- Eu07.BlackBox.Views/EventList.cs | 11 +++++--- Eu07.BlackBox/Records.cs | 20 +++++++++++++++ StarterNG.Tests/BlackBox/CabDoorsTests.cs | 31 +++++++++++++++++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 StarterNG.Tests/BlackBox/CabDoorsTests.cs diff --git a/Eu07.BlackBox.Views/CabPanel.cs b/Eu07.BlackBox.Views/CabPanel.cs index e6cdfb1..741bace 100644 --- a/Eu07.BlackBox.Views/CabPanel.cs +++ b/Eu07.BlackBox.Views/CabPanel.cs @@ -226,7 +226,7 @@ public sealed class CabPanel : Control // The doors under them, in two columns: open, permitted, the departure signal, the steps and the lock. top = Math.Max(bottom, top + 16 + 9 * LampRow) + 6; context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top)); - 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 be3b07d..a47f486 100644 --- a/Eu07.BlackBox.Views/EventList.cs +++ b/Eu07.BlackBox.Views/EventList.cs @@ -282,6 +282,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 @@ -291,7 +293,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) { @@ -299,8 +302,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); + // another cab swaps the sides, and tells nothing of the doors + bool sameCab = b.CabEnd == s.CabEnd; + 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/Records.cs b/Eu07.BlackBox/Records.cs index 91df8d0..bf100d7 100644 --- a/Eu07.BlackBox/Records.cs +++ b/Eu07.BlackBox/Records.cs @@ -375,6 +375,26 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit public bool Has(CabDevices device) => (Devices & device) == device; public bool Has(SecurityFlags flag) => (Security & flag) == flag; + 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/CabDoorsTests.cs b/StarterNG.Tests/BlackBox/CabDoorsTests.cs new file mode 100644 index 0000000..7907e73 --- /dev/null +++ b/StarterNG.Tests/BlackBox/CabDoorsTests.cs @@ -0,0 +1,31 @@ +using Eu07.BlackBox; + +namespace StarterNG.Tests.BlackBox; + +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); + } +} From 92c02834790f47687b86d73253e18899188705c8 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:46:27 +0100 Subject: [PATCH 08/20] feat(tapes): the tapes of every train, physicslog.trains, turned on with the tape recording The simulator writes the .dat logs of the drivers of rail vehicles only with "physicslog.trains yes": the tape of every train, without the road vehicles and the passengers that make "physicslog yes" hundreds of files. The settings have a box for it, "Turn on recording" of the tapes' window turns it on with the black box, and a launch is noted and followed with it. The black box goes with it when the ini says nothing of its own, as the simulator has it; the line is written only once on, or where the file has it. --- StarterNG.Tests/SettingsStoreTests.cs | 35 +++++++++++++++++++ StarterNG/Application/StartSimulation.cs | 2 +- .../Domain/Settings/SimulatorSettings.cs | 7 ++++ .../Settings/SettingsSerializer.cs | 13 ++++--- StarterNG/MainWindow.axaml.cs | 3 +- StarterNG/Views/Settings.axaml | 3 ++ StarterNG/Views/Settings.axaml.cs | 3 ++ StarterNG/Views/Tapes/HaslerTapeWindow.cs | 9 +++-- StarterNG/startercfg/lang/cz.xml | 2 ++ StarterNG/startercfg/lang/en.xml | 2 ++ StarterNG/startercfg/lang/hu.xml | 2 ++ StarterNG/startercfg/lang/pl.xml | 2 ++ StarterNG/startercfg/lang/ru.xml | 2 ++ 13 files changed, 77 insertions(+), 8 deletions(-) diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 1abd865..d07fcff 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1371,6 +1371,41 @@ public class SettingsStoreTests Assert.Equal("blackbox yes", LineFor(installation, "blackbox")); } + [Theory] + [InlineData("physicslog no\n", false, false)] + [InlineData("physicslog no\nphysicslog.trains yes\n", true, true)] + [InlineData("physicslog no\nphysicslog.trains yes\nblackbox no\n", true, false)] + public void The_logs_of_the_trains_are_read_and_bring_the_black_box_as_the_simulator_has_it(string ini, bool trains, bool recorded) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); + + installation.SettingsStore.Load(); + + Assert.Equal(trains, installation.SettingsStore.Settings.PhysicsLogTrains); + Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox); + } + + [Fact] + public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Save(); + Assert.Null(LineFor(installation, "physicslog.trains")); + + installation.SettingsStore.Settings.PhysicsLogTrains = true; + installation.SettingsStore.Settings.BlackBox = true; + installation.SettingsStore.Save(); + Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains")); + // it says no more than the logs of the trains bring + Assert.Null(LineFor(installation, "blackbox")); + + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.PhysicsLogTrains = false; + installation.SettingsStore.Save(); + Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains")); + } + [Fact] public void A_black_box_line_written_once_goes_away_when_it_says_no_more() { diff --git a/StarterNG/Application/StartSimulation.cs b/StarterNG/Application/StartSimulation.cs index cd310e1..d0d833e 100644 --- a/StarterNG/Application/StartSimulation.cs +++ b/StarterNG/Application/StartSimulation.cs @@ -144,7 +144,7 @@ public sealed class StartSimulation if (saveSettings) _settings.CaptureAndSave(); - if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox) + if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox || _settings.Settings.PhysicsLogTrains) _tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle); string[] arguments = freeFly || string.IsNullOrEmpty(vehicle) diff --git a/StarterNG/Domain/Settings/SimulatorSettings.cs b/StarterNG/Domain/Settings/SimulatorSettings.cs index 8e34200..b62bf3e 100644 --- a/StarterNG/Domain/Settings/SimulatorSettings.cs +++ b/StarterNG/Domain/Settings/SimulatorSettings.cs @@ -140,6 +140,13 @@ public sealed class SimulatorSettings public bool BlackBox; /// Whether eu07.ini had a line of its own for the black box when read: it is kept saying what is wanted. public bool BlackBoxInIni; + /// + /// The physics logs (.dat) of the trains only, "physicslog.trains": of each driver of rail vehicles, not of the + /// passengers nor of the vehicles of the roads. The tapes of every train, far fewer files than the log of every vehicle. + /// + public bool PhysicsLogTrains; + /// Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on. + public bool PhysicsLogTrainsInIni; public bool DebugLog = true; public bool MultipleLogs; public bool DisplaySimulation = true; diff --git a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs index 0d7227b..43198f8 100644 --- a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs +++ b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs @@ -157,9 +157,11 @@ public sealed class SettingsSerializer s.EnableTraction = c.GetBool("enabletraction", true); s.LiveTraction = c.GetBool("livetraction", true); s.PhysicsLog = c.GetBool("physicslog", false); - // the simulator records the black box along with the physics log when the ini says nothing of it + s.PhysicsLogTrainsInIni = c.Has("physicslog.trains"); + s.PhysicsLogTrains = c.GetBool("physicslog.trains", false); + // the simulator records the black box along with the physics logs when the ini says nothing of it s.BlackBoxInIni = c.Has("blackbox"); - s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog; + s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog || s.PhysicsLogTrains; int debugLog = c.GetInt("debuglog", 3); s.DebugLog = (debugLog & 1) != 0; s.DebugLogVisible = (debugLog & 2) != 0; @@ -373,10 +375,13 @@ public sealed class SettingsSerializer c.SetBool("enabletraction", s.EnableTraction); c.SetBool("livetraction", s.LiveTraction); c.SetBool("physicslog", s.PhysicsLog); - // written where it says more than the physics log, or where the file has it already: an ini without it + // written where it says more than the physics logs, or where the file has it already: an ini without it // stays so, and a line written once and no longer saying more goes away on the next save - if (s.BlackBoxInIni || s.BlackBox != s.PhysicsLog) + if (s.BlackBoxInIni || s.BlackBox != (s.PhysicsLog || s.PhysicsLogTrains)) c.SetBool("blackbox", s.BlackBox); + // a simulator before it doesn't know the line: an ini without it stays so while it is off + if (s.PhysicsLogTrainsInIni || s.PhysicsLogTrains) + c.SetBool("physicslog.trains", s.PhysicsLogTrains); c.SetInt("debuglog", (s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits); c.SetBool("multiplelogs", s.MultipleLogs); diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 4388013..db87da5 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -709,7 +709,8 @@ public partial class MainWindow : Window /// private static void FollowLastRun() { - if (AppServices.Current.Settings.PhysicsLog || AppServices.Current.Settings.BlackBox) + var settings = AppServices.Current.Settings; + if (settings.PhysicsLog || settings.BlackBox || settings.PhysicsLogTrains) _ = Task.Run(AppServices.Current.Tapes.FollowLastRun); } diff --git a/StarterNG/Views/Settings.axaml b/StarterNG/Views/Settings.axaml index b49cc4d..af447a6 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -556,6 +556,9 @@ + + + diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index bebe2b1..d2d74d3 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -330,6 +330,7 @@ public partial class Settings : UserControl, ISettingsCapture { SpeedometerTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLog; BlackBoxCb.IsChecked = AppServices.Current.Settings.BlackBox; + TrainTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLogTrains; SimLogsCb.IsChecked = AppServices.Current.Settings.DebugLog; }); @@ -443,6 +444,7 @@ public partial class Settings : UserControl, ISettingsCapture OverheadOnlyCb.IsChecked = s.LiveTraction; SpeedometerTapesCb.IsChecked = s.PhysicsLog; BlackBoxCb.IsChecked = s.BlackBox; + TrainTapesCb.IsChecked = s.PhysicsLogTrains; SimLogsCb.IsChecked = s.DebugLog; KeepLogsCb.IsChecked = s.MultipleLogs; DisplaySimulationCb.IsChecked = s.DisplaySimulation; @@ -877,6 +879,7 @@ public partial class Settings : UserControl, ISettingsCapture s.LiveTraction = IsChecked(OverheadOnlyCb); s.PhysicsLog = IsChecked(SpeedometerTapesCb); s.BlackBox = IsChecked(BlackBoxCb); + s.PhysicsLogTrains = IsChecked(TrainTapesCb); s.DebugLog = IsChecked(SimLogsCb); s.MultipleLogs = IsChecked(KeepLogsCb); s.DisplaySimulation = IsChecked(DisplaySimulationCb); diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index d5dc3c2..e34c1d4 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -163,7 +163,12 @@ public sealed class HaslerTapeWindow : Window Content = _view }; - _recordingOff = Strip("HaslerRecordingOff", "HaslerRecordingEnable", settings => settings.BlackBox = true); + // the black box, with the tapes of the player's vehicles, and the tapes of every train + _recordingOff = Strip("HaslerRecordingOff", "HaslerRecordingEnable", settings => + { + settings.BlackBox = true; + settings.PhysicsLogTrains = true; + }); _logOff = Strip("HaslerLogOff", "HaslerLogEnable", settings => settings.DebugLog = true); var folder = ToolButton(App.Loc["HaslerOpenFolder"]); @@ -229,7 +234,7 @@ public sealed class HaslerTapeWindow : Window private void ShowWhatIsKnown() { var settings = AppServices.Current.Settings; - bool recording = settings.PhysicsLog || settings.BlackBox; + bool recording = settings.PhysicsLog || settings.BlackBox || settings.PhysicsLogTrains; _recordingOff.IsVisible = !recording; _logOff.IsVisible = recording && !settings.DebugLog; diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 3bd9b22..8177d3d 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -500,6 +500,8 @@ Napájení jen pod trolejí Nahrávat černou skříňku a pásky rychloměru Nahrává jízdu do jednoho souboru ve složce physicslog/ a průběžně, každé 2 s, zapisuje pásky (.dat) vozidel, ve kterých jste. + Nahrávat pásky rychloměru všech vlaků + Průběžně, každé 2 s, zapisuje pásky (.dat) každého vlaku scenérie do složky physicslog/: jednu na strojvedoucího kolejových vozidel, bez silničních vozidel a cestujících. Mnohem méně souborů než fyzikální log každého vozidla. Ukládat fyzikální log všech vozidel Ukládat log simulace Zachovat předchozí logy diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index 3c10bf1..2e37b91 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -519,6 +519,8 @@ When disabled, a raised pantograph can power the vehicle even without touching the wire. Record the black box and the speedometer tapes Records the session to one file in the physicslog/ folder and writes the tapes (.dat) of the vehicles you are in as it goes, every 2 s. + Record the speedometer tapes of every train + Writes the tapes (.dat) of every train of the scenery to the physicslog/ folder as it goes, every 2 s: one per driver of rail vehicles, not of road vehicles nor passengers. Far fewer files than the physics log of every vehicle. Save the physics log of every vehicle Writes the log of every vehicle of the scenery to the physicslog/ folder: a line every 0.05 s, added every 2 s. For diagnostics: on a large scenery that is hundreds of files. Save simulation log diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 2b4cf38..b77a00d 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -500,6 +500,8 @@ Táplálás csak felsővezeték alatt Fekete doboz és sebességmérő-szalagok rögzítése A menetet egy fájlba rögzíti a physicslog/ mappában, és menet közben, 2 másodpercenként kiírja azoknak a járműveknek a szalagjait (.dat), amelyekben ülsz. + Minden vonat sebességmérő-szalagjának rögzítése + Menet közben, 2 másodpercenként kiírja a pálya minden vonatának szalagját (.dat) a physicslog/ mappába: egyet a sínjárművek minden vezetőjének, közúti járművek és utasok nélkül. Jóval kevesebb fájl, mint minden jármű fizikai naplója. Minden jármű fizikai naplójának mentése Szimulációs napló mentése Korábbi naplók megtartása diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 8d02a3f..37d3e05 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -519,6 +519,8 @@ Gdy wyłączone, podniesiony pantograf zasila pojazd nawet bez kontaktu z drutem. Zapisuj czarną skrzynkę i taśmy prędkościomierza Nagrywa przejazd do jednego pliku w folderze physicslog/ i na bieżąco, co 2 s, zapisuje taśmy (.dat) pojazdów, w których jesteś. + Zapisuj taśmy prędkościomierza wszystkich pociągów + Na bieżąco, co 2 s, zapisuje taśmy (.dat) każdego pociągu scenerii do folderu physicslog/: jedną na maszynistę pojazdów szynowych, bez pojazdów drogowych i pasażerów. Znacznie mniej plików niż log fizyki każdego pojazdu. Zapisuj log parametrów fizycznych wszystkich pojazdów Zapisuje log każdego pojazdu scenerii do folderu physicslog/: wiersz co 0,05 s, dopisywany co 2 s. Do diagnostyki: na dużej scenerii to setki plików. Zapisuj log z symulacji diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index 2bca963..669d65c 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -500,6 +500,8 @@ Питание только под контактной сетью Записывать чёрный ящик и ленты скоростемера Записывает поездку в один файл в папке physicslog/ и по ходу, каждые 2 с, сохраняет ленты (.dat) тех единиц, в которых вы находитесь. + Записывать ленты скоростемера всех поездов + По ходу, каждые 2 с, сохраняет ленты (.dat) каждого поезда сценария в папку physicslog/: по одной на машиниста рельсового состава, без автомобилей и пассажиров. Гораздо меньше файлов, чем физический журнал каждой единицы. Сохранять физический лог всех единиц Сохранять журнал симуляции Сохранять предыдущие журналы From 192f9fa4994ada1eee113d4a1faa10b04c0edf8b Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:53:36 +0100 Subject: [PATCH 09/20] feat(settings): the physics log of every vehicle left on is moved once to the tapes of the trains "physicslog yes" was the speedometer's tapes in an earlier starter, and many left it on: the log of every vehicle, hundreds of files on a big scenery. Read with it on and not moved yet, it becomes physicslog.trains with the black box (unless the ini turned the box off itself), marked starter.physicslog.moved so it happens once: turned on again, it stays. --- StarterNG.Tests/SettingsStoreTests.cs | 54 +++++++++++++++++-- StarterNG/Application/SettingsStore.cs | 2 + .../Domain/Settings/SimulatorSettings.cs | 5 ++ .../Settings/SettingsSerializer.cs | 22 ++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index d07fcff..5edc3e8 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1304,9 +1304,9 @@ public class SettingsStoreTests } [Theory] - [InlineData("physicslog yes\n", true)] + [InlineData("starter.physicslog.moved yes\nphysicslog yes\n", true)] [InlineData("physicslog no\n", false)] - [InlineData("physicslog yes\nblackbox no\n", false)] + [InlineData("starter.physicslog.moved yes\nphysicslog yes\nblackbox no\n", false)] [InlineData("physicslog no\nblackbox yes\n", true)] public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded) { @@ -1333,7 +1333,7 @@ public class SettingsStoreTests [Fact] public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line() { - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.Width = 1600; @@ -1343,7 +1343,7 @@ public class SettingsStoreTests } [Theory] - [InlineData("physicslog yes\nblackbox yes\n")] + [InlineData("starter.physicslog.moved yes\nphysicslog yes\nblackbox yes\n")] [InlineData("physicslog no\nblackbox yes\n")] public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini) { @@ -1362,7 +1362,7 @@ public class SettingsStoreTests public void The_physics_log_turned_off_keeps_the_tapes_it_brought() { // an ini of before the black box had a key: the tapes came with the physics log - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.PhysicsLog = false; @@ -1385,6 +1385,50 @@ public class SettingsStoreTests Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox); } + [Theory] + [InlineData("physicslog yes\n", true)] + [InlineData("physicslog yes\nblackbox no\n", false)] + public void The_physics_log_of_every_vehicle_left_on_is_moved_once_to_the_tapes_of_the_trains(string ini, bool recorded) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); + + installation.SettingsStore.Load(); + var s = installation.SettingsStore.Settings; + Assert.False(s.PhysicsLog); + Assert.True(s.PhysicsLogTrains); + // a black box the ini turned off itself stays off + Assert.Equal(recorded, s.BlackBox); + + installation.SettingsStore.Save(); + Assert.Equal("physicslog no", LineFor(installation, "physicslog")); + Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains")); + Assert.Equal("starter.physicslog.moved yes", LineFor(installation, "starter.physicslog.moved")); + } + + [Fact] + public void The_physics_log_of_every_vehicle_turned_on_again_stays_on() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Settings.PhysicsLog = true; + installation.SettingsStore.Save(); + + installation.SettingsStore.Load(); + + Assert.True(installation.SettingsStore.Settings.PhysicsLog); + Assert.Equal("physicslog yes", LineFor(installation, "physicslog")); + } + + [Fact] + public void A_new_ini_is_marked_so_the_physics_log_turned_on_later_is_never_moved() + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n")); + installation.SettingsStore.Load(); + installation.SettingsStore.Save(); + + Assert.Equal("starter.physicslog.moved yes", LineFor(installation, "starter.physicslog.moved")); + } + [Fact] public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them() { diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index f538db1..a185609 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -113,6 +113,8 @@ public sealed class SettingsStore _serializer.Read(Settings, _config); _synced = Render(Settings); + if (!LoadFailed) + SettingsSerializer.MovePhysicsLog(Settings); TouchConfigAge(); } diff --git a/StarterNG/Domain/Settings/SimulatorSettings.cs b/StarterNG/Domain/Settings/SimulatorSettings.cs index b62bf3e..69ca9a1 100644 --- a/StarterNG/Domain/Settings/SimulatorSettings.cs +++ b/StarterNG/Domain/Settings/SimulatorSettings.cs @@ -147,6 +147,11 @@ public sealed class SimulatorSettings public bool PhysicsLogTrains; /// Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on. public bool PhysicsLogTrainsInIni; + /// + /// Whether the physics log of every vehicle, which a starter before called the speedometer's tapes, was moved once + /// to the tapes of the trains and the black box: an ini read with it on and this not yet done is moved so. + /// + public bool PhysicsLogMoved; public bool DebugLog = true; public bool MultipleLogs; public bool DisplaySimulation = true; diff --git a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs index 43198f8..dbce591 100644 --- a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs +++ b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs @@ -9,6 +9,25 @@ namespace StarterNG.Infrastructure.Settings; public sealed class SettingsSerializer { + // the physics log of every vehicle moved once to the tapes of the trains (SimulatorSettings.PhysicsLogMoved) + private const string PhysicsLogMovedKey = "starter.physicslog.moved"; + + /// + /// "physicslog yes", left on from a starter which called it the speedometer's tapes: the log of every vehicle, + /// hundreds of files on a big scenery. Moved once to the tapes of the trains, with the black box unless the ini + /// turned it off itself; whoever wants the log of every vehicle turns it on again, and it stays so. A change of + /// the starter's, after the file is read, so saving writes it. + /// + public static void MovePhysicsLog(SimulatorSettings s) + { + if (!s.PhysicsLogMoved && s.PhysicsLog) + { + s.PhysicsLog = false; + s.PhysicsLogTrains = true; + } + s.PhysicsLogMoved = true; + } + private readonly bool _dlssPlatform; /// Whether the simulator can have DLSS here at all (not on macOS). @@ -162,6 +181,7 @@ public sealed class SettingsSerializer // the simulator records the black box along with the physics logs when the ini says nothing of it s.BlackBoxInIni = c.Has("blackbox"); s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog || s.PhysicsLogTrains; + s.PhysicsLogMoved = c.GetBool(PhysicsLogMovedKey, false); int debugLog = c.GetInt("debuglog", 3); s.DebugLog = (debugLog & 1) != 0; s.DebugLogVisible = (debugLog & 2) != 0; @@ -382,6 +402,8 @@ public sealed class SettingsSerializer // a simulator before it doesn't know the line: an ini without it stays so while it is off if (s.PhysicsLogTrainsInIni || s.PhysicsLogTrains) c.SetBool("physicslog.trains", s.PhysicsLogTrains); + if (s.PhysicsLogMoved) + c.SetBool(PhysicsLogMovedKey, true); c.SetInt("debuglog", (s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits); c.SetBool("multiplelogs", s.MultipleLogs); From f1d77addae328f271d9b238e2a162def95823eca Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:56:25 +0100 Subject: [PATCH 10/20] fix(tapes): a followed tape cut shorter meanwhile is read as it is, let go when the window closes - what is read up to the file's end counts, not the length taken before it; the end kept is made of the bytes read, with no second read - the window of the tapes forgets the followed one when closed - the door sides change only with the end of the cab, not when it is left (0) --- Eu07.BlackBox.Views/EventList.cs | 4 +-- StarterNG/Application/HaslerTapes.cs | 30 +++++++++++++++++++---- StarterNG/Views/Tapes/HaslerTapeWindow.cs | 6 ++++- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/Eu07.BlackBox.Views/EventList.cs b/Eu07.BlackBox.Views/EventList.cs index a47f486..b55cca9 100644 --- a/Eu07.BlackBox.Views/EventList.cs +++ b/Eu07.BlackBox.Views/EventList.cs @@ -302,8 +302,8 @@ public sealed class EventList : ListBox movingOpen = false; continue; } - // another cab swaps the sides, and tells nothing of the doors - bool sameCab = b.CabEnd == s.CabEnd; + // 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) diff --git a/StarterNG/Application/HaslerTapes.cs b/StarterNG/Application/HaslerTapes.cs index c183ebe..46ab209 100644 --- a/StarterNG/Application/HaslerTapes.cs +++ b/StarterNG/Application/HaslerTapes.cs @@ -458,12 +458,29 @@ public sealed class HaslerTapes public HaslerTape? Load(TapeFile file) => Load(file, follow: false); + /// No tape followed any more: what was kept of the last one is let go. + public void Forget() + { + lock (_followedLock) + _followed = null; + } + + // what the file has between the two: less, up to its end, when it was cut shorter since its length was taken private static byte[] Bytes(Stream stream, long from, long to) { stream.Seek(from, SeekOrigin.Begin); var bytes = new byte[to - from]; - stream.ReadExactly(bytes); - return bytes; + int read = stream.ReadAtLeast(bytes, bytes.Length, throwOnEndOfStream: false); + return read == bytes.Length ? bytes : bytes[..read]; + } + + // the end of what was read, after the part added to it + private static byte[] Tail(byte[] before, byte[] added) + { + if (added.Length >= FollowedTail) + return added[^FollowedTail..]; + var keptBefore = Math.Min(before.Length, FollowedTail - added.Length); + return [.. before[^keptBefore..], .. added]; } /// @@ -492,14 +509,17 @@ public sealed class HaslerTapes if (!follow || _followed is not { } followed || followed.Path != file.Path || length < followed.Read || !Bytes(stream, followed.Read - followed.Tail.Length, followed.Read).AsSpan().SequenceEqual(followed.Tail)) followed = (file.Path, 0, Array.Empty(), new HaslerTape.Reader()); - followed.Reader.Feed(Encoding.ASCII.GetString(Bytes(stream, followed.Read, length))); + // what was read, not the length taken before: the file may be cut shorter meanwhile + var added = Bytes(stream, followed.Read, length); + followed.Reader.Feed(Encoding.ASCII.GetString(added)); // the time went back in what was added: the log begun anew and already longer than was read if (followed.Read > 0 && followed.Reader.WentBack) { followed = (file.Path, 0, Array.Empty(), new HaslerTape.Reader()); - followed.Reader.Feed(Encoding.ASCII.GetString(Bytes(stream, 0, length))); + added = Bytes(stream, 0, length); + followed.Reader.Feed(Encoding.ASCII.GetString(added)); } - _followed = (file.Path, length, Bytes(stream, Math.Max(0, length - FollowedTail), length), followed.Reader); + _followed = (file.Path, followed.Read + added.Length, Tail(followed.Tail, added), followed.Reader); return followed.Reader.Tape(final: !follow); } catch (Exception ex) diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index e34c1d4..9cc1e3b 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -224,7 +224,11 @@ public sealed class HaslerTapeWindow : Window await RefreshListAsync(); }; Activated += (_, _) => ShowWhatIsKnown(); - Closed += (_, _) => _timer.Stop(); + Closed += (_, _) => + { + _timer.Stop(); + _tapes.Forget(); + }; } /// From 5ab9bce321d324cb20659b6e3d236093760bacc7 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 00:01:46 +0100 Subject: [PATCH 11/20] fix(settings): a profile is not moved to physicslog.trains, and a closed tape window keeps nothing - the one-time move runs on the player's own settings only; a profile from before it keeps physicslog as it was, and the player's mark of the move stays when it is applied - a read of the tapes under way when the window closes is let go --- StarterNG.Tests/SettingsStoreTests.cs | 17 +++++++++++++++++ StarterNG/Application/SettingsStore.cs | 11 +++++++++-- StarterNG/Views/Tapes/HaslerTapeWindow.cs | 10 ++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 5edc3e8..b712520 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1257,6 +1257,23 @@ public class SettingsStoreTests Assert.False(store.LoadFailed); } + [Fact] + public void A_profile_from_before_the_move_is_not_moved_and_keeps_the_players_mark() + { + var files = new InMemoryFileSystem() + .WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n") + .WithFile(Profile, "physicslog yes\n"); + var store = WithHome(files).SettingsStore; + store.Load(); + + Assert.True(store.TryLoadProfile(Profile)); + store.Save(); + + Assert.True(store.Settings.PhysicsLog); + Assert.False(store.Settings.PhysicsLogTrains); + Assert.Contains("starter.physicslog.moved yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); + } + [Fact] public void A_missing_profile_leaves_the_settings_as_they_are() { diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index a185609..8e39473 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -83,6 +83,9 @@ public sealed class SettingsStore string source = _files.FileExists(_savePath) ? _savePath : _paths.InstallationConfigPath(); LoadedFrom = source; LoadFrom(source); + // the player's own settings only, after the snapshot so the next save writes it; a profile is not moved + if (!LoadFailed) + SettingsSerializer.MovePhysicsLog(Settings); } /// A player with no settings of their own yet starts at High, in the file at once so the simulator goes by it too. @@ -113,8 +116,6 @@ public sealed class SettingsStore _serializer.Read(Settings, _config); _synced = Render(Settings); - if (!LoadFailed) - SettingsSerializer.MovePhysicsLog(Settings); TouchConfigAge(); } @@ -126,9 +127,15 @@ public sealed class SettingsStore { if (_files.FileExists(path)) { + // a profile saved before the move has no mark of it: the player's mark is kept, so their own + // physicslog is not moved again at the next start + bool moved = Settings.PhysicsLogMoved; LoadFrom(path); if (!LoadFailed) + { + Settings.PhysicsLogMoved |= moved; return true; + } } if (LoadFailed) diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index 9cc1e3b..7283026 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -73,6 +73,8 @@ public sealed class HaslerTapeWindow : Window private bool _running; private bool _loading; private bool _looking; + // closed: a read already under way when it closed is let go, not kept followed + private bool _closed; /// A setting went on from here; the settings page's boxes have to follow it. public event Action? LogEnabled; @@ -226,6 +228,7 @@ public sealed class HaslerTapeWindow : Window Activated += (_, _) => ShowWhatIsKnown(); Closed += (_, _) => { + _closed = true; _timer.Stop(); _tapes.Forget(); }; @@ -643,6 +646,11 @@ public sealed class HaslerTapeWindow : Window // the same tape grown, as the simulator writes it: only what was added is read bool follow = file.Path == _shown?.Path && file.Size >= _shown.Size; var tape = await Task.Run(() => _tapes.Load(file, follow)); + if (_closed) + { + _tapes.Forget(); + return; + } bool another = file.Path != _shown?.Path; _shown = file; _tapeless = null; @@ -697,6 +705,8 @@ public sealed class HaslerTapeWindow : Window try { var sessions = await Task.Run(_tapes.Sessions); + if (_closed) + return; bool live = _live.IsChecked == true; bool newDriven = live && DrivenTape(sessions) is { } driven && driven.Path != _followed; if (newDriven || Fingerprint(sessions) != _listed) From 13990a70369e8293e8a53232fb40784592cee7f8 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 00:05:10 +0100 Subject: [PATCH 12/20] refactor(settings): the move to the trains' tapes made simple, by the black box line An ini with no physicslog.trains line and blackbox yes gets physicslog.trains yes and physicslog no. The line of the trains' tapes, written from then on even when turned off again, is the mark that it was done; the starter.physicslog.moved key is gone. A profile goes the same way as the ini. --- StarterNG.Tests/SettingsStoreTests.cs | 66 ++++++++++--------- StarterNG/Application/SettingsStore.cs | 12 +--- .../Domain/Settings/SimulatorSettings.cs | 5 -- .../Settings/SettingsSerializer.cs | 27 +++----- 4 files changed, 49 insertions(+), 61 deletions(-) diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index b712520..2913880 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1258,20 +1258,20 @@ public class SettingsStoreTests } [Fact] - public void A_profile_from_before_the_move_is_not_moved_and_keeps_the_players_mark() + public void A_profile_from_before_the_tapes_of_the_trains_is_moved_as_the_ini_would_be() { var files = new InMemoryFileSystem() - .WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n") - .WithFile(Profile, "physicslog yes\n"); + .WithFile(UserIni, "physicslog no\nphysicslog.trains no\n") + .WithFile(Profile, "physicslog yes\nblackbox yes\n"); var store = WithHome(files).SettingsStore; store.Load(); Assert.True(store.TryLoadProfile(Profile)); store.Save(); - Assert.True(store.Settings.PhysicsLog); - Assert.False(store.Settings.PhysicsLogTrains); - Assert.Contains("starter.physicslog.moved yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); + Assert.False(store.Settings.PhysicsLog); + Assert.True(store.Settings.PhysicsLogTrains); + Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); } [Fact] @@ -1321,9 +1321,9 @@ public class SettingsStoreTests } [Theory] - [InlineData("starter.physicslog.moved yes\nphysicslog yes\n", true)] + [InlineData("physicslog yes\n", true)] [InlineData("physicslog no\n", false)] - [InlineData("starter.physicslog.moved yes\nphysicslog yes\nblackbox no\n", false)] + [InlineData("physicslog yes\nblackbox no\n", false)] [InlineData("physicslog no\nblackbox yes\n", true)] public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded) { @@ -1350,7 +1350,7 @@ public class SettingsStoreTests [Fact] public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line() { - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n")); + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.Width = 1600; @@ -1360,7 +1360,7 @@ public class SettingsStoreTests } [Theory] - [InlineData("starter.physicslog.moved yes\nphysicslog yes\nblackbox yes\n")] + [InlineData("physicslog yes\nblackbox yes\n")] [InlineData("physicslog no\nblackbox yes\n")] public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini) { @@ -1379,7 +1379,7 @@ public class SettingsStoreTests public void The_physics_log_turned_off_keeps_the_tapes_it_brought() { // an ini of before the black box had a key: the tapes came with the physics log - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "starter.physicslog.moved yes\nphysicslog yes\n")); + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.PhysicsLog = false; @@ -1403,9 +1403,9 @@ public class SettingsStoreTests } [Theory] - [InlineData("physicslog yes\n", true)] - [InlineData("physicslog yes\nblackbox no\n", false)] - public void The_physics_log_of_every_vehicle_left_on_is_moved_once_to_the_tapes_of_the_trains(string ini, bool recorded) + [InlineData("physicslog yes\nblackbox yes\n")] + [InlineData("physicslog no\nblackbox yes\n")] + public void Recording_turned_on_before_the_tapes_of_the_trains_is_moved_to_them(string ini) { var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); @@ -1413,37 +1413,43 @@ public class SettingsStoreTests var s = installation.SettingsStore.Settings; Assert.False(s.PhysicsLog); Assert.True(s.PhysicsLogTrains); - // a black box the ini turned off itself stays off - Assert.Equal(recorded, s.BlackBox); + Assert.True(s.BlackBox); installation.SettingsStore.Save(); Assert.Equal("physicslog no", LineFor(installation, "physicslog")); Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains")); - Assert.Equal("starter.physicslog.moved yes", LineFor(installation, "starter.physicslog.moved")); + Assert.Equal("blackbox yes", LineFor(installation, "blackbox")); + } + + [Theory] + [InlineData("physicslog yes\n", true)] + [InlineData("physicslog yes\nblackbox no\n", true)] + [InlineData("physicslog yes\nblackbox yes\nphysicslog.trains no\n", true)] + [InlineData("physicslog no\nblackbox yes\nphysicslog.trains no\n", false)] + public void Without_a_black_box_line_saying_yes_or_with_the_trains_tapes_line_nothing_is_moved(string ini, bool physicsLog) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); + + installation.SettingsStore.Load(); + + Assert.Equal(physicsLog, installation.SettingsStore.Settings.PhysicsLog); + Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains); } [Fact] - public void The_physics_log_of_every_vehicle_turned_on_again_stays_on() + public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on() { - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n")); + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\nblackbox yes\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.PhysicsLog = true; + installation.SettingsStore.Settings.PhysicsLogTrains = false; installation.SettingsStore.Save(); installation.SettingsStore.Load(); Assert.True(installation.SettingsStore.Settings.PhysicsLog); - Assert.Equal("physicslog yes", LineFor(installation, "physicslog")); - } - - [Fact] - public void A_new_ini_is_marked_so_the_physics_log_turned_on_later_is_never_moved() - { - var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n")); - installation.SettingsStore.Load(); - installation.SettingsStore.Save(); - - Assert.Equal("starter.physicslog.moved yes", LineFor(installation, "starter.physicslog.moved")); + Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains); + Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains")); } [Fact] diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index 8e39473..8ad1dbd 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -83,9 +83,6 @@ public sealed class SettingsStore string source = _files.FileExists(_savePath) ? _savePath : _paths.InstallationConfigPath(); LoadedFrom = source; LoadFrom(source); - // the player's own settings only, after the snapshot so the next save writes it; a profile is not moved - if (!LoadFailed) - SettingsSerializer.MovePhysicsLog(Settings); } /// A player with no settings of their own yet starts at High, in the file at once so the simulator goes by it too. @@ -116,6 +113,9 @@ public sealed class SettingsStore _serializer.Read(Settings, _config); _synced = Render(Settings); + // after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would + if (!LoadFailed) + SettingsSerializer.MoveToTrainTapes(Settings); TouchConfigAge(); } @@ -127,15 +127,9 @@ public sealed class SettingsStore { if (_files.FileExists(path)) { - // a profile saved before the move has no mark of it: the player's mark is kept, so their own - // physicslog is not moved again at the next start - bool moved = Settings.PhysicsLogMoved; LoadFrom(path); if (!LoadFailed) - { - Settings.PhysicsLogMoved |= moved; return true; - } } if (LoadFailed) diff --git a/StarterNG/Domain/Settings/SimulatorSettings.cs b/StarterNG/Domain/Settings/SimulatorSettings.cs index 69ca9a1..b62bf3e 100644 --- a/StarterNG/Domain/Settings/SimulatorSettings.cs +++ b/StarterNG/Domain/Settings/SimulatorSettings.cs @@ -147,11 +147,6 @@ public sealed class SimulatorSettings public bool PhysicsLogTrains; /// Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on. public bool PhysicsLogTrainsInIni; - /// - /// Whether the physics log of every vehicle, which a starter before called the speedometer's tapes, was moved once - /// to the tapes of the trains and the black box: an ini read with it on and this not yet done is moved so. - /// - public bool PhysicsLogMoved; public bool DebugLog = true; public bool MultipleLogs; public bool DisplaySimulation = true; diff --git a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs index dbce591..50a9a48 100644 --- a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs +++ b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs @@ -9,23 +9,19 @@ namespace StarterNG.Infrastructure.Settings; public sealed class SettingsSerializer { - // the physics log of every vehicle moved once to the tapes of the trains (SimulatorSettings.PhysicsLogMoved) - private const string PhysicsLogMovedKey = "starter.physicslog.moved"; - /// - /// "physicslog yes", left on from a starter which called it the speedometer's tapes: the log of every vehicle, - /// hundreds of files on a big scenery. Moved once to the tapes of the trains, with the black box unless the ini - /// turned it off itself; whoever wants the log of every vehicle turns it on again, and it stays so. A change of - /// the starter's, after the file is read, so saving writes it. + /// An ini of before the tapes of the trains, its recording turned on ("blackbox yes", with the physics log of every + /// vehicle, hundreds of files on a big scenery): moved to the tapes of the trains, the log of every vehicle off. + /// Once: saved, the line of the trains' tapes is in the file, even turned off again before. A change of the + /// starter's, after the file is read, so saving writes it. /// - public static void MovePhysicsLog(SimulatorSettings s) + public static void MoveToTrainTapes(SimulatorSettings s) { - if (!s.PhysicsLogMoved && s.PhysicsLog) - { - s.PhysicsLog = false; - s.PhysicsLogTrains = true; - } - s.PhysicsLogMoved = true; + if (s.PhysicsLogTrainsInIni || !s.BlackBoxInIni || !s.BlackBox) + return; + s.PhysicsLogTrains = true; + s.PhysicsLogTrainsInIni = true; + s.PhysicsLog = false; } private readonly bool _dlssPlatform; @@ -181,7 +177,6 @@ public sealed class SettingsSerializer // the simulator records the black box along with the physics logs when the ini says nothing of it s.BlackBoxInIni = c.Has("blackbox"); s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog || s.PhysicsLogTrains; - s.PhysicsLogMoved = c.GetBool(PhysicsLogMovedKey, false); int debugLog = c.GetInt("debuglog", 3); s.DebugLog = (debugLog & 1) != 0; s.DebugLogVisible = (debugLog & 2) != 0; @@ -402,8 +397,6 @@ public sealed class SettingsSerializer // a simulator before it doesn't know the line: an ini without it stays so while it is off if (s.PhysicsLogTrainsInIni || s.PhysicsLogTrains) c.SetBool("physicslog.trains", s.PhysicsLogTrains); - if (s.PhysicsLogMoved) - c.SetBool(PhysicsLogMovedKey, true); c.SetInt("debuglog", (s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits); c.SetBool("multiplelogs", s.MultipleLogs); From 76693c14946045215d91b48af3fe72165d5794e1 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 00:09:36 +0100 Subject: [PATCH 13/20] fix(settings): an imported ini moved to the trains' tapes too, a closed tape window forgets only its own tape - ImportFrom moves an ini of before the trains' tapes as a profile is - HaslerTapes.Forget takes the file: a window closing lets go of its own tape, not of the one another window follows --- StarterNG.Tests/HaslerTapeTests.cs | 20 ++++++++++++++++++++ StarterNG.Tests/SettingsStoreTests.cs | 18 ++++++++++++++++++ StarterNG/Application/HaslerTapes.cs | 10 +++++++--- StarterNG/Application/SettingsStore.cs | 2 ++ StarterNG/Views/Tapes/HaslerTapeWindow.cs | 5 +++-- 5 files changed, 50 insertions(+), 5 deletions(-) diff --git a/StarterNG.Tests/HaslerTapeTests.cs b/StarterNG.Tests/HaslerTapeTests.cs index 15e2934..43bc9c3 100644 --- a/StarterNG.Tests/HaslerTapeTests.cs +++ b/StarterNG.Tests/HaslerTapeTests.cs @@ -182,6 +182,26 @@ public class HaslerTapeTests Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6); } + [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/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 2913880..8b7dd7e 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1436,6 +1436,24 @@ public class SettingsStoreTests Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains); } + [Fact] + public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is() + { + string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini"); + var files = new InMemoryFileSystem() + .WithFile(UserIni, "physicslog yes\nphysicslog.trains no\n") + .WithFile(backup, "physicslog yes\nblackbox yes\n"); + var store = WithHome(files).SettingsStore; + store.Load(); + + Assert.True(store.ImportFrom(backup)); + store.Save(); + + Assert.False(store.Settings.PhysicsLog); + Assert.True(store.Settings.PhysicsLogTrains); + Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); + } + [Fact] public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on() { diff --git a/StarterNG/Application/HaslerTapes.cs b/StarterNG/Application/HaslerTapes.cs index 46ab209..9ba7fed 100644 --- a/StarterNG/Application/HaslerTapes.cs +++ b/StarterNG/Application/HaslerTapes.cs @@ -458,11 +458,15 @@ public sealed class HaslerTapes public HaslerTape? Load(TapeFile file) => Load(file, follow: false); - /// No tape followed any more: what was kept of the last one is let go. - public void Forget() + /// + /// The tape of this file no longer followed: what was kept of it is let go. Another file's, followed for another + /// window, stays. + /// + public void Forget(string path) { lock (_followedLock) - _followed = null; + if (_followed?.Path == path) + _followed = null; } // what the file has between the two: less, up to its end, when it was cut shorter since its length was taken diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index 8ad1dbd..28d340f 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -236,6 +236,8 @@ public sealed class SettingsStore s.WindowMaximized = maximized; s.CabLampLight = cabLampLight; s.DepthPrepassScene = depthPrepassScene; + // an ini of before the tapes of the trains goes the same way as a profile + SettingsSerializer.MoveToTrainTapes(s); return true; } diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index 7283026..004338d 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -230,7 +230,8 @@ public sealed class HaslerTapeWindow : Window { _closed = true; _timer.Stop(); - _tapes.Forget(); + if (_shown is { } shown) + _tapes.Forget(shown.Path); }; } @@ -648,7 +649,7 @@ public sealed class HaslerTapeWindow : Window var tape = await Task.Run(() => _tapes.Load(file, follow)); if (_closed) { - _tapes.Forget(); + _tapes.Forget(file.Path); return; } bool another = file.Path != _shown?.Path; From b63ba8fe2e93165c7a8bf5d02e176f780c3a8fd1 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 00:09:36 +0100 Subject: [PATCH 14/20] feat(start): starting with unsaved settings asks first Edits on the settings page (or of the keys) not saved yet: the start asks whether to save them and start, start without them, or not start. Closing the question starts nothing. "Start without saving settings" from the menu asks nothing, as it says what it does. --- StarterNG/MainWindow.axaml.cs | 12 ++++++++++++ StarterNG/Views/MessageBox.cs | 29 +++++++++++++++++++++++++++++ StarterNG/Views/Settings.axaml.cs | 5 ++++- StarterNG/startercfg/lang/cz.xml | 3 +++ StarterNG/startercfg/lang/en.xml | 3 +++ StarterNG/startercfg/lang/hu.xml | 3 +++ StarterNG/startercfg/lang/pl.xml | 3 +++ StarterNG/startercfg/lang/ru.xml | 3 +++ 8 files changed, 60 insertions(+), 1 deletion(-) diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index db87da5..008905a 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -610,6 +610,18 @@ public partial class MainWindow : Window App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo)) return; + // edits on the settings page not saved: said before they go to the simulator, or not + if (saveSettings && SettingsView.HasUnsavedChanges) + { + var save = await MessageBox.Choose(this, App.Loc["StartUnsavedMessage"], App.Loc["UnsavedChanges"], + App.Loc["StartUnsavedSave"], App.Loc["StartUnsavedWithout"]); + if (save is null) + return; + if (save == true) + SettingsView.Save(); + saveSettings = save == true; + } + LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path)); await FollowStartAsync(() => AppServices.Current.StartSimulation.Execute(freeFly, saveSettings)); diff --git a/StarterNG/Views/MessageBox.cs b/StarterNG/Views/MessageBox.cs index 30818b4..1067562 100644 --- a/StarterNG/Views/MessageBox.cs +++ b/StarterNG/Views/MessageBox.cs @@ -42,6 +42,35 @@ public static class MessageBox return yes; } + /// + /// A question with two answers and a way back: true for the first, false for the second, null when cancelled + /// or the window is closed - closing it never picks one of the answers. + /// + public static async Task Choose(Window owner, string message, string title, string firstText, + string secondText) + { + var win = FixedDialog(title, 460); + + bool? answer = null; + var first = DialogButton(firstText, "Accent", 80, () => { answer = true; win.Close(); }); + var second = DialogButton(secondText, "Flat", 80, () => { answer = false; win.Close(); }); + var cancel = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close()); + + win.Content = new StackPanel + { + Margin = new Avalonia.Thickness(16), + Spacing = 16, + Children = + { + new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap }, + ButtonRow(first, second, cancel) + } + }; + + await win.ShowDialog(owner); + return answer; + } + /// /// A notice with one action besides closing it, and a box to stop it coming /// back, which counts however the window is closed. diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index d2d74d3..176c839 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -1482,9 +1482,12 @@ public partial class Settings : UserControl, ISettingsCapture UpdateSaveState(); } + /// Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells. + public bool HasUnsavedChanges => _dirty || KeyboardConfig.Instance.Dirty; + private void UpdateSaveState() { - bool dirty = _dirty || KeyboardConfig.Instance.Dirty; + bool dirty = HasUnsavedChanges; SaveButton.Classes.Set("Accent", dirty); SaveStatus.Text = dirty ? App.Loc["UnsavedChanges"] : string.Empty; } diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 8177d3d..7fdd310 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -632,6 +632,9 @@ Připojit soupravu ze skladu Přidat soupravy ze souboru... Spustit bez uložení nastavení + Nastavení obsahuje neuložené změny. Simulátor se s nimi spustí, jen pokud budou uloženy. + Uložit a spustit + Spustit bez uložení Další způsoby spuštění Spustit bez vozidla Editor scenérie diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index 2e37b91..17fa374 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -658,6 +658,9 @@ Append warehouse consist Add consists from file... Start without saving settings + The settings have unsaved changes. The simulator starts with them only if they are saved. + Save and start + Start without saving More ways to start Start with no vehicle Scenery editor diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index b77a00d..8223491 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -632,6 +632,9 @@ Raktári szerelvény hozzáfűzése Szerelvények hozzáadása fájlból... Indítás a beállítások mentése nélkül + A beállításokban nem mentett módosítások vannak. A szimulátor csak akkor indul velük, ha mentve lesznek. + Mentés és indítás + Indítás mentés nélkül További indítási módok Indítás jármű nélkül Pályaszerkesztő diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 37d3e05..2ad493a 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -658,6 +658,9 @@ Dołącz skład z magazynu Dodaj składy z pliku... Uruchom bez zapisu ustawień + Ustawienia mają niezapisane zmiany. Symulator uruchomi się z nimi tylko wtedy, gdy zostaną zapisane. + Zapisz i uruchom + Uruchom bez zapisu Inne sposoby uruchomienia Uruchom bez pojazdu Edytor scenerii diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index 669d65c..f16810a 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -632,6 +632,9 @@ Присоединить состав со склада Добавить составы из файла... Запустить без сохранения настроек + В настройках есть несохранённые изменения. Симулятор запустится с ними, только если их сохранить. + Сохранить и запустить + Запустить без сохранения Другие способы запуска Запустить без транспорта Редактор сценария From 5b43e29f9ea76fd857dc5f99eb60b888b3cfba9a Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 00:16:13 +0100 Subject: [PATCH 15/20] fix(start): unsaved settings let go rather than started without, a failed save starts nothing - the second answer discards the edits (as "Restore" does): kept, the starter would write them when it closes, with auto-close while the simulator reads the file - a save that fails is said and the simulator is not started - settings read again from a file changed outside leave the page with no edit of its own - a closed tape window lets go of the file it read last, shown or not --- StarterNG/MainWindow.axaml.cs | 16 +++++++++++++--- StarterNG/Views/Settings.axaml.cs | 13 +++++++++++-- StarterNG/Views/Tapes/HaslerTapeWindow.cs | 7 +++++-- StarterNG/startercfg/lang/cz.xml | 4 ++-- StarterNG/startercfg/lang/en.xml | 4 ++-- StarterNG/startercfg/lang/hu.xml | 4 ++-- StarterNG/startercfg/lang/pl.xml | 4 ++-- StarterNG/startercfg/lang/ru.xml | 4 ++-- 8 files changed, 39 insertions(+), 17 deletions(-) diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 008905a..f978000 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -610,16 +610,26 @@ public partial class MainWindow : Window App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo)) return; - // edits on the settings page not saved: said before they go to the simulator, or not + // edits on the settings page not saved: saved, or let go - kept, the starter would write them when it + // closes, perhaps while the simulator reads the file if (saveSettings && SettingsView.HasUnsavedChanges) { var save = await MessageBox.Choose(this, App.Loc["StartUnsavedMessage"], App.Loc["UnsavedChanges"], App.Loc["StartUnsavedSave"], App.Loc["StartUnsavedWithout"]); if (save is null) return; - if (save == true) + if (save == false) + SettingsView.DiscardChanges(); + else + { SettingsView.Save(); - saveSettings = save == true; + if (AppServices.Current.SettingsStore.LastSaveFailed) + { + await MessageBox.Show(this, App.Loc["SettingsNotSaved"], App.Loc["UnsavedChanges"], + MessageBoxButtons.Ok); + return; + } + } } LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path)); diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index 176c839..c47af0d 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -316,7 +316,13 @@ public partial class Settings : UserControl, ISettingsCapture SelectExeCb.SelectedIndex = index; } - public void ReloadFromSettings() => ApplyToUi(); + /// The settings read again from the file: the page shows them, no edit of its own left. + public void ReloadFromSettings() + { + ApplyToUi(); + _dirty = false; + UpdateSaveState(); + } /// /// True while a cab-control binding is waiting for a keypress. The window's own @@ -1145,7 +1151,10 @@ public partial class Settings : UserControl, ISettingsCapture ThumbnailSizeChanged?.Invoke(); } - private void ResetButton_OnClick(object? sender, RoutedEventArgs e) + private void ResetButton_OnClick(object? sender, RoutedEventArgs e) => DiscardChanges(); + + /// The edits not saved let go, the page and the keys as the files have them: "Przywróć". + public void DiscardChanges() { AppServices.Current.SettingsStore.Load(); ApplyToUi(); diff --git a/StarterNG/Views/Tapes/HaslerTapeWindow.cs b/StarterNG/Views/Tapes/HaslerTapeWindow.cs index 004338d..46e29da 100644 --- a/StarterNG/Views/Tapes/HaslerTapeWindow.cs +++ b/StarterNG/Views/Tapes/HaslerTapeWindow.cs @@ -75,6 +75,8 @@ public sealed class HaslerTapeWindow : Window private bool _looking; // closed: a read already under way when it closed is let go, not kept followed private bool _closed; + // the file read last, kept by the tapes to be followed even once another is picked or none is shown + private string? _read; /// A setting went on from here; the settings page's boxes have to follow it. public event Action? LogEnabled; @@ -230,8 +232,8 @@ public sealed class HaslerTapeWindow : Window { _closed = true; _timer.Stop(); - if (_shown is { } shown) - _tapes.Forget(shown.Path); + if (_read is { } read) + _tapes.Forget(read); }; } @@ -646,6 +648,7 @@ public sealed class HaslerTapeWindow : Window { // the same tape grown, as the simulator writes it: only what was added is read bool follow = file.Path == _shown?.Path && file.Size >= _shown.Size; + _read = file.Path; var tape = await Task.Run(() => _tapes.Load(file, follow)); if (_closed) { diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 7fdd310..daeac62 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -632,9 +632,9 @@ Připojit soupravu ze skladu Přidat soupravy ze souboru... Spustit bez uložení nastavení - Nastavení obsahuje neuložené změny. Simulátor se s nimi spustí, jen pokud budou uloženy. + Nastavení obsahuje neuložené změny. Uložit je před spuštěním simulátoru? Uložit a spustit - Spustit bez uložení + Zahodit změny a spustit Další způsoby spuštění Spustit bez vozidla Editor scenérie diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index 17fa374..d3944ce 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -658,9 +658,9 @@ Append warehouse consist Add consists from file... Start without saving settings - The settings have unsaved changes. The simulator starts with them only if they are saved. + The settings have unsaved changes. Save them before starting the simulator? Save and start - Start without saving + Discard changes and start More ways to start Start with no vehicle Scenery editor diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 8223491..1799721 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -632,9 +632,9 @@ Raktári szerelvény hozzáfűzése Szerelvények hozzáadása fájlból... Indítás a beállítások mentése nélkül - A beállításokban nem mentett módosítások vannak. A szimulátor csak akkor indul velük, ha mentve lesznek. + A beállításokban nem mentett módosítások vannak. Menti őket a szimulátor indítása előtt? Mentés és indítás - Indítás mentés nélkül + Módosítások elvetése és indítás További indítási módok Indítás jármű nélkül Pályaszerkesztő diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 2ad493a..d819706 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -658,9 +658,9 @@ Dołącz skład z magazynu Dodaj składy z pliku... Uruchom bez zapisu ustawień - Ustawienia mają niezapisane zmiany. Symulator uruchomi się z nimi tylko wtedy, gdy zostaną zapisane. + Ustawienia mają niezapisane zmiany. Zapisać je przed uruchomieniem symulatora? Zapisz i uruchom - Uruchom bez zapisu + Odrzuć zmiany i uruchom Inne sposoby uruchomienia Uruchom bez pojazdu Edytor scenerii diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index f16810a..ea72368 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -632,9 +632,9 @@ Присоединить состав со склада Добавить составы из файла... Запустить без сохранения настроек - В настройках есть несохранённые изменения. Симулятор запустится с ними, только если их сохранить. + В настройках есть несохранённые изменения. Сохранить их перед запуском симулятора? Сохранить и запустить - Запустить без сохранения + Отменить изменения и запустить Другие способы запуска Запустить без транспорта Редактор сценария From 829a3e7a3d8225f4d7b8c66333d81bd80d4b8273 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 01:20:36 +0100 Subject: [PATCH 16/20] fix(start): discarding unsaved settings lets go of the page's edits only, a failed key save starts nothing - the page shows the settings as held again, not read from the file as Restore does, so what other pages set and not yet saved (the depot's filters, the window maximized) stays - the start goes on only once nothing is left to be saved, the keys' file included --- StarterNG/MainWindow.axaml.cs | 5 +++-- StarterNG/Views/Settings.axaml.cs | 17 +++++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index f978000..6f75ceb 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -619,11 +619,12 @@ public partial class MainWindow : Window if (save is null) return; if (save == false) - SettingsView.DiscardChanges(); + SettingsView.DiscardEdits(); else { SettingsView.Save(); - if (AppServices.Current.SettingsStore.LastSaveFailed) + // eu07.ini or the keys' file not written: still there to be saved + if (SettingsView.HasUnsavedChanges) { await MessageBox.Show(this, App.Loc["SettingsNotSaved"], App.Loc["UnsavedChanges"], MessageBoxButtons.Ok); diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index c47af0d..0b9e00d 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -1151,10 +1151,7 @@ public partial class Settings : UserControl, ISettingsCapture ThumbnailSizeChanged?.Invoke(); } - private void ResetButton_OnClick(object? sender, RoutedEventArgs e) => DiscardChanges(); - - /// The edits not saved let go, the page and the keys as the files have them: "Przywróć". - public void DiscardChanges() + private void ResetButton_OnClick(object? sender, RoutedEventArgs e) { AppServices.Current.SettingsStore.Load(); ApplyToUi(); @@ -1164,6 +1161,18 @@ public partial class Settings : UserControl, ISettingsCapture UpdateSaveState(); } + /// + /// The page's own edits let go, and the keys': the page shows the settings as held. Not read again from the file + /// as "Restore" does - what other pages set and not yet saved (a filter of the depot, the window maximized) stays. + /// + public void DiscardEdits() + { + ApplyToUi(); + _keyBindings.Reload(); + _dirty = false; + UpdateSaveState(); + } + /// The list as has it for the monitors there are now, with the size selected. private void SelectResolution(int width, int height) { From faa06fb9d8320251ee03be48fdb64fb44c184e6c Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 01:24:17 +0100 Subject: [PATCH 17/20] fix(settings): a profile or an ini exported takes the page's edits in a copy, so discarding them still works Saving a profile or exporting eu07.ini captured the page's edits into the settings held, so discarding them before a start showed them again and the start's save wrote them. The export writes a copy with the edits in; the settings held stay as saved. --- StarterNG.Tests/SettingsStoreTests.cs | 16 ++++++++++++++++ StarterNG/Application/SettingsStore.cs | 5 +++-- StarterNG/Views/Settings.Graphics.cs | 5 ++--- StarterNG/Views/Settings.axaml.cs | 5 ++--- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 8b7dd7e..68c1730 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -1274,6 +1274,22 @@ public class SettingsStoreTests Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); } + [Fact] + public void A_profile_exported_from_a_pages_edits_leaves_the_settings_held_and_the_ini_alone() + { + var files = new InMemoryFileSystem().WithFile(UserIni, "fieldofview 45\n"); + var store = WithHome(files).SettingsStore; + store.Load(); + var edited = store.Settings.Copy(); + edited.FieldOfView = 60; + + Assert.True(store.ExportTo(Profile, edited)); + + Assert.Contains("fieldofview 60", files.ReadAllText(Profile, System.Text.Encoding.UTF8)); + Assert.Equal(45, store.Settings.FieldOfView); + Assert.Contains("fieldofview 45", files.ReadAllText(UserIni, System.Text.Encoding.UTF8)); + } + [Fact] public void A_missing_profile_leaves_the_settings_as_they_are() { diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index 28d340f..036bf80 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -245,7 +245,8 @@ public sealed class SettingsStore /// Writes the settings as a complete eu07.ini somewhere else - this user's file /// with the settings applied - leaving the file itself and its state alone. /// - public bool ExportTo(string path) + /// What to write, when not the settings held: a page's edits, still not taken in. + public bool ExportTo(string path, SimulatorSettings? settings = null) { if (LoadFailed) { @@ -254,7 +255,7 @@ public sealed class SettingsStore } var copy = ConfigFile.Parse(_config.ToText()); - ApplyChanges(copy, Changes(Settings)); + ApplyChanges(copy, Changes(settings ?? Settings)); try { diff --git a/StarterNG/Views/Settings.Graphics.cs b/StarterNG/Views/Settings.Graphics.cs index 52e8146..a9114ee 100644 --- a/StarterNG/Views/Settings.Graphics.cs +++ b/StarterNG/Views/Settings.Graphics.cs @@ -328,9 +328,8 @@ public partial class Settings return; // The edits on screen go into the export as they would into a save, but the - // user's own eu07.ini is not written. - CaptureInto(AppServices.Current.Settings); - if (!AppServices.Current.SettingsStore.ExportTo(path)) + // user's own eu07.ini is not written, nor the settings held: the edits stay the page's, not saved. + if (!AppServices.Current.SettingsStore.ExportTo(path, Trial())) { await MessageBox.Show(owner, string.Format(App.Loc["ExportIniFailed"], path), App.Loc["ExportIni"], MessageBoxButtons.Ok); diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index 0b9e00d..648b1d1 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -235,9 +235,8 @@ public partial class Settings : UserControl, ISettingsCapture App.Loc["ProfileSaveAs"], MessageBoxButtons.YesNo)) return; - // Written beside the user's own eu07.ini, which stays as it is. - CaptureInto(AppServices.Current.Settings); - bool saved = AppServices.Current.SettingsStore.ExportTo(path); + // Written beside the user's own eu07.ini, which stays as it is; the edits stay the page's, not saved + bool saved = AppServices.Current.SettingsStore.ExportTo(path, Trial()); PopulateProfileCombo(); int idx = FindComboIndexByContent(ProfileCb, Path.GetFileNameWithoutExtension(path)); if (idx >= 0) ProfileCb.SelectedIndex = idx; From 195f358e558dfdbb7f863b51840b9b9d786228e4 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 13:06:58 +0100 Subject: [PATCH 18/20] refactor(tapes): the line of a tape drawn by a class of its own, so Sonar sees a figure ended after a gap Sonar (S2583, the reliability rating of #54) took the end of a figure after a gap in Trace for code never run: begun was changed by the local function Flush, and its analysis doesn't follow a local changed that way. Nothing was wrong in what was drawn. The columns of the line are kept by ColumnLine, in its fields, and drawn through the three calls it is given, the figure begun, a line to the next point and its end; Trace hands it those of the StreamGeometry. What is drawn is the same. Tests: a column entered where it started and left where it ended through its lowest and highest, a break ending the figure and the next point beginning another, a break with nothing drawn ending nothing. Co-Authored-By: Claude Opus 5.5 --- StarterNG.Tests/ColumnLineTests.cs | 55 ++++++++++++++++++++++++ StarterNG/Views/Tapes/ColumnLine.cs | 65 +++++++++++++++++++++++++++++ StarterNG/Views/Tapes/TapeView.cs | 50 ++-------------------- 3 files changed, 124 insertions(+), 46 deletions(-) create mode 100644 StarterNG.Tests/ColumnLineTests.cs create mode 100644 StarterNG/Views/Tapes/ColumnLine.cs 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/Views/Tapes/ColumnLine.cs b/StarterNG/Views/Tapes/ColumnLine.cs new file mode 100644 index 0000000..7273681 --- /dev/null +++ b/StarterNG/Views/Tapes/ColumnLine.cs @@ -0,0 +1,65 @@ +using System; +using Avalonia; + +namespace StarterNG.Views.Tapes; + +/// +/// The line of a tape, one column of pixels at a time: of each column, the first, the lowest, the highest and the +/// last point in it, entered where the column started and left where it ended, so a long trip draws as fast as a +/// short one. The figures go out through the three calls given: one begun at its first point, a line to each next, +/// and its end. +/// +/// +/// Its state is kept in fields, not in the locals of a local function, which Sonar's analysis doesn't see changed +/// by it (S2583 took the end of a figure after a gap for code never run). +/// +internal sealed class ColumnLine(Action begin, Action lineTo, Action end) +{ + private bool _begun; + private int _column = int.MinValue; + private double _top, _bottom, _first, _last; + + /// The point of a sample, at its column of pixels. + public void Add(int column, double value) + { + if (column != _column) + { + Flush(); + _column = column; + _top = _bottom = _first = value; + } + _top = Math.Min(_top, value); + _bottom = Math.Max(_bottom, value); + _last = value; + } + + /// The line ends here, at a gap or at the end of the tape; a point added after begins a figure of its own. + public void Break() + { + Flush(); + _column = int.MinValue; + if (!_begun) + return; + end(); + _begun = false; + } + + private void Flush() + { + if (_column == int.MinValue) + return; + // Enter where the column started, leave where it ended. + var (a, b) = _first <= _last ? (_top, _bottom) : (_bottom, _top); + foreach (double v in new[] { _first, a, b, _last }) + { + var p = new Point(_column, v); + if (_begun) + lineTo(p); + else + { + begin(p); + _begun = true; + } + } + } +} diff --git a/StarterNG/Views/Tapes/TapeView.cs b/StarterNG/Views/Tapes/TapeView.cs index 5cf5e47..d02f9ec 100644 --- a/StarterNG/Views/Tapes/TapeView.cs +++ b/StarterNG/Views/Tapes/TapeView.cs @@ -341,60 +341,18 @@ public abstract class TapeView : Control { var geometry = new StreamGeometry(); using var g = geometry.Open(); - bool begun = false; - int column = int.MinValue; - double top = 0, bottom = 0, first = 0, last = 0; - - void Flush() - { - if (column == int.MinValue) - return; - // Enter where the column started, leave where it ended. - var (a, b) = first <= last ? (top, bottom) : (bottom, top); - foreach (double v in new[] { first, a, b, last }) - { - var p = new Point(column, v); - if (!begun) - { - g.BeginFigure(p, false); - begun = true; - } - else - g.LineTo(p); - } - } - + var line = new ColumnLine(p => g.BeginFigure(p, false), p => g.LineTo(p), () => g.EndFigure(false)); double? before = null; foreach (var s in tape.Samples) { // A gap, the player in another vehicle, is not drawn as if the train drove or stood through it: the // line breaks off there. if (before is { } previous && s.Time - previous > tape.GapSeconds) - { - Flush(); - column = int.MinValue; - if (begun) - { - g.EndFigure(false); - begun = false; - } - } + line.Break(); before = s.Time; - int c = (int)Math.Round(XOf(s)); - double value = y(s); - if (c != column) - { - Flush(); - column = c; - top = bottom = first = value; - } - top = Math.Min(top, value); - bottom = Math.Max(bottom, value); - last = value; + line.Add((int)Math.Round(XOf(s)), y(s)); } - Flush(); - if (begun) - g.EndFigure(false); + line.Break(); return geometry; } } From fa8ae760e1a5ca879fbba799d088f9dd774354b2 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 15:42:56 +0100 Subject: [PATCH 19/20] fix(tests): the black box text tests wait their turn with the other Avalonia ones EventTextsTests and SecurityBrakingTests from #55 ran beside the Avalonia controls collection; their AppBuilder setup raced it and 28 UI tests failed with "Setup was already called" on every runner. Co-Authored-By: Claude Opus 5.5 --- StarterNG.Tests/BlackBox/EventTextsTests.cs | 1 + StarterNG.Tests/BlackBox/SecurityBrakingTests.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/StarterNG.Tests/BlackBox/EventTextsTests.cs b/StarterNG.Tests/BlackBox/EventTextsTests.cs index d3cd3ba..9b1635f 100644 --- a/StarterNG.Tests/BlackBox/EventTextsTests.cs +++ b/StarterNG.Tests/BlackBox/EventTextsTests.cs @@ -3,6 +3,7 @@ using Eu07.BlackBox.Views; namespace StarterNG.Tests.BlackBox; +[Collection(AvaloniaControls.Name)] public class EventTextsTests { [Theory] diff --git a/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs b/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs index 12e0816..8fb4fa9 100644 --- a/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs +++ b/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs @@ -4,6 +4,7 @@ using Eu07.BlackBox.Views; namespace StarterNG.Tests.BlackBox; +[Collection(AvaloniaControls.Name)] public class SecurityBrakingTests { // as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too From f0fa2d176816770855db36adf64d03e4442a2531 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 15:58:31 +0100 Subject: [PATCH 20/20] test(tapes): the tapes window, the choice asked before a start, the wheels and the doors from the other cab - HaslerTapeWindow: with nothing recorded it offers to record and turns on the black box and the trains' tapes; a tape of the last launch is summed up with its scenario and train, and is no longer followed once the window closes. - HaslerTapes.Load: a log begun anew over the end that was read is read whole once its time goes back; an unreadable tape is none and told in the log; a file read only forward is read whole each time. Empty log lines are passed over. - MessageBox.Choose: the answer clicked, or none on the way back or on closing. - CabPanel: wheels turning apart from the train are said beside its speed. - EventList: going to the other cab tells nothing of the doors, still the switches. - WarehouseEditTests and ConsistOrientationTests put in app-wide services of their own: they now wait their turn with the controls that read them. Co-Authored-By: Claude Opus 5.5 --- .../BlackBox/BlackBoxViewsTests.cs | 28 ++++++ StarterNG.Tests/BlackBox/CabDoorsTests.cs | 18 ++++ StarterNG.Tests/ConsistOrientationTests.cs | 2 + StarterNG.Tests/Fakes/ForwardOnlyStream.cs | 29 ++++++ StarterNG.Tests/Fakes/InMemoryFileSystem.cs | 15 ++- StarterNG.Tests/HaslerTapeTests.cs | 61 +++++++++++- StarterNG.Tests/HaslerTapeWindowTests.cs | 96 +++++++++++++++++++ StarterNG.Tests/MessageBoxTests.cs | 87 +++++++++++++++++ StarterNG.Tests/WarehouseEditTests.cs | 2 + 9 files changed, 335 insertions(+), 3 deletions(-) create mode 100644 StarterNG.Tests/Fakes/ForwardOnlyStream.cs create mode 100644 StarterNG.Tests/HaslerTapeWindowTests.cs create mode 100644 StarterNG.Tests/MessageBoxTests.cs 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 index 7907e73..d801d0c 100644 --- a/StarterNG.Tests/BlackBox/CabDoorsTests.cs +++ b/StarterNG.Tests/BlackBox/CabDoorsTests.cs @@ -1,7 +1,10 @@ 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) => @@ -28,4 +31,19 @@ public class CabDoorsTests 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/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 43bc9c3..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} ") + @@ -182,6 +182,63 @@ public class HaslerTapeTests 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() { 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