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.
This commit is contained in:
maj00r
2026-11-15 23:34:53 +01:00
parent 7823bb8d09
commit 06513537f0
12 changed files with 315 additions and 54 deletions

View File

@@ -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
}
}
/// <summary>
/// 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.
/// </summary>
public static IReadOnlyList<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> Recordings(IEnumerable<BlackBoxRecording> 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;
}
/// <summary>
/// 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.
/// </summary>
private static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable<BlackBoxRecording> 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;
}
/// <summary>
/// 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.
/// </summary>
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<byte>(), 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<byte>(), 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;
}
}
}
}

View File

@@ -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<TapeSample> samples)
public HaslerTape(IReadOnlyList<TapeSample> samples) : this(samples, GapAbove(samples))
{
}
// the gap already found, by the reader: the steps are sorted once, not again here
private HaslerTape(IReadOnlyList<TapeSample> 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
/// <summary>Seconds of <see cref="Duration"/> not recorded: the gaps, see <see cref="GapAbove"/>.</summary>
public double GapTime { get; }
/// <summary>A step between two lines longer than this is a gap: <see cref="GapAbove"/> of this tape.</summary>
public double GapSeconds { get; }
public double StandingTime => Duration - RunningTime - GapTime;
/// <summary>Mean speed while moving.</summary>
@@ -89,7 +99,7 @@ public sealed class HaslerTape
/// <summary>
/// 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.
/// </summary>
public static double GapAbove(IReadOnlyList<TapeSample> samples)
{
@@ -104,47 +114,102 @@ public sealed class HaslerTape
public static HaslerTape Parse(string text)
{
var samples = new List<TapeSample>();
var reader = new Reader();
reader.Feed(text);
return reader.Tape(final: true);
}
int securityFromEnd = SecurityFromEndOf25;
foreach (var raw in text.Split('\n'))
/// <summary>
/// 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.
/// </summary>
public sealed class Reader
{
private readonly List<TapeSample> _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);
}
/// <summary>
/// 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.
/// </summary>
public HaslerTape Tape(bool final)
{
var read = _samples;
if (final && _unended.Length > 0)
{
read = new List<TapeSample>(_samples);
Keep(_unended.ToString(), read);
}
// the distance, trapezoid by trapezoid, none over the gaps
var samples = new List<TapeSample>(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<TapeSample> 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);
/// <summary>In the last piece fed, a line whose time was before the last one's, left out: maybe the log begun anew.</summary>
public bool WentBack { get; private set; }
}
/// <summary>Index of the last sample at or before the given time or distance.</summary>

View File

@@ -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)

View File

@@ -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)

View File

@@ -98,6 +98,7 @@
<String key="HaslerClockUnknown">hodina neznámá, čas se počítá od startu simulace</String>
<String key="HaslerUnreadable">Pásku {0} se nepodařilo přečíst.</String>
<String key="HaslerSummary">{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</String>
<String key="HaslerGap">nezaznamenáno {0}</String>
<String key="HaslerCursor">{0} · {1:0.0} km · {2:0} km/h · válce {3:0.0} bar · proud {4}</String>
<String key="HaslerTrackCylinders">Válce</String>
<String key="HaslerTrackPipe">HP</String>

View File

@@ -98,6 +98,7 @@
<String key="HaslerClockUnknown">hour unknown, time counted from the start of the simulation</String>
<String key="HaslerUnreadable">Could not read the tape {0}.</String>
<String key="HaslerSummary">{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</String>
<String key="HaslerGap">not recorded {0}</String>
<String key="HaslerCursor">{0} · {1:0.0} km · {2:0} km/h · cylinders {3:0.0} bar · current {4}</String>
<String key="HaslerTrackCylinders">Cylinders</String>
<String key="HaslerTrackPipe">BP</String>

View File

@@ -98,6 +98,7 @@
<String key="HaslerClockUnknown">az óra ismeretlen, az idő a szimuláció kezdetétől számít</String>
<String key="HaslerUnreadable">A(z) {0} szalag nem olvasható.</String>
<String key="HaslerSummary">{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</String>
<String key="HaslerGap">nem rögzítve {0}</String>
<String key="HaslerCursor">{0} · {1:0.0} km · {2:0} km/h · hengerek {3:0.0} bar · áram {4}</String>
<String key="HaslerTrackCylinders">Hengerek</String>
<String key="HaslerTrackPipe">Fővez.</String>

View File

@@ -98,6 +98,7 @@
<String key="HaslerClockUnknown">godzina nieznana, czas liczony od startu symulacji</String>
<String key="HaslerUnreadable">Nie udało się odczytać taśmy {0}.</String>
<String key="HaslerSummary">{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</String>
<String key="HaslerGap">nie zarejestrowano {0}</String>
<String key="HaslerCursor">{0} · {1:0.0} km · {2:0} km/h · cylindry {3:0.0} bar · prąd {4}</String>
<String key="HaslerTrackCylinders">Cylindry</String>
<String key="HaslerTrackPipe">PG</String>

View File

@@ -98,6 +98,7 @@
<String key="HaslerClockUnknown">час неизвестен, время считается от начала симуляции</String>
<String key="HaslerUnreadable">Не удалось прочитать ленту {0}.</String>
<String key="HaslerSummary">{0} · записано {1} (движение {2}, стоянка {3}) · путь {4:0.00} км · Vmax {5:0} км/ч · средняя в движении {6:0} км/ч · средняя со стоянками {7:0} км/ч</String>
<String key="HaslerGap">не записано {0}</String>
<String key="HaslerCursor">{0} · {1:0.0} км · {2:0} км/ч · цилиндры {3:0.0} бар · ток {4}</String>
<String key="HaslerTrackCylinders">Цилиндры</String>
<String key="HaslerTrackPipe">ТМ</String>