Compare commits

...

46 Commits

Author SHA1 Message Date
maj00r
be7b9c5679 Merge main into feat/tapes-from-blackbox
Conflicts:
- CabPanel.cs: main (#50) tells the screen reader what the panel draws, this branch keeps the km/h
  label for the speed of the wheels beside it and shows the doors as the cab sees them. Both kept, and
  the speed of the wheels, new on this branch, is told to the screen reader too, as all the rest.
- Records.cs: main (#55) adds the buzzers and the protection braking, this branch AsTheCabSees. Both kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:02:47 +01:00
3c9b578e6b Merge pull request #55 from MaSzyna-EU07/feat/command-descriptions
Black box: commands described, the protection's buzzer apart from its braking
2026-11-16 09:16:55 +00:00
952618be13 Merge pull request #52 from MaSzyna-EU07/fix/exe-list-refresh
fix: a simulator copied in while the starter runs is on the list
2026-11-16 09:16:17 +00:00
156af3fdd1 Merge pull request #51 from MaSzyna-EU07/fix/noavx2-exe
fix: without AVX2 the starter starts the simulator built without it
2026-11-16 09:16:05 +00:00
49b76aa66c Merge pull request #49 from MaSzyna-EU07/fix/reshade-beside-starter
fix: graphics wrappers beside the starter no longer reach its window
2026-11-16 09:15:52 +00:00
9b1523ef78 Merge pull request #50 from MaSzyna-EU07/fix/screen-reader-names
fix: a screen reader user can find, hear and work every part of the starter
2026-11-16 09:15:39 +00:00
1d5b0ea1f4 Merge pull request #46 from MaSzyna-EU07/fix/linux-file-case
fix: find game data whatever the case of its names on Linux
2026-11-16 09:14:44 +00:00
maj00r
8baf2149ea fix(blackbox): a buzzer named by the lamps of its buzzing samples only 2026-11-16 02:21:23 +01:00
maj00r
aebfaf34ac fix(blackbox): a buzzer cut by the power or the protection switched off is not acknowledged, and is named by every lamp it had
The keys tab's English names the train brake's positions and the dashboard light as the black box does.
2026-11-16 02:20:34 +01:00
maj00r
5bc5da3fbf feat(blackbox): the train protection's buzzer told apart from its braking
The buzzer has a colour of its own on the timeline and in the cab, no longer the braking's red, and an event of its
own: acknowledged after how long, or not acknowledged when the braking follows. The alerter's buzzer needs its lamp,
since a protection with one acknowledgement tells the cab signalling's buzzer as the alerter's too. Braking with no
lamp, the protection with no power, is not shown as the driver's on the timeline and in the cab either.
2026-11-16 02:17:57 +01:00
maj00r
e4d092ab3e fix(blackbox): the command texts set right, and in the old starter's languages as the keys tab has them
Spelling and wording fixed (świateł, piasecznica, dezaktywacja, podgrzewacz wody, the dashboard light, the
locomotive brake), and the train brake's service and full service positions told by what they set, not as the key
file swaps them. In Czech, Hungarian and Russian the commands are named in the old starter's key descriptions.
2026-11-16 02:17:57 +01:00
maj00r
632e1003ee fix(blackbox): the protection braking with no power not counted as the driver's
TSecuritySystem brakes whenever it has no power, a cab not yet started or a power cut, with no lamp
lit. Only braking with the alerter or the cab signalling lamp is the driver's not acknowledging.
2026-11-16 02:04:22 +01:00
maj00r
34ee131d61 feat(blackbox): the commands in the events and on the timeline told by what they do
Every command of a vehicle the simulator can record (input/command.cpp) has a Polish and an English
text: those with a key take the key file's and the starter's own, the rest are written out. A command
with no text keeps its name.
2026-11-16 02:04:22 +01:00
maj00r
faa06fb9d8 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.
2026-11-16 01:24:17 +01:00
maj00r
829a3e7a3d 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
2026-11-16 01:20:36 +01:00
maj00r
5b43e29f9e 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
2026-11-16 00:16:13 +01:00
maj00r
b63ba8fe2e 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.
2026-11-16 00:09:36 +01:00
maj00r
76693c1494 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
2026-11-16 00:09:36 +01:00
maj00r
13990a7036 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.
2026-11-16 00:05:10 +01:00
maj00r
5ab9bce321 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
2026-11-16 00:01:46 +01:00
maj00r
f1d77addae 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)
2026-11-15 23:56:25 +01:00
maj00r
192f9fa499 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.
2026-11-15 23:53:36 +01:00
maj00r
92c0283479 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.
2026-11-15 23:46:27 +01:00
maj00r
b2fd53f7bc 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.
2026-11-15 23:46:26 +01:00
maj00r
06513537f0 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.
2026-11-15 23:34:53 +01:00
maj00r
38802845c7 test: no-AVX2 build names carry the date as the simulator writes it, 2026-11-15 2026-11-15 21:35:58 +01:00
maj00r
bba9e3ef48 fix: without AVX2 the starter starts the simulator built without it
The simulator now also comes built without AVX2, its file name ending in
_noavx2 (eu07-x64_<date>_<hash>_noavx2.exe, eu07_noavx2 on Linux), and both
builds can lie side by side in the game folder. The automatic choice took
eu07.exe or the shortest name and never that one, so a processor without
AVX2 got a simulator that stops at its first instruction and a notice
telling it to build its own.

Without AVX2 the automatic choice now takes the newest _noavx2 build, even
one through Wine before a native build that would not run. With AVX2 the
build made for it stays first and a _noavx2 one is used only when it is all
there is.

The notice comes only when what would start still needs AVX2. With a
_noavx2 build in the folder but another chosen by hand it names both and
offers to go back to the automatic choice; with none it says what such a
build is called and that the starter picks it up from the game folder.
2026-11-15 21:28:47 +01:00
maj00r
f29ce10f5c fix: a simulator copied in while the starter runs is on the list
The list of simulators in the settings was filled when they opened, so a new
eu07*.exe from CI or one's own build stayed missing until the starter was
reopened, and the older file was easy to start by mistake. The folder is now
looked at again when the settings page is shown, when the list takes focus
and when the window comes back to the front.

Looking again never changes the choice: a file picked from elsewhere, or one
since removed, stays chosen rather than falling back to automatic, and
nothing waits for Save after it. A list that did not change is left alone.

Closes #48
2026-11-15 21:13:53 +01:00
maj00r
6e2dbf9eac test: the system graphics libraries and the software render switch
Taking the libraries and the switch's options are apart from Main, so they are
tested on every system, not only where Windows has them to load.
2026-11-15 17:30:13 +01:00
maj00r
91c496ab48 fix: graphics wrappers beside the starter no longer reach its window
ReShade installed for Direct3D as dxgi.dll in the simulator's folder was
loaded into the starter as well, and its window came up empty. The system
dxgi, d3d11, d3d9 and opengl32 are loaded first, and the window code's own
imports are handed those. The simulator still finds its wrappers.

--software-render draws the window on the processor, on Windows and X11,
for a machine on which it still comes up empty.
2026-11-15 14:41:48 +01:00
maj00r
7823bb8d09 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.
2026-11-14 00:50:03 +01:00
maj00r
1398545ff2 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.
2026-11-14 00:50:03 +01:00
maj00r
45105e7b9c 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.
2026-11-14 00:50:02 +01:00
maj00r
4429eff4ef 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.
2026-11-14 00:05:06 +01:00
maj00r
1ef630b1b6 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.
2026-11-14 00:05:05 +01:00
maj00r
7cd3ef8f1a test: the in-memory disk has the root of an absolute Linux path 2026-11-13 17:44:26 +01:00
maj00r
1b41ef752a chore: version 1.6
Data names are now found whatever their letter case on Linux.
2026-11-13 16:23:47 +01:00
maj00r
42f702a096 fix: an include in other letter case is no fault, as eu07 opens it
eu07 now finds files whatever the case of their names on Linux too
(MaSzyna-EU07/maszyna#362), so the starter no longer folds an include or a
scenery's .sbt to lower case to judge whether the simulator opens it: it
looks them up through CaseInsensitivePaths. The IncludeLetterCase fault and
its texts go, being a false alarm now, and the parser takes a plain yes or
no for each include.
2026-11-13 16:23:47 +01:00
maj00r
7f57160aae fix: open a livery's folder whatever the case of its name
"Open texture folder" finds the folder under dynamic, or from the game
folder, through CaseInsensitivePaths, so on Linux it opens the folder
when textures.txt names it in other letter case.
2026-11-13 16:23:47 +01:00
maj00r
2efae83b57 fix: find the loading screen logo whatever the case of its name
The textures/logo folder and a trainset's or scenery's logo in it are
looked up through CaseInsensitivePaths, with extensions in any case, so
on Linux the chosen logo is shown instead of a random one or none. The
lookup takes the file system, so it is tested.
2026-11-13 16:23:47 +01:00
maj00r
34f2ce99e8 fix: list files whatever the case of their extensions on Linux
PhysicalFileSystem matches a search pattern case-insensitively, as on
Windows, so X.SCN, .BMP minis and .FIZ files of data made on Windows are
listed on Linux as well.
2026-11-13 16:23:47 +01:00
maj00r
52408a9931 fix: follow .fiz includes and check vehicle files whatever their case
An include in a .fiz is looked up in the vehicle's folder through
CaseInsensitivePaths, so its physics are read on Linux when the include
names the file in other letter case. The missing-asset scan finds skins and
models the same way, with extensions in any case, instead of reporting
files that are there.
2026-11-13 16:23:47 +01:00
maj00r
290b753f40 fix: open a scenery's attachments whatever the case of their names
A //$f attachment is looked up from the game folder through the new
AttachmentLocator, so on Linux its button is enabled and opens the file
when the scenery names it in other letter case or with backslashes.
2026-11-13 16:23:47 +01:00
maj00r
6279228a7d fix: find a scenery's i18n tables whatever the case of their names
The i18n folder and its <scenery>_<language>.json tables are looked up
through CaseInsensitivePaths, so on Linux a scenery's texts are translated
when the table is named in other letter case than the scenery file.
2026-11-13 16:23:47 +01:00
maj00r
d4975796a8 fix: find a scenery's image and timetables whatever the case of their names
The //$i image and a trainset's timetable are looked up through
CaseInsensitivePaths, so on Linux they show when the scenery names them in
other letter case than the disk has. A timetable written with backslashes
is found there too, and with it the train number of a Hasler tape.
2026-11-13 16:23:47 +01:00
maj00r
48af11b4b2 refactor: share the case-insensitive lookup of data files
The scenery repository's include lookup becomes CaseInsensitivePaths, which
takes any folder over IFileSystem and gives a name as it is on disk. Of
folders named alike in other case it now tries each, not only the first.
A name is joined to the folder as the simulator joins it, a leading slash
counting for nothing. IFileSystem tells whether the disk ignores case; there,
as on Windows, a name missed as written is not looked for any further, so
no folder is listed.
2026-11-13 16:23:47 +01:00
78 changed files with 2854 additions and 307 deletions

View File

@@ -30,7 +30,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.",
["Follow"] = "Follow the train",
["Fit"] = "Whole map",
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.",
["Unreadable"] = "Can't read {0}: {1}",
["Reading"] = "Reading {0}…",
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
@@ -185,8 +185,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["EventHornMissed"] = "W6: NO HORN",
["EventCab"] = "Cab {0} of {1}",
["EventSecurityBraking"] = "BRAKING BY {0}",
["EventSecurityAlarm"] = "{0} buzzer",
["EventSecurityAlarmAcknowledged"] = "{0} buzzer, acknowledged after {1:0.0} s",
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
["EventTimetable"] = "Timetable {0}, {1}",
["CabSpeed"] = "Speed",
["CabWheels"] = "wheels {0:0}",
["CabAiTarget"] = "AI {0:0} km/h",
["CabAcceleration"] = "Along",
["CabLateral"] = "Lateral",
@@ -305,7 +309,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
["Follow"] = "Śledź pociąg",
["Fit"] = "Cała mapa",
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.",
["Unreadable"] = "Nie można odczytać {0}: {1}",
["Reading"] = "Czytanie {0}…",
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
@@ -460,8 +464,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
["EventCab"] = "Kabina {0} w {1}",
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
["EventSecurityAlarm"] = "Brzęczyk {0}",
["EventSecurityAlarmAcknowledged"] = "Brzęczyk {0}, potwierdzony po {1:0.0} s",
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
["EventTimetable"] = "Rozkład {0}, {1}",
["CabSpeed"] = "Prędkość",
["CabWheels"] = "koła {0:0}",
["CabAiTarget"] = "AI {0:0} km/h",
["CabAcceleration"] = "Wzdłużne",
["CabLateral"] = "Boczne",
@@ -564,7 +572,11 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["FileFilter"] = "Czarna skrzynka"
};
/// <summary>The key of the text of a simulator's command: <see cref="CommandPrefix"/> and its name.</summary>
public const string CommandPrefix = "Cmd.";
private readonly Dictionary<string, string> _texts;
private readonly string _languageCode;
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
{
@@ -577,11 +589,15 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
/// <summary>Polish for "pl", English for any other language.</summary>
public DefaultBlackBoxStrings(string languageCode)
{
_languageCode = languageCode;
_texts = languageCode == "pl" ? Polish : English;
}
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
public static IEnumerable<string> Keys => English.Keys;
public string this[string key] => _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
/// <summary>A key of <see cref="CommandPrefix"/> gives what the command does (<see cref="CommandTexts"/>).</summary>
public string this[string key] =>
key.StartsWith(CommandPrefix, System.StringComparison.Ordinal) ? CommandTexts.Of(key[CommandPrefix.Length..], _languageCode)
: _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
}

View File

@@ -24,6 +24,7 @@ public sealed class CabPanel : Control
private const double LampRow = 14;
private const int DoorColumns = 2;
private const double DriveRow = 34;
private const double WheelsApartKmh = 1.0; // the wheels shown when they turn this much faster or slower
private Recording? _recording;
private double _time;
@@ -174,8 +175,19 @@ public sealed class CabPanel : Control
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
context.DrawText(speed, new Point(Pad, 24));
Say($"{kmh} km/h");
context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
var unit = MapView.Text("km/h", Palette.DimText, 12);
context.DrawText(unit, new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
double gaugeX = Pad + Math.Max(150, width * 0.42);
// the wheels, when they turn otherwise: slipping, or locked in a skid. Signed both, so wheels slipping ahead
// of a train rolling back show too. Kept off the gauges at the right, as the AI's line is.
if (s.WheelSpeedKmh is { } wheels && Math.Abs(wheels - s.SpeedKmh) >= WheelsApartKmh)
{
double wheelsX = Pad + speed.Width + 4 + unit.Width + 8;
string wheelsText = string.Format(culture, Strings["CabWheels"], Math.Abs(wheels));
using (context.PushClip(new Rect(wheelsX, 24, Math.Max(0, gaugeX - 8 - wheelsX), 40)))
context.DrawText(MapView.Text(wheelsText, Palette.Warn, 12), new Point(wheelsX, 24 + speed.Height - 21));
Say(wheelsText);
}
if (s.AiValid)
{
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
@@ -337,7 +349,7 @@ public sealed class CabPanel : Control
{
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
Say(Strings["CabGroupDoors"]);
var doors = Doors(s);
var doors = Doors(s.AsTheCabSees);
double doorColumn = width / DoorColumns;
for (int i = 0; i < doors.Length; i++)
{
@@ -660,12 +672,12 @@ public sealed class CabPanel : Control
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
{
// A recording which tells them apart.
safety.Add((Strings["DevVigilance"], Security(SecurityFlags.VigilanceBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.Vigilance, Palette.Vigilance)));
safety.Add((Strings["DevCabSignal"], Security(SecurityFlags.CabSignalBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.CabSignal, Palette.CabSignal)));
safety.Add((Strings["DevSecurityBraking"], Security(SecurityFlags.Braking, Palette.LampAlarm)));
safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance)));
safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal)));
safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null));
}
else
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));

View File

@@ -0,0 +1,378 @@
using System.Collections.Generic;
namespace Eu07.BlackBox.Views;
/// <summary>
/// What the simulator's commands of a vehicle do, as the black box names them (input/command.cpp): Polish
/// and English. Those with a key carry the texts of the key file (eu07_input-keyboard.ini) and of the starter's
/// English; the rest, worked by the mouse in the cab or by scripts, are written here.
/// </summary>
public static class CommandTexts
{
private static readonly Dictionary<string, (string Polish, string English)> Texts = new()
{
["aidriverenable"] = ("Aktywacja automechanika", "Engage the AI driver"),
["aidriverdisable"] = ("Dezaktywacja automechanika", "Disengage the AI driver"),
["jointcontrollerset"] = ("Ustawienie nastawnika zespolonego", "Set the combined controller"),
["mastercontrollerincrease"] = ("Zwiększenie nastawnika głównego", "Master controller up"),
["mastercontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika głównego", "Master controller up, fast"),
["mastercontrollerdecrease"] = ("Zmniejszenie nastawnika głównego", "Master controller down"),
["mastercontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika głównego", "Master controller down, fast"),
["mastercontrollerset"] = ("Ustawienie nastawnika głównego", "Set the master controller"),
["dynamicbrakecontrollerincrease"] = ("Zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake"),
["dynamicbrakecontrollerdecrease"] = ("Zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake"),
["dynamicbrakecontrollerset"] = ("Ustawienie hamulca elektrodynamicznego", "Set the dynamic brake"),
["dynamicbrakecontrollerincreasefast"] = ("Szybkie zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake fast"),
["dynamicbrakecontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake fast"),
["secondcontrollerincrease"] = ("Zwiększenie nastawnika boczników", "Shunt controller up"),
["secondcontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika boczników", "Shunt controller up, fast"),
["secondcontrollerdecrease"] = ("Zmniejszenie nastawnika boczników", "Shunt controller down"),
["secondcontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika boczników", "Shunt controller down, fast"),
["secondcontrollerset"] = ("Ustawienie nastawnika boczników", "Set the shunt controller"),
["mucurrentindicatorothersourceactivate"] = ("Zmiana członu dla wskaźnika prądu", "Switch the current gauge to the other unit"),
["independentbrakeincrease"] = ("Zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake"),
["independentbrakeincreasefast"] = ("Szybkie zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake, fast"),
["independentbrakedecrease"] = ("Zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake"),
["independentbrakedecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake, fast"),
["independentbrakeset"] = ("Ustawienie hamulca lokomotywy", "Set the locomotive brake"),
["independentbrakebailoff"] = ("Odluźniacz", "Bail off the locomotive brake"),
["universalbrakebutton1"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 1", "Universal brake button 1"),
["universalbrakebutton2"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 2", "Universal brake button 2"),
["universalbrakebutton3"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 3", "Universal brake button 3"),
["trainbrakeincrease"] = ("Zwiększenie stopnia hamowania zaworu maszynisty", "Train brake valve: more braking"),
["trainbrakedecrease"] = ("Zmniejszenie stopnia hamowania zaworu maszynisty", "Train brake valve: less braking"),
["trainbrakeset"] = ("Ustawienie hamulca zespolonego", "Set the train brake"),
["trainbrakecharging"] = ("Napełnianie uderzeniowe przewodu głównego", "Train brake valve: overcharge the brake pipe"),
["trainbrakerelease"] = ("Ustawienie zaworu maszynisty w pozycji jazdy", "Train brake valve: running position"),
["trainbrakefirstservice"] = ("Pozycja pierwszego stopnia hamowania", "Train brake valve: first braking step"),
["trainbrakeservice"] = ("Pozycja hamowania służbowego", "Train brake valve: service braking"),
["trainbrakefullservice"] = ("Pozycja hamowania pełnego", "Train brake valve: full service"),
["trainbrakehandleoff"] = ("Pozycja odcięcia", "Train brake valve: lap position"),
["trainbrakeemergency"] = ("Hamowanie nagłe", "Emergency braking"),
["trainbrakebasepressureincrease"] = ("Zwiększenie poziomu ciśnienia w przewodzie głównym", "Raise the brake pipe pressure level"),
["trainbrakebasepressuredecrease"] = ("Zmniejszenie poziomu ciśnienia w przewodzie głównym", "Lower the brake pipe pressure level"),
["trainbrakebasepressurereset"] = ("Domyślny poziom ciśnienia w przewodzie głównym", "Default brake pipe pressure level"),
["trainbrakeoperationtoggle"] = ("Przełączenie stanu hamulca pojazdu", "Toggle the vehicle's brake"),
["manualbrakeincrease"] = ("Zwiększenie nastawy hamulca ręcznego", "Apply more hand brake"),
["manualbrakedecrease"] = ("Zmniejszenie nastawy hamulca ręcznego", "Release hand brake"),
["alarmchaintoggle"] = ("Przełączenie stanu hamulca bezpieczeństwa", "Toggle the emergency brake"),
["alarmchainenable"] = ("Pociągnięcie hamulca bezpieczeństwa", "Pull the alarm chain"),
["alarmchaindisable"] = ("Zwolnienie hamulca bezpieczeństwa", "Release the alarm chain"),
["wheelspinbrakeactivate"] = ("Aktywacja podhamowania przeciwpoślizgowego", "Anti-slip brake"),
["sandboxactivate"] = ("Aktywacja piasecznicy", "Sander"),
["autosandboxtoggle"] = ("Przełączenie automatycznej piasecznicy", "Toggle the automatic sander"),
["autosandboxactivate"] = ("Włączenie automatycznej piasecznicy", "Turn the automatic sander on"),
["autosandboxdeactivate"] = ("Wyłączenie automatycznej piasecznicy", "Turn the automatic sander off"),
["reverserincrease"] = ("Zwiększenie pozycji nastawnika kierunku", "Reverser up"),
["reverserdecrease"] = ("Zmniejszenie pozycji nastawnika kierunku", "Reverser down"),
["reverserforwardhigh"] = ("Pozycja jazdy do przodu II nastawnika kierunku", "Reverser: forward II"),
["reverserforward"] = ("Pozycja jazdy do przodu nastawnika kierunku", "Reverser: forward"),
["reverserneutral"] = ("Pozycja neutralna nastawnika kierunku", "Reverser: neutral"),
["reverserbackward"] = ("Pozycja jazdy do tyłu nastawnika kierunku", "Reverser: backward"),
["waterpumpbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego pompy wody", "Toggle the water pump circuit breaker"),
["waterpumpbreakerclose"] = ("Załączenie wyłącznika pompy wody", "Close the water pump breaker"),
["waterpumpbreakeropen"] = ("Wyłączenie wyłącznika pompy wody", "Open the water pump breaker"),
["waterpumptoggle"] = ("Przełączenie stanu pompy wody", "Toggle the water pump"),
["waterpumpenable"] = ("Włączenie pompy wody", "Turn the water pump on"),
["waterpumpdisable"] = ("Wyłączenie pompy wody", "Turn the water pump off"),
["waterheaterbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego podgrzewacza wody", "Toggle the water heater circuit breaker"),
["waterheaterbreakerclose"] = ("Załączenie wyłącznika podgrzewacza wody", "Close the water heater breaker"),
["waterheaterbreakeropen"] = ("Wyłączenie wyłącznika podgrzewacza wody", "Open the water heater breaker"),
["waterheatertoggle"] = ("Przełączenie stanu podgrzewacza wody", "Toggle the water heater"),
["waterheaterenable"] = ("Włączenie podgrzewacza wody", "Turn the water heater on"),
["waterheaterdisable"] = ("Wyłączenie podgrzewacza wody", "Turn the water heater off"),
["watercircuitslinktoggle"] = ("Przełączenie stanu połączenia obiegów wody", "Toggle the link between the water circuits"),
["watercircuitslinkenable"] = ("Połączenie obiegów wody", "Link the water circuits"),
["watercircuitslinkdisable"] = ("Rozłączenie obiegów wody", "Unlink the water circuits"),
["fuelpumptoggle"] = ("Przełączenie stanu pompy paliwa", "Toggle the fuel pump"),
["fuelpumpenable"] = ("Włączenie pompy paliwa", "Turn the fuel pump on"),
["fuelpumpdisable"] = ("Wyłączenie pompy paliwa", "Turn the fuel pump off"),
["oilpumptoggle"] = ("Przełączenie stanu pompy oleju", "Toggle the oil pump"),
["oilpumpenable"] = ("Włączenie pompy oleju", "Turn the oil pump on"),
["oilpumpdisable"] = ("Wyłączenie pompy oleju", "Turn the oil pump off"),
["linebreakertoggle"] = ("Przełączenie stanu wyłącznika szybkiego", "Toggle the line breaker"),
["linebreakeropen"] = ("Wyłączenie wyłącznika szybkiego", "Open the line breaker"),
["linebreakerclose"] = ("Załączenie wyłącznika szybkiego", "Close the line breaker"),
["convertertoggle"] = ("Przełączenie stanu przetwornicy", "Toggle the converter"),
["converterenable"] = ("Włączenie przetwornicy", "Turn the converter on"),
["converterdisable"] = ("Wyłączenie przetwornicy", "Turn the converter off"),
["convertertogglelocal"] = ("Przełączenie stanu przetwornicy w obsadzonym członie", "Toggle the converter in the occupied unit"),
["converteroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego przetwornicy", "Reset the converter overload relay"),
["compressortoggle"] = ("Przełączenie stanu sprężarki", "Toggle the compressor"),
["compressorenable"] = ("Włączenie sprężarki", "Turn the compressor on"),
["compressordisable"] = ("Wyłączenie sprężarki", "Turn the compressor off"),
["compressortogglelocal"] = ("Przełączenie stanu sprężarki w obsadzonym członie", "Toggle the compressor in the occupied unit"),
["compressorpresetactivatenext"] = ("Następny tryb pracy sprężarek", "Next compressor mode"),
["compressorpresetactivateprevious"] = ("Poprzedni tryb pracy sprężarek", "Previous compressor mode"),
["compressorpresetactivatedefault"] = ("Domyślny tryb pracy sprężarek", "Default compressor mode"),
["motoroverloadrelaythresholdtoggle"] = ("Przełączenie rozruchu niskiego/wysokiego", "Switch between low and high starting current"),
["motoroverloadrelaythresholdsetlow"] = ("Niski próg przekaźnika nadmiarowego silników", "Motor overload relay threshold low"),
["motoroverloadrelaythresholdsethigh"] = ("Wysoki próg przekaźnika nadmiarowego silników", "Motor overload relay threshold high"),
["motoroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego silników", "Reset the traction motor overload relay"),
["universalrelayreset1"] = ("Odblokowanie zdefiniowanych przekaźników nr 1", "Reset the defined relays, set 1"),
["universalrelayreset2"] = ("Odblokowanie zdefiniowanych przekaźników nr 2", "Reset the defined relays, set 2"),
["universalrelayreset3"] = ("Odblokowanie zdefiniowanych przekaźników nr 3", "Reset the defined relays, set 3"),
["notchingrelaytoggle"] = ("Przełączenie stanu przekaźnika samoczynnego rozruchu", "Toggle the automatic notching relay"),
["epbrakecontroltoggle"] = ("Przełączenie stanu hamulca elektropneumatycznego", "Toggle the electro-pneumatic brake"),
["epbrakecontrolenable"] = ("Włączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake on"),
["epbrakecontroldisable"] = ("Wyłączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake off"),
["trainbrakeoperationmodeincrease"] = ("Zmiana trybu pracy hamulca na bardziej efektywny", "Brake operation mode: more effective"),
["trainbrakeoperationmodedecrease"] = ("Zmiana trybu pracy hamulca na prostszy", "Brake operation mode: simpler"),
["brakeactingspeedincrease"] = ("Wybór szybszego trybu działania hamulca pociągu", "Faster train brake acting speed"),
["brakeactingspeeddecrease"] = ("Wybór wolniejszego trybu działania hamulca pociągu", "Slower train brake acting speed"),
["brakeactingspeedsetcargo"] = ("Wybór trybu hamulca dla pociągu towarowego", "Brake acting speed for a freight train"),
["brakeactingspeedsetpassenger"] = ("Wybór trybu hamulca dla pociągu osobowego", "Brake acting speed for a passenger train"),
["brakeactingspeedsetrapid"] = ("Wybór trybu hamulca dla pociągu pospiesznego", "Brake acting speed for an express train"),
["brakeloadcompensationincrease"] = ("Wybór wyższego przełożenia hamulca", "Higher brake load setting"),
["brakeloadcompensationdecrease"] = ("Wybór niższego przełożenia hamulca", "Lower brake load setting"),
["mubrakingindicatortoggle"] = ("Przełączenie stanu wskaźnika hamowania członów EZT", "Toggle the EMU unit braking indicator"),
["alerteracknowledge"] = ("Wygaszenie czuwaka i SHP", "Acknowledge the vigilance device and cab signalling"),
["cabsignalacknowledge"] = ("Wygaszenie SHP", "Acknowledge the cab signalling"),
["hornlowactivate"] = ("Aktywacja syreny niskotonowej", "Low-tone horn"),
["hornhighactivate"] = ("Aktywacja syreny wysokotonowej", "High-tone horn"),
["whistleactivate"] = ("Aktywacja gwizdka", "Whistle"),
["radiotoggle"] = ("Przełączenie stanu radiotelefonu", "Toggle the radio"),
["radioenable"] = ("Włączenie radiotelefonu", "Turn the radio on"),
["radiodisable"] = ("Wyłączenie radiotelefonu", "Turn the radio off"),
["radiochannelincrease"] = ("Wybór kolejnego kanału radia", "Next radio channel"),
["radiochanneldecrease"] = ("Wybór poprzedniego kanału radia", "Previous radio channel"),
["radiochannelset"] = ("Ustawienie kanału radiotelefonu", "Set the radio channel"),
["radiostopsend"] = ("Emisja radiostopu", "Send radio-stop"),
["radiostopenable"] = ("Włączenie sygnału Radio-Stop", "Send Radio-Stop"),
["radiostopdisable"] = ("Wyłączenie sygnału Radio-Stop", "Stop sending Radio-Stop"),
["radiostoptest"] = ("Lokalny test radiostopu", "Local radio-stop test"),
["radiocall1send"] = ("Wywołanie radiowe 1", "Radio call 1"),
["radiocall3send"] = ("Emisja sygnału zew3", "Send the call-3 signal"),
["radiovolumeincrease"] = ("Zwiększenie głośności radia", "Radio volume up"),
["radiovolumedecrease"] = ("Zmniejszenie głośności radia", "Radio volume down"),
["radiovolumeset"] = ("Ustawienie głośności radiotelefonu", "Set the radio volume"),
["radiofusetoggle"] = ("Przełączenie bezpiecznika radiotelefonu", "Toggle the radio fuse"),
["radiofuseenable"] = ("Załączenie bezpiecznika radiotelefonu", "Close the radio fuse"),
["radiofusedisable"] = ("Wyłączenie bezpiecznika radiotelefonu", "Open the radio fuse"),
["cabchangeforward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku czoła pociągu", "Move to the next compartment towards the front"),
["cabchangebackward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku tyłu pociągu", "Move to the next compartment towards the rear"),
["modernlightdimmerdecrease"] = ("Przyciemnienie oświetlenia", "Dim the lights"),
["modernlightdimmerincrease"] = ("Rozjaśnienie oświetlenia", "Brighten the lights"),
["nearestcarcouplingincrease"] = ("Łączenie sprzęgów", "Couple"),
["nearestcarcouplingdisconnect"] = ("Rozłączenie sprzęgów", "Uncouple"),
["nearestcarcoupleradapterattach"] = ("Nałożenie półsprzęgu", "Attach the coupler adapter"),
["nearestcarcoupleradapterremove"] = ("Demontaż półsprzęgu", "Remove the coupler adapter"),
["occupiedcarcouplingdisconnect"] = ("Rozłączenie sprzęgów po stronie obsadzonej kabiny", "Uncouple at the occupied cab's end"),
["occupiedcarcouplingdisconnectback"] = ("Rozłączenie sprzęgu z tyłu zajmowanego pojazdu", "Uncouple at the back of the occupied car"),
["doortoggleleft"] = ("Przełączenie stanu drzwi lewych", "Toggle the left doors"),
["doortoggleright"] = ("Przełączenie stanu drzwi prawych", "Toggle the right doors"),
["doorpermitleft"] = ("Zezwolenie na otwarcie drzwi lewych", "Permit opening the left doors"),
["doorpermitright"] = ("Zezwolenie na otwarcie drzwi prawych", "Permit opening the right doors"),
["doorpermitpresetactivatenext"] = ("Aktywacja kolejnej konfiguracji zezwolenia na otwarcie drzwi", "Next door permit preset"),
["doorpermitpresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji zezwolenia na otwarcie drzwi", "Previous door permit preset"),
["dooropenleft"] = ("Otwarcie drzwi z lewej", "Open the left doors"),
["dooropenright"] = ("Otwarcie drzwi z prawej", "Open the right doors"),
["dooropenall"] = ("Otwarcie drzwi z zezwoleniem", "Open the permitted doors"),
["doorcloseleft"] = ("Zamknięcie drzwi lewych", "Close the left doors"),
["doorcloseright"] = ("Zamknięcie drzwi prawych", "Close the right doors"),
["doorcloseall"] = ("Zamknięcie wszystkich drzwi", "Close all doors"),
["doorsteptoggle"] = ("Przełączenie stanu stopnia drzwi", "Toggle the door steps"),
["doormodetoggle"] = ("Przełączenie trybu działania drzwi", "Toggle the door operation mode"),
["mirrorstoggle"] = ("Złożenie lub rozłożenie lusterek", "Fold or unfold the mirrors"),
["departureannounce"] = ("Sygnał odjazdu", "Departure signal"),
["doorlocktoggle"] = ("Przełączenie stanu blokady drzwi", "Toggle the door lock"),
["pantographcompressorvalvetoggle"] = ("Przełączenie stanu kurka trójdrogowego", "Toggle the three-way pantograph valve"),
["pantographcompressorvalveenable"] = ("Otwarcie zaworu sprężarki pantografów", "Open the pantograph compressor valve"),
["pantographcompressorvalvedisable"] = ("Zamknięcie zaworu sprężarki pantografów", "Close the pantograph compressor valve"),
["pantographcompressoractivate"] = ("Aktywacja sprężarki pomocniczej", "Auxiliary pantograph compressor"),
["pantographtogglefront"] = ("Przełączenie stanu pantografu przedniego", "Toggle the front pantograph"),
["pantographtogglerear"] = ("Przełączenie stanu pantografu tylnego", "Toggle the rear pantograph"),
["pantographraisefront"] = ("Podniesienie przedniego pantografu", "Raise the front pantograph"),
["pantographraiserear"] = ("Podniesienie tylnego pantografu", "Raise the rear pantograph"),
["pantographlowerfront"] = ("Opuszczenie przedniego pantografu", "Lower the front pantograph"),
["pantographlowerrear"] = ("Opuszczenie tylnego pantografu", "Lower the rear pantograph"),
["pantographlowerall"] = ("Opuszczenie wszystkich pantografów", "Lower all pantographs"),
["pantographselectnext"] = ("Aktywacja kolejnej konfiguracji wyboru pantografów", "Next pantograph selection preset"),
["pantographselectprevious"] = ("Aktywacja poprzedniej konfiguracji wyboru pantografów", "Previous pantograph selection preset"),
["pantographtoggleselected"] = ("Przełączenie stanu wybranych pantografów", "Toggle the selected pantographs"),
["pantographraiseselected"] = ("Podniesienie wybranych pantografów", "Raise the selected pantographs"),
["pantographlowerselected"] = ("Opuszczenie wybranych pantografów", "Lower the selected pantographs"),
["pantographvalvesupdate"] = ("Ustawienie zaworów pantografów", "Set the pantograph valves"),
["pantographvalvesoff"] = ("Zamknięcie zaworów pantografów", "Close the pantograph valves"),
["heatingtoggle"] = ("Przełączenie stanu ogrzewania pociągu", "Toggle train heating"),
["heatingenable"] = ("Włączenie ogrzewania pociągu", "Turn the train heating on"),
["heatingdisable"] = ("Wyłączenie ogrzewania pociągu", "Turn the train heating off"),
["lightspresetactivatenext"] = ("Aktywacja kolejnej konfiguracji reflektorów", "Next headlight preset"),
["lightspresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji reflektorów", "Previous headlight preset"),
["headlighttoggleleft"] = ("Przełączenie stanu lewego reflektora", "Toggle the left headlight"),
["headlightenableleft"] = ("Włączenie lewego reflektora z przodu", "Turn the front left headlight on"),
["headlightdisableleft"] = ("Wyłączenie lewego reflektora z przodu", "Turn the front left headlight off"),
["headlighttoggleright"] = ("Przełączenie stanu prawego reflektora", "Toggle the right headlight"),
["headlightenableright"] = ("Włączenie prawego reflektora z przodu", "Turn the front right headlight on"),
["headlightdisableright"] = ("Wyłączenie prawego reflektora z przodu", "Turn the front right headlight off"),
["headlighttoggleupper"] = ("Przełączenie stanu górnego reflektora", "Toggle the upper headlight"),
["headlightenableupper"] = ("Włączenie górnego reflektora z przodu", "Turn the front upper headlight on"),
["headlightdisableupper"] = ("Wyłączenie górnego reflektora z przodu", "Turn the front upper headlight off"),
["redmarkertoggleleft"] = ("Przełączenie lewego światła czerwonego", "Toggle the left red marker"),
["redmarkerenableleft"] = ("Włączenie lewego sygnału końcowego z przodu", "Turn the front left red marker on"),
["redmarkerdisableleft"] = ("Wyłączenie lewego sygnału końcowego z przodu", "Turn the front left red marker off"),
["redmarkertoggleright"] = ("Przełączenie prawego światła czerwonego", "Toggle the right red marker"),
["redmarkerenableright"] = ("Włączenie prawego sygnału końcowego z przodu", "Turn the front right red marker on"),
["redmarkerdisableright"] = ("Wyłączenie prawego sygnału końcowego z przodu", "Turn the front right red marker off"),
["headlighttogglerearleft"] = ("Przełączenie stanu lewego tylnego reflektora", "Toggle the rear left headlight"),
["headlightenablerearleft"] = ("Włączenie lewego reflektora z tyłu", "Turn the rear left headlight on"),
["headlightdisablerearleft"] = ("Wyłączenie lewego reflektora z tyłu", "Turn the rear left headlight off"),
["headlighttogglerearright"] = ("Przełączenie stanu prawego tylnego reflektora", "Toggle the rear right headlight"),
["headlightenablerearright"] = ("Włączenie prawego reflektora z tyłu", "Turn the rear right headlight on"),
["headlightdisablerearright"] = ("Wyłączenie prawego reflektora z tyłu", "Turn the rear right headlight off"),
["headlighttogglerearupper"] = ("Przełączenie stanu górnego tylnego reflektora", "Toggle the rear upper headlight"),
["headlightenablerearupper"] = ("Włączenie górnego reflektora z tyłu", "Turn the rear upper headlight on"),
["headlightdisablerearupper"] = ("Wyłączenie górnego reflektora z tyłu", "Turn the rear upper headlight off"),
["redmarkertogglerearleft"] = ("Przełączenie lewego tylnego światła czerwonego", "Toggle the rear left red marker"),
["redmarkerenablerearleft"] = ("Włączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker on"),
["redmarkerdisablerearleft"] = ("Wyłączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker off"),
["redmarkertogglerearright"] = ("Przełączenie prawego tylnego światła czerwonego", "Toggle the rear right red marker"),
["redmarkerenablerearright"] = ("Włączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker on"),
["redmarkerdisablerearright"] = ("Wyłączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker off"),
["redmarkerstoggle"] = ("Przełączenie świateł końca pociągu", "Toggle the end-of-train lights"),
["endsignalstoggle"] = ("Przełączenie tabliczek końca pociągu", "Toggle the end-of-train plates"),
["headlightsdimtoggle"] = ("Przełączenie przyciemnienia reflektorów", "Toggle headlight dimming"),
["headlightsdimenable"] = ("Przyciemnienie reflektorów", "Dim the headlights"),
["headlightsdimdisable"] = ("Pełne światło reflektorów", "Headlights at full"),
["motorconnectorsopen"] = ("Rozłączenie styczników liniowych", "Open the line contactors"),
["motorconnectorsclose"] = ("Załączenie styczników liniowych", "Close the line contactors"),
["motordisconnect"] = ("Odłączenie uszkodzonych silników", "Cut out the damaged motors"),
["interiorlighttoggle"] = ("Przełączenie stanu oświetlenia kabiny", "Toggle the cab light"),
["interiorlightenable"] = ("Włączenie oświetlenia kabiny", "Turn the cab light on"),
["interiorlightdisable"] = ("Wyłączenie oświetlenia kabiny", "Turn the cab light off"),
["interiorlightdimtoggle"] = ("Przełączenie przyciemnienia oświetlenia kabiny", "Toggle cab light dimming"),
["interiorlightdimenable"] = ("Przyciemnienie oświetlenia kabiny", "Dim the cab light"),
["interiorlightdimdisable"] = ("Pełne oświetlenie kabiny", "Cab light at full"),
["compartmentlightstoggle"] = ("Przełączenie stanu oświetlenia przedziałów", "Toggle the compartment lights"),
["compartmentlightsenable"] = ("Włączenie oświetlenia przedziałów", "Turn the compartment lights on"),
["compartmentlightsdisable"] = ("Wyłączenie oświetlenia przedziałów", "Turn the compartment lights off"),
["instrumentlighttoggle"] = ("Przełączenie stanu oświetlenia przyrządów", "Toggle the instrument lights"),
["instrumentlightenable"] = ("Włączenie oświetlenia przyrządów", "Turn the instrument lights on"),
["instrumentlightdisable"] = ("Wyłączenie oświetlenia przyrządów", "Turn the instrument lights off"),
["dashboardlighttoggle"] = ("Przełączenie stanu oświetlenia pulpitu", "Toggle the dashboard light"),
["dashboardlightenable"] = ("Włączenie oświetlenia pulpitu", "Turn the dashboard light on"),
["dashboardlightdisable"] = ("Wyłączenie oświetlenia pulpitu", "Turn the dashboard light off"),
["timetablelighttoggle"] = ("Przełączenie stanu oświetlenia rozkładu jazdy", "Toggle the timetable light"),
["timetablelightenable"] = ("Włączenie oświetlenia rozkładu jazdy", "Turn the timetable light on"),
["timetablelightdisable"] = ("Wyłączenie oświetlenia rozkładu jazdy", "Turn the timetable light off"),
["generictoggle0"] = ("Przełączenie elementu uniwersalnego nr 0", "Generic switch 0"),
["generictoggle1"] = ("Przełączenie elementu uniwersalnego nr 1", "Generic switch 1"),
["generictoggle2"] = ("Przełączenie elementu uniwersalnego nr 2", "Generic switch 2"),
["generictoggle3"] = ("Przełączenie elementu uniwersalnego nr 3", "Generic switch 3"),
["generictoggle4"] = ("Przełączenie elementu uniwersalnego nr 4", "Generic switch 4"),
["generictoggle5"] = ("Przełączenie elementu uniwersalnego nr 5", "Generic switch 5"),
["generictoggle6"] = ("Przełączenie elementu uniwersalnego nr 6", "Generic switch 6"),
["generictoggle7"] = ("Przełączenie elementu uniwersalnego nr 7", "Generic switch 7"),
["generictoggle8"] = ("Przełączenie elementu uniwersalnego nr 8", "Generic switch 8"),
["generictoggle9"] = ("Przełączenie elementu uniwersalnego nr 9", "Generic switch 9"),
["generictoggle10"] = ("Przełączenie elementu uniwersalnego nr 10", "Generic switch 10"),
["generictoggle11"] = ("Przełączenie elementu uniwersalnego nr 11", "Generic switch 11"),
["generictoggle12"] = ("Przełączenie elementu uniwersalnego nr 12", "Generic switch 12"),
["generictoggle13"] = ("Przełączenie elementu uniwersalnego nr 13", "Generic switch 13"),
["generictoggle14"] = ("Przełączenie elementu uniwersalnego nr 14", "Generic switch 14"),
["generictoggle15"] = ("Przełączenie elementu uniwersalnego nr 15", "Generic switch 15"),
["generictoggle16"] = ("Przełączenie elementu uniwersalnego nr 16", "Generic switch 16"),
["generictoggle17"] = ("Przełączenie elementu uniwersalnego nr 17", "Generic switch 17"),
["generictoggle18"] = ("Przełączenie elementu uniwersalnego nr 18", "Generic switch 18"),
["generictoggle19"] = ("Przełączenie elementu uniwersalnego nr 19", "Generic switch 19"),
["generictoggle20"] = ("Przełączenie elementu uniwersalnego nr 20", "Generic switch 20"),
["generictoggle21"] = ("Przełączenie elementu uniwersalnego nr 21", "Generic switch 21"),
["generictoggle22"] = ("Przełączenie elementu uniwersalnego nr 22", "Generic switch 22"),
["generictoggle23"] = ("Przełączenie elementu uniwersalnego nr 23", "Generic switch 23"),
["generictoggle24"] = ("Przełączenie elementu uniwersalnego nr 24", "Generic switch 24"),
["generictoggle25"] = ("Przełączenie elementu uniwersalnego nr 25", "Generic switch 25"),
["generictoggle26"] = ("Przełączenie elementu uniwersalnego nr 26", "Generic switch 26"),
["generictoggle27"] = ("Przełączenie elementu uniwersalnego nr 27", "Generic switch 27"),
["generictoggle28"] = ("Przełączenie elementu uniwersalnego nr 28", "Generic switch 28"),
["generictoggle29"] = ("Przełączenie elementu uniwersalnego nr 29", "Generic switch 29"),
["batterytoggle"] = ("Przełączenie stanu akumulatorów", "Toggle the batteries"),
["batteryenable"] = ("Włączenie baterii", "Turn the battery on"),
["batterydisable"] = ("Wyłączenie baterii", "Turn the battery off"),
["cabactivationtoggle"] = ("Przełączenie stanu aktywacji kabiny", "Toggle cab activation"),
["cabactivationenable"] = ("Aktywacja kabiny", "Activate the cab"),
["cabactivationdisable"] = ("Dezaktywacja kabiny", "Deactivate the cab"),
["motorblowerstogglefront"] = ("Przełączenie stanu wentylatorów przednich silników trakcyjnych", "Toggle the front traction motor blowers"),
["motorblowerstogglerear"] = ("Przełączenie stanu wentylatorów tylnych silników trakcyjnych", "Toggle the rear traction motor blowers"),
["motorblowersdisableall"] = ("Wyłączenie wszystkich wentylatorów silników trakcyjnych", "Switch off all traction motor blowers"),
["coolingfanstoggle"] = ("Przełączenie stanu wentylatorów oporów rozruchowych", "Toggle the starting resistor fans"),
["tempomattoggle"] = ("Przełączenie stanu tempomatu", "Toggle the cruise control"),
["springbraketoggle"] = ("Przełączenie stanu hamulca sprężynowego", "Toggle the spring brake"),
["springbrakeenable"] = ("Załączenie hamulca sprężynowego", "Apply the spring brake"),
["springbrakedisable"] = ("Zwolnienie hamulca sprężynowego", "Release the spring brake"),
["springbrakeshutofftoggle"] = ("Przełączenie stanu kurka odcinającego hamulca sprężynowego", "Toggle the spring brake shut-off cock"),
["springbrakeshutoffenable"] = ("Odcięcie hamulca sprężynowego", "Cut the spring brake off"),
["springbrakeshutoffdisable"] = ("Przywrócenie hamulca sprężynowego", "Cut the spring brake back in"),
["springbrakerelease"] = ("Luzowanie hamulca sprężynowego", "Release the spring brake"),
["distancecounteractivate"] = ("Załączenie miernika przejechanego dystansu", "Start the distance counter"),
["speedcontrolincrease"] = ("Zwiększenie prędkości utrzymywanej przez tempomat", "Cruise control speed up"),
["speedcontroldecrease"] = ("Zmniejszenie prędkości utrzymywanej przez tempomat", "Cruise control speed down"),
["speedcontrolpowerincrease"] = ("Zwiększenie maksymalnego poziomu mocy dostępnej dla tempomatu", "More power for the cruise control"),
["speedcontrolpowerdecrease"] = ("Zmniejszenie maksymalnego poziomu mocy dostępnej dla tempomatu", "Less power for the cruise control"),
["speedcontrolbutton0"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 0", "Cruise control preset speed 0"),
["speedcontrolbutton1"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 1", "Cruise control preset speed 1"),
["speedcontrolbutton2"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 2", "Cruise control preset speed 2"),
["speedcontrolbutton3"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 3", "Cruise control preset speed 3"),
["speedcontrolbutton4"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 4", "Cruise control preset speed 4"),
["speedcontrolbutton5"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 5", "Cruise control preset speed 5"),
["speedcontrolbutton6"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 6", "Cruise control preset speed 6"),
["speedcontrolbutton7"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 7", "Cruise control preset speed 7"),
["speedcontrolbutton8"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 8", "Cruise control preset speed 8"),
["speedcontrolbutton9"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 9", "Cruise control preset speed 9"),
["inverterenable1"] = ("Włączenie falownika 1", "Turn inverter 1 on"),
["inverterenable2"] = ("Włączenie falownika 2", "Turn inverter 2 on"),
["inverterenable3"] = ("Włączenie falownika 3", "Turn inverter 3 on"),
["inverterenable4"] = ("Włączenie falownika 4", "Turn inverter 4 on"),
["inverterenable5"] = ("Włączenie falownika 5", "Turn inverter 5 on"),
["inverterenable6"] = ("Włączenie falownika 6", "Turn inverter 6 on"),
["inverterenable7"] = ("Włączenie falownika 7", "Turn inverter 7 on"),
["inverterenable8"] = ("Włączenie falownika 8", "Turn inverter 8 on"),
["inverterenable9"] = ("Włączenie falownika 9", "Turn inverter 9 on"),
["inverterenable10"] = ("Włączenie falownika 10", "Turn inverter 10 on"),
["inverterenable11"] = ("Włączenie falownika 11", "Turn inverter 11 on"),
["inverterenable12"] = ("Włączenie falownika 12", "Turn inverter 12 on"),
["inverterdisable1"] = ("Wyłączenie falownika 1", "Turn inverter 1 off"),
["inverterdisable2"] = ("Wyłączenie falownika 2", "Turn inverter 2 off"),
["inverterdisable3"] = ("Wyłączenie falownika 3", "Turn inverter 3 off"),
["inverterdisable4"] = ("Wyłączenie falownika 4", "Turn inverter 4 off"),
["inverterdisable5"] = ("Wyłączenie falownika 5", "Turn inverter 5 off"),
["inverterdisable6"] = ("Wyłączenie falownika 6", "Turn inverter 6 off"),
["inverterdisable7"] = ("Wyłączenie falownika 7", "Turn inverter 7 off"),
["inverterdisable8"] = ("Wyłączenie falownika 8", "Turn inverter 8 off"),
["inverterdisable9"] = ("Wyłączenie falownika 9", "Turn inverter 9 off"),
["inverterdisable10"] = ("Wyłączenie falownika 10", "Turn inverter 10 off"),
["inverterdisable11"] = ("Wyłączenie falownika 11", "Turn inverter 11 off"),
["inverterdisable12"] = ("Wyłączenie falownika 12", "Turn inverter 12 off"),
["invertertoggle1"] = ("Przełączenie falownika 1", "Toggle inverter 1"),
["invertertoggle2"] = ("Przełączenie falownika 2", "Toggle inverter 2"),
["invertertoggle3"] = ("Przełączenie falownika 3", "Toggle inverter 3"),
["invertertoggle4"] = ("Przełączenie falownika 4", "Toggle inverter 4"),
["invertertoggle5"] = ("Przełączenie falownika 5", "Toggle inverter 5"),
["invertertoggle6"] = ("Przełączenie falownika 6", "Toggle inverter 6"),
["invertertoggle7"] = ("Przełączenie falownika 7", "Toggle inverter 7"),
["invertertoggle8"] = ("Przełączenie falownika 8", "Toggle inverter 8"),
["invertertoggle9"] = ("Przełączenie falownika 9", "Toggle inverter 9"),
["invertertoggle10"] = ("Przełączenie falownika 10", "Toggle inverter 10"),
["invertertoggle11"] = ("Przełączenie falownika 11", "Toggle inverter 11"),
["invertertoggle12"] = ("Przełączenie falownika 12", "Toggle inverter 12"),
["vehiclemoveforwards"] = ("Przesunięcie pojazdu do przodu", "Move the vehicle forwards"),
["vehiclemovebackwards"] = ("Przesunięcie pojazdu do tyłu", "Move the vehicle backwards"),
["vehicleboost"] = ("Przyspieszenie pojazdu", "Boost the vehicle"),
["wiperswitchincrease"] = ("Szybsza praca wycieraczek", "Wipers faster"),
["wiperswitchdecrease"] = ("Wolniejsza praca wycieraczek", "Wipers slower"),
["lightsset"] = ("Ustawienie świateł", "Set the lights"),
["oilfuelpumptoggle"] = ("Przełączenie pomp oleju i paliwa", "Toggle the oil and fuel pumps"),
["linebreakertoggleb"] = ("Przełączenie wyłącznika szybkiego B", "Toggle line breaker B"),
["linebreakeropenb"] = ("Wyłączenie wyłącznika szybkiego B", "Open line breaker B"),
["linebreakercloseb"] = ("Załączenie wyłącznika szybkiego B", "Close line breaker B"),
["linebreakertogglec"] = ("Przełączenie wyłącznika szybkiego C", "Toggle line breaker C"),
["linebreakeropenc"] = ("Wyłączenie wyłącznika szybkiego C", "Open line breaker C"),
["linebreakerclosec"] = ("Załączenie wyłącznika szybkiego C", "Close line breaker C"),
};
/// <summary>The text of <paramref name="command"/>, Polish for "pl", else English; its name when unknown.</summary>
public static string Of(string command, string languageCode) =>
Texts.TryGetValue(command, out var text) ? languageCode == "pl" ? text.Polish : text.English : command;
/// <summary>The commands there are texts for.</summary>
public static IEnumerable<string> Commands => Texts.Keys;
}

View File

@@ -155,7 +155,9 @@ public sealed class EventList : ListBox
var culture = CultureInfo.CurrentCulture;
var events = new List<BlackBoxEvent>();
foreach (var c in recording.UserCommands())
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], c.Name), Palette.Command, false));
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"],
strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]),
Palette.Command, false));
foreach (var d in recording.DriverChanges)
{
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
@@ -176,14 +178,7 @@ public sealed class EventList : ListBox
foreach (var horn in recording.UserHornChecks())
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
foreach (var span in recording.SecurityBrakings())
{
// Which of them was not acknowledged: the lamps blinking when it braked.
string who = recording.CabAt(span.Start) is { } s
? s.Has(SecurityFlags.CabSignal) && s.Has(SecurityFlags.Vigilance) ? "CA/SHP" : s.Has(SecurityFlags.CabSignal) ? "SHP" : "CA"
: "CA";
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"], who), Palette.Bad, true));
}
AddSecurity(recording, strings, events, culture);
AddCameras(recording, strings, events, culture);
AddCouplings(recording, strings, events, culture);
AddCabChanges(recording, strings, events, culture);
@@ -196,6 +191,45 @@ public sealed class EventList : ListBox
return events.OrderBy(e => e.Time).ToList();
}
/// <summary>
/// The train protection: its buzzer, acknowledged or not, and the braking apart. A lamp acknowledged before the
/// buzzer is the driving as usual, not told.
/// </summary>
private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
var brakings = recording.SecurityBrakings();
foreach (var span in recording.SecurityAlarms())
{
// The lamps of all its buzzing samples: one buzzer for both, the other may join it before it's acknowledged.
var lamps = recording.Cab.Where(c => c.Time >= span.Start && c.Time <= span.End && (c.VigilanceBuzzer || c.CabSignalBuzzer))
.Aggregate(SecurityFlags.None, (all, c) => all | c.Security);
string who = ProtectionName(lamps);
var before = recording.CabAt(span.Start);
string text = brakings.Any(b => b.Start >= span.Start && b.Start <= span.End)
? string.Format(culture, strings["EventSecurityAlarmMissed"], who)
// Acknowledged when the sample it ended at buzzes no more and doesn't brake, in the same vehicle: not
// the end of the recording or a gap in it, nor the power cut or the protection switched off.
: recording.CabAt(span.End) is { } after && !after.VigilanceBuzzer && !after.CabSignalBuzzer
&& !after.Has(SecurityFlags.Braking) && after.Vehicle == before?.Vehicle
? string.Format(culture, strings["EventSecurityAlarmAcknowledged"], who, span.End - span.Start)
: string.Format(culture, strings["EventSecurityAlarm"], who);
events.Add(new BlackBoxEvent(span.Start, text, Palette.Buzzer, false));
}
foreach (var span in brakings)
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"],
ProtectionName(recording.CabAt(span.Start)?.Security ?? SecurityFlags.None)),
Palette.Bad, true));
}
/// <summary>Which of them it was: the lamps blinking.</summary>
private static string ProtectionName(SecurityFlags lamps) =>
(lamps & (SecurityFlags.CabSignal | SecurityFlags.Vigilance)) switch
{
SecurityFlags.CabSignal | SecurityFlags.Vigilance => "CA/SHP",
SecurityFlags.CabSignal => "SHP",
_ => "CA"
};
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
UserVehicleChange? before = null;
@@ -282,6 +316,8 @@ public sealed class EventList : ListBox
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
];
private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight;
/// <summary>
/// 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 +327,8 @@ public sealed class EventList : ListBox
{
CabSample? last = null;
bool movingOpen = false;
foreach (var s in recording.Cab)
// the doors' sides as the driver has them, from the cab the driver is in (CabSample.AsTheCabSees)
foreach (var s in recording.Cab.Select(sample => sample.AsTheCabSees))
{
if (last is not { } b || b.Vehicle != s.Vehicle)
{
@@ -299,8 +336,10 @@ public sealed class EventList : ListBox
movingOpen = false;
continue;
}
bool Came(CabDevices device) => !b.Has(device) && s.Has(device);
bool Went(CabDevices device) => b.Has(device) && !s.Has(device);
// the other end swaps the sides, and tells nothing of the doors; no cab (0) sees them as the front one does
bool sameCab = (b.CabEnd < 0) == (s.CabEnd < 0);
bool Came(CabDevices device) => !b.Has(device) && s.Has(device) && (sameCab || (device & DoorSides) == 0);
bool Went(CabDevices device) => b.Has(device) && !s.Has(device) && (sameCab || (device & DoorSides) == 0);
foreach (var (device, key) in Switched)
{
if (Came(device))

View File

@@ -81,6 +81,8 @@ public static class Palette
public static readonly IBrush LampOn = Brush("#4cc46e");
public static readonly IBrush LampWarning = Brush("#e8c547");
public static readonly IBrush LampAlarm = Brush("#f0584a");
/// <summary>The train protection's buzzer: still to be acknowledged, not braking yet.</summary>
public static readonly IBrush Buzzer = Brush("#c77dff");
public static readonly IBrush LightWhite = Brush("#fff6d8");
public static readonly IBrush LightRed = Brush("#ff3b30");
public static readonly IBrush Command = Brush("#8b96a3");

View File

@@ -309,16 +309,16 @@ public sealed class TimelineView : Control
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
{
// The alerter and the cab signalling apart, red when not acknowledged in time.
rows[3].Add(x0, x1, s.Has(SecurityFlags.VigilanceBeeping) ? Palette.LampAlarm
// The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked.
rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
rows[4].Add(x0, x1, s.Has(SecurityFlags.CabSignalBeeping) ? Palette.LampAlarm
rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
if (s.Has(SecurityFlags.Braking))
if (s.ProtectionBraking)
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
}
else
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
// Where the user looked from: the samples go on in time, and so does the camera.
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
@@ -590,7 +590,8 @@ public sealed class TimelineView : Control
foreach (var d in recording.DriverChanges)
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
foreach (var c in recording.UserCommands())
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], c.Name));
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"],
Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]));
}
return found;
}

View File

@@ -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;
}

View File

@@ -520,7 +520,13 @@ public sealed class Recording
}
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.Has(SecurityFlags.Braking));
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.ProtectionBraking);
/// <summary>
/// When the train protection's buzzer sounded in the user's cab: a lamp not acknowledged in time, the braking to
/// follow unless acknowledged on. Until it ends, braking included.
/// </summary>
public IReadOnlyList<TimeSpanRange> SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer);
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);

View File

@@ -366,11 +366,50 @@ 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;
/// <summary>
/// The alerter's buzzer: its lamp not acknowledged in time. A protection with one acknowledgement for both tells
/// the cab signalling's buzzer as the alerter's too, so the alerter's lamp has to blink with it.
/// </summary>
public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance);
/// <summary>The cab signalling's buzzer: its lamp not acknowledged in time.</summary>
public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping);
/// <summary>
/// The train protection braking for an alarm not acknowledged, its lamp blinking. Braking with no lamp is the
/// protection with no power (TSecuritySystem::is_braking), a cab not started or a power cut: no driver's fault.
/// </summary>
public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal));
private const CabDevices LeftDoors = CabDevices.DoorsLeft | CabDevices.DoorPermitLeft;
private const CabDevices RightDoors = CabDevices.DoorsRight | CabDevices.DoorPermitRight;
/// <summary>
/// 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.
/// </summary>
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);

View File

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

View File

@@ -60,13 +60,15 @@ public class BlackBoxListingTests
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
{
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
// named in the local time they started at, whatever the zone the tests run in
string first = Box("td", early.AddHours(-1)), second = Box("td", early.AddMinutes(30));
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("a.dat"), "t")
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
.WithFile(Log(first), "b")
.WithFile(Log(second), "b")
.WrittenAt(Log("a.dat"), early)
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
.WrittenAt(Log(first), early.AddSeconds(2))
.WrittenAt(Log(second), early.AddHours(1)));
var sessions = installation.Tapes.Sessions();
@@ -74,12 +76,59 @@ public class BlackBoxListingTests
Assert.All(sessions, session => Assert.Null(session.Launch));
// Newest first: the black box on its own, then the run with the tape.
Assert.Empty(sessions[0].Tapes);
Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path);
Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path);
Assert.Single(sessions[1].Tapes);
Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path);
Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path);
Assert.Equal(early, sessions[1].StartedUtc);
}
[Fact]
public void The_tape_of_a_vehicle_left_early_in_a_run_with_no_launch_goes_with_its_black_box()
{
// The black box writes the tapes as it goes: that of the vehicle the player left after ten minutes ends
// twenty minutes before the run, that of the next one with it.
var started = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
string box = Box("td", started);
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("first.dat"), "t")
.WithFile(Log("second.dat"), "t")
.WithFile(Log(box), "b")
.WrittenAt(Log("first.dat"), started.AddMinutes(10))
.WrittenAt(Log(box), started.AddMinutes(30))
.WrittenAt(Log("second.dat"), started.AddMinutes(30).AddSeconds(1)));
var session = Assert.Single(installation.Tapes.Sessions());
Assert.Null(session.Launch);
Assert.Equal(new[] { "first", "second" }, session.Tapes.Select(tape => tape.Vehicle).Order());
Assert.EndsWith(box, Assert.Single(session.BlackBoxes).Path);
}
[Fact]
public void A_black_box_downloaded_later_takes_in_no_tapes_of_the_runs_after_it()
{
// Shared and downloaded two weeks later, so last written then; a run of its own with no launch noted since.
var shared = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
var later = shared.AddDays(7);
string old = Box("td", shared), own = Box("td", later);
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log(old), "b").WrittenAt(Log(old), shared.AddDays(14))
.WithFile(Log(own), "b").WrittenAt(Log(own), later.AddMinutes(30))
.WithFile(Log("ra.dat"), "t").WrittenAt(Log("ra.dat"), later.AddMinutes(30).AddSeconds(1))
.WithFile(Log("left.dat"), "t").WrittenAt(Log("left.dat"), later.AddMinutes(10)));
var recordings = StarterNG.Application.HaslerTapes.Recordings(new[]
{
new StarterNG.Application.BlackBoxRecording(Log(old), shared.AddDays(14), 1),
new StarterNG.Application.BlackBoxRecording(Log(own), later.AddMinutes(30), 1),
});
Assert.EndsWith(own, StarterNG.Application.HaslerTapes.RecordingAt(later.AddMinutes(10), recordings)!.Path);
var mine = Assert.Single(installation.Tapes.Sessions(), session => session.Tapes.Count > 0);
Assert.Equal(new[] { "left", "ra" }, mine.Tapes.Select(tape => tape.Vehicle).Order());
Assert.EndsWith(own, Assert.Single(mine.BlackBoxes).Path);
}
[Fact]
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
{

View File

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

View File

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

View File

@@ -0,0 +1,43 @@
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
public class EventTextsTests
{
[Theory]
[InlineData("pl", "aidriverenable", "Aktywacja automechanika")]
[InlineData("en", "aidriverenable", "Engage the AI driver")]
[InlineData("pl", "mastercontrollerset", "Ustawienie nastawnika głównego")]
[InlineData("pl", "headlightenablerearleft", "Włączenie lewego reflektora z tyłu")]
[InlineData("cz", "batteryenable", "Turn the battery on")]
public void A_command_is_told_by_what_it_does(string language, string command, string text) =>
Assert.Equal(text, new DefaultBlackBoxStrings(language)[DefaultBlackBoxStrings.CommandPrefix + command]);
[Fact]
public void A_command_with_no_text_keeps_its_name() =>
Assert.Equal("somethingnew", new DefaultBlackBoxStrings("pl")[DefaultBlackBoxStrings.CommandPrefix + "somethingnew"]);
[Fact]
public void Every_command_has_both_texts_starting_with_a_capital()
{
foreach (string command in CommandTexts.Commands)
foreach (string language in new[] { "pl", "en" })
{
string text = CommandTexts.Of(command, language);
Assert.NotEqual(command, text);
Assert.True(char.IsUpper(text[0]), $"{command} ({language}): {text}");
}
}
[Fact]
public void The_events_name_the_commands_by_what_they_do()
{
var recording = BlackBoxReader.Read(new BlackBoxFile().Info()
.Vehicle(1, "EP07-424").User(0, 1, true).Command(12.0, 1, true, "batteryenable").Stream());
var events = EventList.Collect(recording, new DefaultBlackBoxStrings("pl"));
Assert.Contains(events, e => e.Text == "Włączenie baterii");
}
}

View File

@@ -0,0 +1,88 @@
using System.Globalization;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
public class SecurityBrakingTests
{
// as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too
private const byte CabSignal = 0x02, CabSignalBuzzing = 0x0e, CabSignalBraking = 0x1e, NoPower = 0x10;
private static Recording Drive(System.Func<double, byte> security)
{
var file = new BlackBoxFile().Info().Vehicle(1, "EP07-424").User(0, 1, true);
for (double t = 0; t <= 20; t += 0.5)
file.Cab(t, 1, 100, 0, security: security(t));
return BlackBoxReader.Read(file.Stream());
}
private static List<string> Events(Recording recording)
{
var culture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
try
{
return EventList.Collect(recording, new DefaultBlackBoxStrings("pl")).Select(e => e.Text).ToList();
}
finally
{
CultureInfo.CurrentCulture = culture;
}
}
[Fact]
public void The_protection_braking_with_no_power_is_not_the_drivers_fault()
{
// no power for the first seconds, then the cab signalling not acknowledged
var recording = Drive(t => t < 5 ? NoPower : t is >= 10 and < 12 ? (byte)0x1a : (byte)0);
var braking = Assert.Single(recording.SecurityBrakings());
Assert.Equal(10, braking.Start, 6);
}
[Fact]
public void A_buzzer_acknowledged_in_time_is_told_apart_from_braking()
{
var recording = Drive(t => t is >= 2 and < 4 ? CabSignal : t is >= 4 and < 5.5 ? CabSignalBuzzing : (byte)0);
var events = Events(recording);
Assert.Contains("Brzęczyk SHP, potwierdzony po 1.5 s", events);
Assert.DoesNotContain(events, e => e.StartsWith("HAMOWANIE", System.StringComparison.Ordinal));
Assert.Empty(recording.SecurityBrakings());
}
[Fact]
public void A_buzzer_cut_by_the_power_is_not_acknowledged()
{
var recording = Drive(t => t is >= 2 and < 4 ? CabSignalBuzzing : t is >= 4 and < 8 ? NoPower : (byte)0);
var events = Events(recording);
Assert.Contains("Brzęczyk SHP", events);
Assert.DoesNotContain(events, e => e.Contains("potwierdzony", System.StringComparison.Ordinal));
}
[Fact]
public void A_buzzer_the_other_joins_is_named_by_both()
{
// the alerter's buzzer, then a magnet passed before it's acknowledged
var recording = Drive(t => t is >= 2 and < 4 ? (byte)0x05 : t is >= 4 and < 5 ? (byte)0x0f : (byte)0);
Assert.Contains("Brzęczyk CA/SHP, potwierdzony po 3.0 s", Events(recording));
}
[Fact]
public void A_buzzer_not_acknowledged_is_followed_by_the_braking()
{
// the cab signalling at the start: the buzzer at once, braking when not acknowledged
var recording = Drive(t => t < 3 ? CabSignalBuzzing : t < 6 ? CabSignalBraking : (byte)0);
var events = Events(recording);
Assert.Equal(["Brzęczyk SHP, bez potwierdzenia", "HAMOWANIE PRZEZ SHP"],
events.Where(e => e.Contains("SHP", System.StringComparison.Ordinal)));
Assert.DoesNotContain(events, e => e.Contains("CA", System.StringComparison.Ordinal));
}
}

View File

@@ -0,0 +1,119 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class CaseInsensitivePathsTests
{
private static InMemoryFileSystem Disk() => new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/scenery/Braniewo/Base.ctr", "")
.WithFile("game/scenery/Braniewo/rozklady/TGS3657.txt", "")
.WithDirectory("game/textures/mini");
[Theory]
[InlineData("braniewo/base.ctr", "Braniewo/Base.ctr")]
[InlineData(@"BRANIEWO\Rozklady\tgs3657.TXT", "Braniewo/rozklady/TGS3657.txt")]
[InlineData("Braniewo/Base.ctr", "Braniewo/Base.ctr")]
[InlineData("braniewo//base.ctr", "Braniewo/Base.ctr")]
[InlineData("/braniewo/base.ctr", "Braniewo/Base.ctr")]
[InlineData(@"\Braniewo\Base.ctr", "Braniewo/Base.ctr")]
public void A_name_in_any_case_is_given_as_it_is_on_disk(string name, string onDisk) =>
Assert.Equal(onDisk, new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
[Theory]
[InlineData("braniewo/brak.ctr")]
[InlineData("brak/base.ctr")]
[InlineData("")]
public void A_name_nothing_answers_to_is_not_found(string name) =>
Assert.Null(new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
[Fact]
public void A_folder_is_found_only_when_one_is_asked_for()
{
var names = new CaseInsensitivePaths(Disk());
Assert.Equal("Braniewo/rozklady", names.Resolve("game/scenery", "braniewo/ROZKLADY", directory: true));
Assert.Null(names.Resolve("game/scenery", "braniewo/ROZKLADY"));
Assert.Null(names.Resolve("game/scenery", "braniewo/base.ctr", directory: true));
}
[Fact]
public void The_name_written_as_on_disk_wins_over_one_in_other_case()
{
var files = Disk().WithFile("game/scenery/braniewo/base.ctr", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("braniewo/base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "Braniewo/base.CTR"));
}
[Fact]
public void Of_folders_named_alike_the_one_holding_the_file_is_taken()
{
var files = Disk().WithFile("game/scenery/braniewo/tory.scm", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
Assert.Equal("braniewo/tory.scm", names.Resolve("game/scenery", "Braniewo/Tory.scm"));
}
[Fact]
public void The_full_path_joins_the_folder_and_the_name_on_disk() =>
Assert.Equal(Path.Combine("game/scenery", "Braniewo", "Base.ctr"),
new CaseInsensitivePaths(Disk()).Find("game/scenery", "BRANIEWO/BASE.CTR"));
[Fact]
public void A_full_path_is_found_from_its_own_root()
{
string scenery = Path.GetFullPath(Path.Combine("game", "scenery"));
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(Path.Combine(scenery, "Braniewo", "Base.ctr"), "");
Assert.Equal(Path.Combine(scenery, "Braniewo", "Base.ctr"),
new CaseInsensitivePaths(files).Find("elsewhere", Path.Combine(scenery, "BRANIEWO", "base.CTR")));
}
[Fact]
public void A_disk_that_ignores_case_gives_the_name_back_as_written()
{
var files = new InMemoryFileSystem().WithFile("game/scenery/Braniewo/Base.ctr", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("BRANIEWO/base.CTR", names.Resolve("game/scenery", "BRANIEWO/base.CTR"));
Assert.Null(names.Resolve("game/scenery", "braniewo/brak.ctr"));
}
[Fact]
public void Kept_listings_hold_until_forgotten()
{
var files = Disk();
var names = new CaseInsensitivePaths(files, keepListings: true);
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
names.Forget();
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
}
[Fact]
public void Listings_not_kept_see_a_file_added_since()
{
var files = Disk();
var names = new CaseInsensitivePaths(files);
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
}
[Fact]
public void A_folder_that_cannot_be_listed_holds_nothing_to_find()
{
var files = Disk().DenyListing("game/scenery");
Assert.Null(new CaseInsensitivePaths(files).Resolve("game/scenery", "braniewo/base.ctr"));
}
}

View File

@@ -0,0 +1,53 @@
using StarterNG.Views;
namespace StarterNG.Tests;
public class ExecutableListTests
{
[Fact]
public void A_build_copied_in_joins_the_list_and_the_choice_stays()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], "eu07.exe");
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void Automatic_stays_automatic()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], null);
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(-1, chosen);
}
[Fact]
public void A_simulator_picked_from_elsewhere_stays_on_the_list_and_chosen()
{
const string picked = @"D:\build\eu07.exe";
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], picked);
Assert.Equal(new[] { "eu07.exe", picked }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void A_chosen_file_since_removed_stays_chosen_rather_than_switch_silently()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], "eu07_old.exe");
Assert.Equal(new[] { "eu07.exe", "eu07_old.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void The_choice_is_found_whatever_the_case_of_its_name()
{
var (entries, chosen) = ExecutableList.Refreshed(["EU07.exe"], "eu07.exe");
Assert.Equal(new[] { "EU07.exe" }, entries);
Assert.Equal(0, chosen);
}
}

View File

@@ -0,0 +1,82 @@
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class ExecutableNoAvx2Tests
{
private const string Elf = "\u007fELF binary";
private static readonly DateTime Older = new(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime Newer = new(2026, 11, 15, 0, 0, 0, DateTimeKind.Utc);
private static InMemoryFileSystem With(params string[] names)
{
var files = new InMemoryFileSystem();
foreach (string name in names)
files.WithExecutable(TestInstallation.At(name), Elf);
return files;
}
private static string Automatic(InMemoryFileSystem files, bool lacksAvx2) =>
Path.GetFileName(new TestInstallation(files, lacksAvx2: lacksAvx2).Executables
.Resolve(new SimulatorSettings(), out _));
[Theory]
[InlineData("eu07_noavx2", true)]
[InlineData("eu07-x64_2026-11-15_abc1234_noavx2.exe", true)]
[InlineData("EU07_NOAVX2.EXE", true)]
[InlineData("eu07", false)]
[InlineData("eu07-x64_2026-11-15_abc1234.exe", false)]
[InlineData("eu07_noavx2_old.exe", false)]
public void A_build_without_avx2_is_known_by_the_end_of_its_name(string name, bool noAvx2) =>
Assert.Equal(noAvx2, ExecutableLocator.IsNoAvx2(name));
[Fact]
public void Without_avx2_the_build_without_it_is_chosen_over_the_canonical_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: true));
[Fact]
public void With_avx2_the_build_made_for_it_stays_first() =>
Assert.Equal("eu07", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: false));
[Fact]
public void With_avx2_a_build_without_it_is_used_when_it_is_the_only_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07_noavx2"), lacksAvx2: false));
[Fact]
public void Without_avx2_the_newest_build_without_it_is_chosen()
{
var files = With("eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", Automatic(files, lacksAvx2: true));
}
[Fact]
public void Without_avx2_and_no_build_without_it_the_usual_choice_stands() =>
Assert.Equal("eu07", Automatic(With("eu07-dev", "eu07"), lacksAvx2: true));
[Fact]
public void Only_a_build_with_avx2_on_a_processor_without_it_will_not_run()
{
var lacking = new TestInstallation(lacksAvx2: true).Executables;
var able = new TestInstallation(lacksAvx2: false).Executables;
Assert.True(lacking.WillNotRunHere("eu07.exe"));
Assert.False(lacking.WillNotRunHere("eu07-x64_noavx2.exe"));
Assert.False(able.WillNotRunHere("eu07.exe"));
}
[Fact]
public void The_newest_build_without_avx2_is_offered_by_name()
{
var files = With("eu07", "eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", new TestInstallation(files).Executables.NewestNoAvx2());
Assert.Null(new TestInstallation(With("eu07")).Executables.NewestNoAvx2());
}
}

View File

@@ -97,6 +97,8 @@ public sealed class InMemoryFileSystem : IFileSystem
return this;
}
public bool IgnoresCase => _comparison == StringComparison.OrdinalIgnoreCase;
public bool FileExists(string path) => _files.ContainsKey(Normalize(path));
/// <summary>A link counts as the directory it points at, as the disk has it.</summary>
@@ -273,6 +275,9 @@ public sealed class InMemoryFileSystem : IFileSystem
return;
slash = key.LastIndexOf('/');
}
// An absolute Unix path's parent is the root, "/", which normalises to "".
if (slash == 0)
_directories.Add("");
}
private static string Normalize(string path) =>

View File

@@ -14,7 +14,7 @@ public sealed class TestInstallation
{
public const string Root = "game";
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
{
Files = files ?? new InMemoryFileSystem();
Paths = new GamePaths(Root);
@@ -35,7 +35,8 @@ public sealed class TestInstallation
SettingsPaths.VehicleCacheDirectory());
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
// The processor of the machine running the tests is not the one tested.
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
}

View File

@@ -68,6 +68,140 @@ public class HaslerTapeTests
Assert.Equal(5, tape.DistanceM, 6);
}
[Fact]
public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end()
{
// the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures
string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n");
static string WithSpeed(string line, double kmh) =>
line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n"));
// the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter
string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n",
" 0 1 0.0000 0.0000 0.0000 0.0000\r\n");
var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header()
{
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance()
{
// the player in another vehicle for ten minutes, then back in this one
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0)
+ Line(602, 36, 0, 0) + Line(603, 0, 0, 0));
Assert.Equal(603, tape.Duration, 6);
Assert.Equal(600, tape.GapTime, 6);
Assert.Equal(2, tape.RunningTime, 6);
Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping
Assert.Equal(10 + 10 + 5, tape.DistanceM, 6);
Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6);
}
[Fact]
public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap()
{
// a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after
var text = new System.Text.StringBuilder(Header);
double t = 0;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
t += 1.017 - 0.05;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
var tape = HaslerTape.Parse(text.ToString());
Assert.Equal(0, tape.GapTime, 6);
Assert.Equal(tape.Duration, tape.RunningTime, 6);
Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6);
}
[Fact]
public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole()
{
string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400)
+ Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0);
var whole = HaslerTape.Parse(text);
for (int cut = 1; cut < text.Length; cut += 7)
{
var reader = new HaslerTape.Reader();
reader.Feed(text[..cut]);
reader.Feed(text[cut..]);
Assert.Equal(whole.Samples, reader.Tape(final: true).Samples);
}
}
[Fact]
public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed()
{
var reader = new HaslerTape.Reader();
string line = Line(1, 36, 0, 0);
reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]);
Assert.Single(reader.Tape(final: false).Samples);
Assert.Single(reader.Tape(final: false).Samples);
reader.Feed(line[20..]);
Assert.Equal(2, reader.Tape(final: false).Samples.Count);
}
[Fact]
public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Single(tapes.Load(file, follow: false)!.Samples);
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0));
Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count);
// begun anew, and already longer than was read: its time goes back
files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0));
var tape = tapes.Load(file, follow: true)!;
Assert.Equal(4, tape.Samples.Count);
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
// begun anew, and shorter
files.WithFile(path, Header + Line(0, 18, 0, 0));
Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6);
}
[Fact]
public void 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()
{

View File

@@ -0,0 +1,28 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class LoadingScreenLogoTests
{
private static InMemoryFileSystem Logos() => new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/Textures/Logo/EP09_Logo.PNG", "png")
.WithFile("game/Textures/Logo/Braniewo.JPG", "jpg")
.WithFile("game/Textures/Logo/Logo1.BMP", "bmp")
.WithFile("game/Textures/Logo/notes.txt", "");
[Theory]
[InlineData("ep09_logo", null, "EP09_Logo.PNG")]
[InlineData("ep09_logo.bmp", "braniewo", "EP09_Logo.PNG")]
[InlineData(null, "braniewo", "Braniewo.JPG")]
[InlineData("brak", "brak", "Logo1.BMP")]
public void The_logo_is_found_whatever_the_case_of_its_name_and_extension(string? logo, string? scenery,
string onDisk) =>
Assert.Equal(Path.GetFullPath(Path.Combine("game", "Textures", "Logo", onDisk)),
Path.GetFullPath(LoadingScreen.FindSource(Logos(), "game", logo, scenery, new Random(1))!));
[Fact]
public void With_no_logo_folder_there_is_no_logo() =>
Assert.Null(LoadingScreen.FindSource(new InMemoryFileSystem(caseSensitive: true), "game", "x", "y",
new Random(1)));
}

View File

@@ -21,6 +21,20 @@ public sealed class PhysicalFileSystemTests : IDisposable
Assert.Equal(new[] { path }, Directory.GetFiles(_root));
}
[Fact]
public void A_pattern_lists_names_in_any_letter_case()
{
Directory.CreateDirectory(Path.Combine(_root, "PKP", "EP09"));
foreach (string name in new[] { "Braniewo.SCN", "kato.scn", "notes.txt", Path.Combine("PKP", "EP09", "EP09.FIZ"),
Path.Combine("PKP", "EP09", "ep09dumb.fiz") })
File.WriteAllText(Path.Combine(_root, name), "");
Assert.Equal(new[] { "Braniewo.SCN", "kato.scn" },
_files.GetFiles(_root, "*.scn").Select(Path.GetFileName).Order(StringComparer.Ordinal));
Assert.Equal(new[] { "EP09.FIZ", "ep09dumb.fiz" },
_files.GetFilesRecursive(_root, "*.fiz").Select(Path.GetFileName).Order(StringComparer.Ordinal));
}
[Fact]
public void An_atomic_write_that_cannot_finish_leaves_what_stood_there()
{

View File

@@ -65,6 +65,19 @@ public class PhysicsAndAssetsTests
Assert.Equal(125, physics.VMax);
}
[Fact]
public void An_include_named_in_other_case_is_followed()
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(Fiz("pkp", "ep07", "ep07"), "include Common.FIZ 84000 end")
.WithFile(TestInstallation.At("dynamic", "pkp", "ep07", "common.fiz"), "Param: M=(1) Vmax=125"));
var physics = installation.Physics.For("pkp/ep07/", "ep07")!;
Assert.Equal(84000, physics.Mass);
Assert.Equal(125, physics.VMax);
}
[Fact]
public void A_dot_in_the_model_name_is_part_of_the_name()
{
@@ -202,4 +215,31 @@ public class PhysicsAndAssetsTests
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
}
[Fact]
public void A_livery_with_no_folder_is_looked_for_in_dynamic_itself()
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("dynamic", "EP09.bmp"), "bitmap")
.WithFile(TestInstallation.At("dynamic", "ep09.e3d"), "model"));
var catalog = new StarterNG.Domain.Vehicles.VehicleCatalog(installation.MiniTextures);
catalog.Textures.Add(new StarterNG.Domain.Vehicles.VehicleTexture { Directory = "", Skinfile = "ep09", Model = "EP09" });
Assert.Empty(installation.MissingAssets.Scan(catalog));
}
[Fact]
public void A_skin_and_model_on_disk_in_other_case_are_not_reported()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "textures.txt"),
"EP09-014.mat=ep09.e3d,ep09")
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "ep09-014.BMP"), "bitmap")
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "EP09.E3D"), "model");
var installation = new TestInstallation(files);
installation.Vehicles.Load(installation.Library.Vehicles);
Assert.NotEmpty(installation.Library.Vehicles.Textures);
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
}
}

View File

@@ -182,6 +182,20 @@ public class TimetableLocatorTests
Assert.NotNull(new TimetableLocator(files).Resolve(scenery, "r1.txt"));
}
[Theory]
[InlineData(@"rozklady\tgs3657")]
[InlineData("ROZKLADY/TGS3657.TXT")]
public void A_timetable_named_in_other_case_or_with_backslashes_is_found_as_on_disk(string name)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$n Braniewo")
.WithFile(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"), "rozkład");
var scenery = Assert.Single(new TestInstallation(files).Sceneries.LoadAll());
Assert.Equal(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"),
new TimetableLocator(files).Resolve(scenery, name));
}
[Fact]
public void The_formats_none_and_a_missing_file_both_resolve_to_nothing()
{
@@ -195,3 +209,26 @@ public class TimetableLocatorTests
Assert.Null(locator.Resolve(scenery, null));
}
}
public class AttachmentLocatorTests
{
[Theory]
[InlineData(@"scenery\Braniewo\opis.PDF")]
[InlineData("SCENERY/braniewo/Opis.pdf")]
public void An_attachment_named_in_other_case_is_found_as_on_disk(string named)
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"), "%PDF"));
Assert.Equal(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"),
new AttachmentLocator(installation.Files, installation.Paths)
.Resolve(new SceneryAttachment { FilePath = named }));
}
[Theory]
[InlineData("scenery/brak.pdf")]
[InlineData("")]
public void An_attachment_that_is_not_there_is_not_found(string named) =>
Assert.Null(new AttachmentLocator(new InMemoryFileSystem(caseSensitive: true), new TestInstallation().Paths)
.Resolve(new SceneryAttachment { FilePath = named }));
}

View File

@@ -89,6 +89,23 @@ public class SceneryRepositoryTests
Assert.Equal(Path.Combine("game", "scenery", "images", "kato.jpg"), image);
}
[Theory]
[InlineData("calkowo_v2_kopalniaA.jpg", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
[InlineData(@"Images\Calkowo_V2_KopalniaA.JPG", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
[InlineData("CALKOWO_V2.JPG", "game/scenery/Calkowo_v2.jpg")]
public void The_preview_image_is_found_whatever_the_case_it_is_named_in(string named, string onDisk)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/scenery/calkowo.scn", "//$i " + named)
.WithFile("game/scenery/images/calkowo_v2_kopalniaA.jpg", "binary")
.WithFile("game/scenery/Calkowo_v2.jpg", "binary");
var scenery = Assert.Single(Build(files, out _).LoadAll());
string? image = new SceneryImageLocator(files).Resolve(scenery);
Assert.Equal(Path.GetFullPath(onDisk), Path.GetFullPath(image!));
}
[Fact]
public void A_scenery_without_an_image_directive_resolves_to_nothing()
{

View File

@@ -273,7 +273,7 @@ public class ScenerySyntaxTests
include koniec.scm
""";
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => new IncludeLookup(true));
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
Assert.Empty(scenery.Faults);
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
@@ -326,7 +326,7 @@ public class ScenerySyntaxTests
endoptional
""";
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => new IncludeLookup(name is "tory.scm" or "budynek.inc")).Faults;
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => name is "tory.scm" or "budynek.inc").Faults;
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
}
@@ -347,9 +347,9 @@ public class ScenerySyntaxTests
}
[Fact]
public void An_include_on_disk_only_in_other_letter_case_is_what_linux_misses()
public void An_include_on_disk_in_other_letter_case_is_no_fault()
{
// The simulator folds the name to lower case and opens it so.
// The simulator finds the file whatever the case of its letters, on Linux too.
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/braniewo_szeroki.scn",
"include braniewo/base.ctr end\ninclude Braniewo/Tory.SCM end\n")
@@ -357,21 +357,20 @@ public class ScenerySyntaxTests
.WithFile("game/scenery/braniewo/tory.scm", "");
var repository = TestScenery.Repository(files);
var faults = repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults;
Assert.Equal((SceneryFaultKind.IncludeLetterCase, "braniewo_szeroki.scn", 1, "Braniewo/Base.ctr", "braniewo/base.ctr"),
Seen(Assert.Single(faults)));
Assert.Empty(repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(bool sbt)
[InlineData(null)]
[InlineData("lk2_sandbox.sbt")]
[InlineData("Lk2_Sandbox.SBT")]
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(string? sbtOnDisk)
{
bool sbt = sbtOnDisk is not null;
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/Lk2_Sandbox.scn", "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n");
if (sbt)
files.WithFile("game/scenery/lk2_sandbox.sbt", "EU07");
files.WithFile("game/scenery/" + sbtOnDisk, "EU07");
var repository = TestScenery.Repository(files);
var scenery = repository.Load("game/scenery/Lk2_Sandbox.scn")!;

View File

@@ -39,6 +39,24 @@ public class SceneryTranslationsTests
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
}
[Fact]
public void The_tables_are_found_whatever_the_case_of_their_names()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$d @brief")
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "braniewo_en.json"),
"""{ "brief": "English" }""")
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "BRANIEWO_PL.json"),
"""{ "brief": "Polski" }""");
var installation = new TestInstallation(files);
var scenery = Assert.Single(installation.Sceneries.LoadAll());
var translations = new SceneryTranslations(files, installation.Log);
translations.LoadFor(scenery, "Polski");
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
}
[Fact]
public void Literal_text_and_unknown_keys_are_left_alone()
{

View File

@@ -1257,6 +1257,39 @@ public class SettingsStoreTests
Assert.False(store.LoadFailed);
}
[Fact]
public void A_profile_from_before_the_tapes_of_the_trains_is_moved_as_the_ini_would_be()
{
var files = new InMemoryFileSystem()
.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.False(store.Settings.PhysicsLog);
Assert.True(store.Settings.PhysicsLogTrains);
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()
{
@@ -1302,4 +1335,189 @@ 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"));
}
[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);
}
[Theory]
[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));
installation.SettingsStore.Load();
var s = installation.SettingsStore.Settings;
Assert.False(s.PhysicsLog);
Assert.True(s.PhysicsLogTrains);
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("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 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()
{
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.False(installation.SettingsStore.Settings.PhysicsLogTrains);
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
}
[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()
{
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"));
}
}

View File

@@ -0,0 +1,45 @@
using Avalonia;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class SoftwareRenderTests
{
[Theory]
[InlineData("--software-render")]
[InlineData("--Software-Render")]
public void The_switch_asks_for_it_in_any_case(string arg)
{
Assert.True(SoftwareRender.AskedIn(new[] { "--other", arg }));
}
[Fact]
public void Without_the_switch_the_graphics_card_draws()
{
Assert.False(SoftwareRender.AskedIn(Array.Empty<string>()));
Assert.False(SoftwareRender.AskedIn(new[] { "--software" }));
}
[Fact]
public void Windows_draws_on_the_processor_into_a_plain_window_surface()
{
var options = SoftwareRender.Win32Options;
Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode);
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
}
[Fact]
public void X11_draws_on_the_processor()
{
Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode);
}
[Fact]
public void Both_platforms_options_go_to_the_same_builder()
{
var builder = AppBuilder.Configure<Avalonia.Application>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
}
}

View File

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

View File

@@ -0,0 +1,98 @@
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class SystemGraphicsLibrariesTests
{
private const string System32 = @"C:\Windows\System32";
private const string Game = @"E:\SteamLibrary\steamapps\common\MaSzyna";
private static readonly IntPtr Dxgi = new(0x1000);
private static readonly IntPtr D3d11 = new(0x2000);
private static SystemGraphicsLibraries Take(Func<string, bool> beside, Dictionary<string, IntPtr> system)
{
return SystemGraphicsLibraries.Take(System32, Game, beside, Load);
bool Load(string path, out IntPtr handle)
{
handle = system.GetValueOrDefault(Path.GetFileName(path));
return handle != IntPtr.Zero;
}
}
private static SystemGraphicsLibraries WithDxgiAndD3d11(Func<string, bool> beside) =>
Take(beside, new Dictionary<string, IntPtr> { ["dxgi.dll"] = Dxgi, ["d3d11.dll"] = D3d11 });
[Fact]
public void An_import_by_name_gets_the_system_library_with_or_without_its_extension()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Equal(Dxgi, taken.Resolve("dxgi"));
Assert.Equal(Dxgi, taken.Resolve("dxgi.dll"));
Assert.Equal(D3d11, taken.Resolve("D3D11.DLL"));
}
[Fact]
public void Other_libraries_and_ones_the_system_lacks_are_left_to_the_usual_search()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Equal(IntPtr.Zero, taken.Resolve("user32.dll"));
Assert.Equal(IntPtr.Zero, taken.Resolve("opengl32"));
}
[Fact]
public void They_are_loaded_from_the_system_folder_dxgi_first()
{
var asked = new List<string>();
SystemGraphicsLibraries.Take(System32, Game, _ => false, Load);
Assert.Equal(SystemGraphicsLibraries.Names.Select(n => Path.Combine(System32, n + ".dll")), asked);
Assert.Equal("dxgi", SystemGraphicsLibraries.Names[0]);
bool Load(string path, out IntPtr handle)
{
asked.Add(path);
handle = IntPtr.Zero;
return false;
}
}
[Fact]
public void A_wrapper_beside_the_starter_is_noted()
{
var taken = WithDxgiAndD3d11(path => path == Path.Combine(Game, "dxgi.dll"));
Assert.Equal(new[] { "dxgi.dll" }, taken.Shadowed);
Assert.Contains("dxgi.dll", taken.Note);
}
[Fact]
public void With_nothing_beside_the_starter_there_is_nothing_to_note()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Empty(taken.Shadowed);
Assert.Null(taken.Note);
}
[Fact]
public void Only_windows_has_system_libraries_to_take()
{
var taken = SystemGraphicsLibraries.TakeOnWindows();
Assert.Equal(OperatingSystem.IsWindows(), taken is not null);
}
[Fact]
public void An_assembly_with_a_resolver_of_its_own_keeps_it()
{
var taken = WithDxgiAndD3d11(_ => false);
var assembly = typeof(SystemGraphicsLibrariesTests).Assembly;
Assert.True(taken.ServeTo(assembly));
Assert.False(taken.ServeTo(assembly));
}
}

View File

@@ -130,6 +130,17 @@ public class TapeLaunchTests
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), name));
[Fact]
public void The_train_number_comes_from_a_timetable_named_in_other_case_with_backslashes()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Baltyk", "EIE1531.txt"), "[ Rodzaj i numer pociagu | EIE1531 ]\r\n");
Assert.Equal("EIE1531", new StarterNG.Infrastructure.Sceneries.TimetableLocator(files)
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""),
@"baltyk\eie1531"));
}
[Fact]
public void A_timetable_that_is_not_there_gives_no_train_number() =>
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())

View File

@@ -0,0 +1,22 @@
using StarterNG.Domain.Vehicles;
using StarterNG.Infrastructure.Vehicles;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class TextureFolderTests
{
private static readonly TestInstallation Installation = new(new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/dynamic/PKP/EP09_v1/textures.txt", "")
.WithDirectory("game/Other/Folder"));
[Theory]
[InlineData("pkp/ep09_v1/", "dynamic/PKP/EP09_v1")]
[InlineData(@"PKP\EP09_V1", "dynamic/PKP/EP09_v1")]
[InlineData("other/folder/", "Other/Folder")]
[InlineData("pkp/brak/", "pkp/brak")]
public void A_liverys_folder_is_found_as_it_is_named_on_disk(string named, string onDisk) =>
Assert.Equal(Path.GetFullPath(Path.Combine("game", onDisk)),
Path.GetFullPath(TextureFolder.Of(Installation.Files, Installation.Paths,
new VehicleTexture { Directory = named })));
}

View File

@@ -207,8 +207,12 @@ public partial class App : Avalonia.Application
if (check.ExecutableMissing())
await main.OfferExecutablePickAsync();
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
await main.ShowCpuNoticeAsync();
// A build without AVX2 in the folder is started instead, and needs no notice.
var services = AppServices.Current;
if (services.Settings.CpuNotice
&& services.Executables.Resolve(services.Settings, out _) is var executable
&& services.Executables.WillNotRunHere(executable))
await main.ShowCpuNoticeAsync(executable);
});
});
}

View File

@@ -7,6 +7,9 @@ namespace StarterNG.Application.Abstractions;
public interface IFileSystem
{
/// <summary>Whether a name finds its file whatever the case of its letters, as on Windows and macOS.</summary>
bool IgnoresCase { get; }
bool FileExists(string path);
bool DirectoryExists(string path);

View File

@@ -56,6 +56,7 @@ public sealed class AppServices
var missingAssets = new MissingAssetScanner(files, paths);
SceneryTexts = new SceneryTranslations(files, log);
Timetables = new TimetableLocator(files);
Attachments = new AttachmentLocator(files, paths);
LoadWeights = new LoadWeightsRepository(files, paths, log);
Library = new GameLibrary(Vehicles, Sceneries, MiniTextures, Physics, log);
State = new AppState();
@@ -122,6 +123,8 @@ public sealed class AppServices
public TimetableLocator Timetables { get; }
public AttachmentLocator Attachments { get; }
public LoadWeightsRepository LoadWeights { get; }
public GameLibrary Library { get; }

View File

@@ -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
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<TapeSession> Sessions()
{
@@ -278,11 +280,15 @@ public sealed class HaslerTapes
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
}
// 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 recordings = Recordings(looseBoxes);
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, 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);
var run = new List<TapeFile>();
var runBoxes = new List<BlackBoxRecording>();
@@ -315,6 +321,39 @@ 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>
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));
@@ -411,19 +450,88 @@ 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);
/// <summary>
/// The tape of this file no longer followed: what was kept of it is let go. Another file's, followed for another
/// window, stays.
/// </summary>
public void Forget(string path)
{
try
lock (_followedLock)
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
private static byte[] Bytes(Stream stream, long from, long to)
{
stream.Seek(from, SeekOrigin.Begin);
var bytes = new byte[to - from];
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];
}
/// <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());
// 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<byte>(), new HaslerTape.Reader());
added = Bytes(stream, 0, length);
followed.Reader.Feed(Encoding.ASCII.GetString(added));
}
_followed = (file.Path, followed.Read + added.Length, Tail(followed.Tail, added), followed.Reader);
return followed.Reader.Tape(final: !follow);
}
catch (Exception ex)
{
_followed = null;
_log.Log($"reading {file.Path}", ex);
return null;
}
}
}
}

View File

@@ -113,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();
}
@@ -233,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;
}
@@ -240,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.
/// </summary>
public bool ExportTo(string path)
/// <param name="settings">What to write, when not the settings held: a page's edits, still not taken in.</param>
public bool ExportTo(string path, SimulatorSettings? settings = null)
{
if (LoadFailed)
{
@@ -249,7 +255,7 @@ public sealed class SettingsStore
}
var copy = ConfigFile.Parse(_config.ToText());
ApplyChanges(copy, Changes(Settings));
ApplyChanges(copy, Changes(settings ?? Settings));
try
{

View File

@@ -144,7 +144,7 @@ public sealed class StartSimulation
if (saveSettings)
_settings.CaptureAndSave();
if (_settings.Settings.PhysicsLog)
if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox || _settings.Settings.PhysicsLogTrains)
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)

View File

@@ -61,13 +61,6 @@ public enum SceneryFaultKind
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
MissingInclude,
/// <summary>
/// An include whose file is there only under a name in other letter case: the
/// simulator looks for it in lower case, which on Linux misses it. The
/// <see cref="SceneryFault.Subject"/> holds the name on disk.
/// </summary>
IncludeLetterCase,
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
IncludeNotClosed,

View File

@@ -5,12 +5,6 @@ using System.Linq;
namespace StarterNG.Domain.Sceneries;
/// <summary>
/// What the simulator makes of an include: whether it opens the file - and when
/// it does not, the file that is there under a name differing only in letter case.
/// </summary>
public readonly record struct IncludeLookup(bool Opens, string? OnDisk = null);
/// <summary>
/// Goes through a scenery's text for the parts the starter reads - trainsets,
/// vehicles, includes - finding where each trainset and loose vehicle is, and
@@ -35,17 +29,17 @@ public static class ScenerySyntax
/// <param name="text">The scenery's text, its includes put in place.</param>
/// <param name="file">The scenery's file name, for faults in its own text.</param>
/// <param name="findInclude">
/// What the simulator makes of an include, named as the include names it; null
/// <param name="opensInclude">
/// Whether the simulator opens an include, named as the include names it; null
/// leaves includes unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, IncludeLookup>? findInclude = null)
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null)
{
string code = SceneryCode.Mask(text, out int unclosed);
var tokens = SceneryCode.Tokens(code);
var lines = new SceneryLines(text, file);
var simulator = new Reading(tokens, lines, findInclude, asSimulator: true);
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true);
simulator.Run();
var author = new Reading(tokens, lines, null, asSimulator: false);
author.Run();
@@ -116,7 +110,7 @@ public static class ScenerySyntax
}
private sealed class Reading(
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, IncludeLookup>? findInclude, bool asSimulator)
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
{
public readonly List<(int Start, int End, string Name)> Trainsets = new();
public readonly List<(int, int)> Loose = new();
@@ -375,13 +369,8 @@ public static class ScenerySyntax
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
}
if (findInclude is not null && Plain(name) && findInclude(name) is { Opens: false } lookup)
{
if (lookup.OnDisk is { } onDisk)
Fault(SceneryFaultKind.IncludeLetterCase, token.Index, onDisk, name);
else
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
}
if (opensInclude is not null && Plain(name) && !opensInclude(name))
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
// The simulator takes its parameters up to the word "end", written just so,
// whatever comes before it.

View File

@@ -133,6 +133,20 @@ public sealed class SimulatorSettings
public bool EnableTraction = true;
public bool LiveTraction = true;
public bool PhysicsLog;
/// <summary>
/// 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.
/// </summary>
public bool BlackBox;
/// <summary>Whether eu07.ini had a line of its own for the black box when read: it is kept saying what is wanted.</summary>
public bool BlackBoxInIni;
/// <summary>
/// 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.
/// </summary>
public bool PhysicsLogTrains;
/// <summary>Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on.</summary>
public bool PhysicsLogTrainsInIni;
public bool DebugLog = true;
public bool MultipleLogs;
public bool DisplaySimulation = true;

View File

@@ -29,23 +29,42 @@ 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<TapeSample> samples)
// 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) : 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);
GapSeconds = gap;
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<TapeSample> Samples { get; }
@@ -60,50 +79,137 @@ public sealed class HaslerTape
public double MaxSpeedKmh { get; }
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing.</summary>
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing, or not recorded.</summary>
public double RunningTime { get; }
public double StandingTime => Duration - RunningTime;
/// <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>
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
/// <summary>Mean speed over the whole recording, stops included - the commercial speed.</summary>
public double AverageWithStopsKmh => Duration > 0 ? DistanceM / Duration * 3.6 : 0;
public double AverageWithStopsKmh => Duration - GapTime > 0 ? DistanceM / (Duration - GapTime) * 3.6 : 0;
/// <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, two seconds at least.
/// </summary>
public static double GapAbove(IReadOnlyList<TapeSample> 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<TapeSample>();
double distance = 0;
TapeSample? previous = null;
var reader = new Reader();
reader.Feed(text);
return reader.Tape(final: true);
}
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 < 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 == 0)
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;
return;
}
if (columns.Length < MinimumColumns || !Number(columns[VelocityColumn], out double velocity))
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 = columns[^SecurityFromEnd] == "1";
bool security = _securityFromEnd <= columns.Length && columns[^_securityFromEnd] == "1";
double speed = Math.Abs(velocity);
if (previous is { } p)
if (samples.Count > 0 && time < samples[^1].Time)
{
if (time < p.Time)
continue;
distance += (p.SpeedKmh + speed) / 2 / 3.6 * (time - p.Time);
WentBack = true;
return;
}
var sample = new TapeSample(time, speed, distance, brake, pipe, current, security);
samples.Add(sample);
previous = sample;
samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security));
}
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

@@ -10,6 +10,9 @@ public sealed class PhysicalFileSystem : IFileSystem
{
public const string TempSuffix = ".starter.tmp";
// Their disks as they come; a Linux one tells case apart.
public bool IgnoresCase { get; } = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
public bool FileExists(string path) => File.Exists(path);
public bool DirectoryExists(string path) => Directory.Exists(path);
@@ -88,8 +91,18 @@ public sealed class PhysicalFileSystem : IFileSystem
public void CopyFile(string sourcePath, string destinationPath, bool overwrite) =>
File.Copy(sourcePath, destinationPath, overwrite);
// The pattern matches names in any letter case, as on Windows: the game's data,
// made there, has X.SCN as well as x.scn.
public IReadOnlyList<string> GetFiles(string path, string searchPattern = "*") =>
Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty<string>();
Directory.Exists(path)
? Directory.GetFiles(path, searchPattern, new EnumerationOptions
{
IgnoreInaccessible = false,
AttributesToSkip = 0,
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive
})
: Array.Empty<string>();
// A folder it may not enter costs what is in it, not the whole listing.
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
@@ -99,7 +112,8 @@ public sealed class PhysicalFileSystem : IFileSystem
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = 0,
MatchType = MatchType.Win32
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive
})
: Array.Empty<string>();

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>
/// Finds a file or folder of the game's data by a name whose letters may stand in
/// another case than on disk, as Windows, Wine and the simulator find it, and gives
/// the name as the disk has it. The data is made on Windows: its names and the
/// names written in it seldom agree letter for letter, which on Linux matters.
/// </summary>
public sealed class CaseInsensitivePaths
{
private readonly IFileSystem _files;
private readonly Func<(string Folder, bool Files), ILookup<string, string>> _list;
/// <summary>Each folder's files and folders by name, listed once until <see cref="Forget"/>; null lists every time.</summary>
private readonly ConcurrentDictionary<(string Folder, bool Files), ILookup<string, string>>? _listings;
/// <param name="keepListings">
/// Lists each folder once, for many names looked up in data that stays as it is
/// meanwhile, until <see cref="Forget"/>.
/// </param>
public CaseInsensitivePaths(IFileSystem files, bool keepListings = false)
{
_files = files;
_list = List;
if (keepListings)
_listings = new ConcurrentDictionary<(string, bool), ILookup<string, string>>();
}
/// <summary>Lets the next lookups list the folders again.</summary>
public void Forget() => _listings?.Clear();
/// <summary>
/// The file named so under <paramref name="folder"/> as it is named on disk, relative
/// to the folder with forward slashes; null when nothing there answers to it. A name
/// written with its letters as on disk wins over one differing only in their case;
/// a disk that does not tell case apart gives it back as written.
/// </summary>
/// <param name="name">
/// A name under the folder, with either slash, joined to it as the simulator joins
/// it: a slash ahead of it counts for nothing.
/// </param>
/// <param name="directory">Looks for a folder instead of a file.</param>
public string? Resolve(string folder, string name, bool directory = false)
{
string[] parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
return null;
string exact = string.Join('/', parts);
string whole = Path.Combine(folder, exact);
if (directory ? _files.DirectoryExists(whole) : _files.FileExists(whole))
return exact;
// Where case does not matter, missed as written is missed in any case.
if (_files.IgnoresCase)
return null;
var found = new string[parts.Length];
return Walk(folder, parts, 0, directory, found) ? string.Join('/', found) : null;
}
/// <summary>
/// The full path of the file named so, its letters as on disk; null when there is
/// none. A name given in full is looked up from its own root, any other under
/// <paramref name="folder"/> as <see cref="Resolve"/> does.
/// </summary>
public string? Find(string folder, string name, bool directory = false)
{
if (Path.IsPathFullyQualified(name))
{
folder = Path.GetPathRoot(name)!;
name = name[folder.Length..];
}
return Resolve(folder, name, directory) is { } found
? Path.Combine(folder, found.Replace('/', Path.DirectorySeparatorChar))
: null;
}
/// <summary>
/// Finds the parts from <paramref name="at"/> on under <paramref name="current"/>. Of
/// folders named alike in other case - two copies of the data on Linux - each is
/// tried, the one written as on disk first.
/// </summary>
private bool Walk(string current, string[] parts, int at, bool directory, string[] found)
{
if (at == parts.Length)
return true;
string part = parts[at];
if (part is "." or "..")
{
found[at] = part;
return Walk(Path.Combine(current, part), parts, at + 1, directory, found);
}
bool last = at == parts.Length - 1;
var matches = Listing(current, files: last && !directory)[part]
.OrderBy(entry => string.Equals(Path.GetFileName(entry), part, StringComparison.Ordinal) ? 0 : 1);
foreach (string match in matches)
{
found[at] = Path.GetFileName(match);
if (Walk(match, parts, at + 1, directory, found))
return true;
}
return false;
}
private ILookup<string, string> Listing(string folder, bool files) =>
_listings is null ? List((folder, files)) : _listings.GetOrAdd((folder, files), _list);
// A folder that cannot be listed holds nothing to be found.
private ILookup<string, string> List((string Folder, bool Files) key)
{
var entries = Array.Empty<string>();
try
{
if (_files.DirectoryExists(key.Folder))
entries = (key.Files ? _files.GetFiles(key.Folder) : _files.GetDirectories(key.Folder)).ToArray();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing listed, nothing found.
}
return entries.ToLookup(entry => Path.GetFileName(entry), StringComparer.OrdinalIgnoreCase);
}
}

View File

@@ -5,16 +5,21 @@ using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using StarterNG.Application.Abstractions;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure;
public static class LoadingScreen
{
private static readonly string[] Extensions = { ".bmp", ".jpg", ".jpeg", ".png" };
public static void Prepare(string? logoKey, string? sceneryName = null)
{
try
{
string? src = ResolveSource(logoKey) ?? ResolveSource(sceneryName) ?? PickRandom();
string? src = FindSource(new PhysicalFileSystem(), Directory.GetCurrentDirectory(), logoKey, sceneryName,
Random.Shared);
if (src is null) return;
string destDir = Path.Combine(Directory.GetCurrentDirectory(), "textures");
@@ -35,32 +40,36 @@ public static class LoadingScreen
}
}
private static string? ResolveSource(string? key)
/// <summary>
/// The picture of textures/logo under <paramref name="root"/> to show: the trainset's,
/// else the scenery's, else one of logo*.* at random; its name and extension in any
/// letter case. Null when there is none.
/// </summary>
public static string? FindSource(IFileSystem files, string root, string? logoKey, string? sceneryName,
Random random)
{
var names = new CaseInsensitivePaths(files);
if (names.Find(root, "textures/logo", directory: true) is not { } dir)
return null;
return Named(names, dir, logoKey) ?? Named(names, dir, sceneryName) ?? PickRandom(files, dir, random);
}
private static string? Named(CaseInsensitivePaths names, string dir, string? key)
{
if (string.IsNullOrWhiteSpace(key)) return null;
key = Path.GetFileNameWithoutExtension(key.Trim());
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
foreach (string ext in new[] { ".bmp", ".jpg", ".jpeg", ".png" })
{
string path = Path.Combine(dir, key + ext);
if (File.Exists(path)) return path;
}
return null;
if (key.Length == 0) return null;
return Extensions.Select(ext => names.Find(dir, key + ext)).FirstOrDefault(path => path is not null);
}
private static string? PickRandom()
private static string? PickRandom(IFileSystem files, string dir, Random random)
{
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
if (!Directory.Exists(dir)) return null;
var files = Directory.GetFiles(dir, "logo*.*")
.Where(f =>
{
string e = Path.GetExtension(f).ToLowerInvariant();
return e is ".bmp" or ".jpg" or ".jpeg" or ".png";
})
var logos = files.GetFiles(dir, "logo*.*")
.Where(f => Extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
.Order(StringComparer.Ordinal)
.ToArray();
if (files.Length == 0) return null;
return files[Random.Shared.Next(files.Length)];
if (logos.Length == 0) return null;
return logos[random.Next(logos.Length)];
}
private static void WriteBmp(string sourcePath, string destPath)

View File

@@ -0,0 +1,24 @@
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Sceneries;
namespace StarterNG.Infrastructure.Sceneries;
/// <summary>Where the file a scenery attaches (<c>//$f</c>) is on disk.</summary>
public sealed class AttachmentLocator
{
private readonly IGamePaths _paths;
private readonly CaseInsensitivePaths _names;
public AttachmentLocator(IFileSystem files, IGamePaths paths)
{
_paths = paths;
_names = new CaseInsensitivePaths(files);
}
/// <summary>
/// The attachment's file, named from the game's folder or in full, with its letters
/// as on disk; null when it is not there.
/// </summary>
public string? Resolve(SceneryAttachment attachment) =>
string.IsNullOrWhiteSpace(attachment.FilePath) ? null : _names.Find(_paths.Root, attachment.FilePath.Trim());
}

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Sceneries;
@@ -8,11 +9,13 @@ namespace StarterNG.Infrastructure.Sceneries;
public sealed class SceneryImageLocator
{
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
private readonly Dictionary<string, string?> _cache = new();
public SceneryImageLocator(IFileSystem files)
{
_files = files;
_names = new CaseInsensitivePaths(files);
}
public string? Resolve(Scenery scenery)
@@ -34,22 +37,23 @@ public sealed class SceneryImageLocator
return null;
string name = scenery.ImageName.Replace('\\', '/').Trim();
if (Path.IsPathFullyQualified(name))
return _names.Find("", name);
if (_files.FileExists(name))
return name;
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
string[] candidates =
(string Folder, string Name)[] candidates =
{
name,
Path.Combine(root, name),
Path.Combine(sceneryDir, name),
Path.Combine(sceneryDir, "images", name),
Path.Combine(root, "scenery", "images", name)
(root, name),
(sceneryDir, name),
(sceneryDir, "images/" + name),
(root, "scenery/images/" + name)
};
foreach (string candidate in candidates)
if (_files.FileExists(candidate))
return candidate;
return null;
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
.FirstOrDefault(found => found is not null);
}
}

View File

@@ -20,11 +20,11 @@ public sealed class SceneryParser
_random = random;
}
/// <param name="findInclude">
/// What the simulator makes of an include, as the include names it; null leaves
/// <param name="opensInclude">
/// Whether the simulator opens an include, as the include names it; null leaves
/// includes unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, IncludeLookup>? findInclude = null)
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null)
{
string original = content;
@@ -38,7 +38,7 @@ public sealed class SceneryParser
// Read from the text with its optional includes blanked, which keeps every
// place where it was, so a fault's line is the line in the file.
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), findInclude);
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude);
var faults = syntax.Faults.ToList();
var inlined = SceneryIncludes.Ranges(content);

View File

@@ -23,7 +23,7 @@ public sealed class SceneryRepository : ISceneryRepository
private readonly SceneryParser _parser;
/// <summary>The scenery folders' files and folders, listed once per load of them all.</summary>
private readonly ConcurrentDictionary<(string, bool), IReadOnlyList<string>> _listings = new();
private readonly CaseInsensitivePaths _names;
public SceneryRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, SceneryParser parser)
{
@@ -31,11 +31,12 @@ public sealed class SceneryRepository : ISceneryRepository
_paths = paths;
_log = log;
_parser = parser;
_names = new CaseInsensitivePaths(files, keepListings: true);
}
public IReadOnlyList<Scenery> LoadAll(IProgress<SceneryLoadProgress>? progress = null)
{
_listings.Clear();
_names.Forget();
var files = SceneryFiles().ToList();
var loaded = new ConcurrentBag<Scenery>();
int total = Math.Max(1, files.Count);
@@ -58,7 +59,7 @@ public sealed class SceneryRepository : ISceneryRepository
public Scenery? Load(string path)
{
_listings.Clear();
_names.Forget();
return LoadOne(path);
}
@@ -79,10 +80,8 @@ public sealed class SceneryRepository : ISceneryRepository
// With its own .sbt the scenery's terrain comes from it, and the simulator
// passes its terrain includes over without opening them.
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
IncludeLookup FindInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"))
? new IncludeLookup(true)
: new IncludeLookup(false, ResolveInclude(name));
bool OpensInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));
(string File, string Text)? ReadInclude(string name)
{
@@ -99,7 +98,7 @@ public sealed class SceneryRepository : ISceneryRepository
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
string text = SceneryIncludes.Inline(own, ReadInclude);
var scenery = _parser.Parse(path, text, FindInclude);
var scenery = _parser.Parse(path, text, OpensInclude);
scenery.HasCompanionTimetable = binaryTerrain;
scenery.Sources = sources;
scenery.TextEncoding = ownEncoding;
@@ -114,11 +113,11 @@ public sealed class SceneryRepository : ISceneryRepository
}
/// <summary>
/// Whether the simulator opens a file of the scenery folder named so: by the
/// name in lower case, which on Linux has to be how it is named on disk.
/// Whether the simulator opens a file of the scenery folder named so: whatever the
/// case of its letters, on Linux too. A shade more lenient than eu07 there, which
/// folds only the letters A to Z and of two folders named alike takes the first.
/// </summary>
private bool Opens(string name) =>
_files.FileExists(Path.Combine(_paths.Scenery, SimulatorNames.Lower(name.Replace('\\', '/'))));
private bool Opens(string name) => ResolveInclude(name) is not null;
/// <summary>
/// An include's file as it is named on disk, from the scenery folder, whatever
@@ -126,44 +125,7 @@ public sealed class SceneryRepository : ISceneryRepository
/// copy written for a start carries in place of the include, so they come along
/// on Linux too.
/// </summary>
private string? ResolveInclude(string name)
{
string relative = name.Replace('\\', '/');
if (_files.FileExists(Path.Combine(_paths.Scenery, relative)))
return relative;
string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries);
string directory = _paths.Scenery;
var found = new List<string>();
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] is "." or "..")
{
directory = Path.Combine(directory, parts[i]);
found.Add(parts[i]);
continue;
}
bool last = i == parts.Length - 1;
string? match = Listing(directory, last)
.FirstOrDefault(entry => string.Equals(Path.GetFileName(entry), parts[i],
StringComparison.OrdinalIgnoreCase));
if (match is null)
return null;
directory = match;
found.Add(Path.GetFileName(match));
}
return string.Join('/', found);
}
private IReadOnlyList<string> Listing(string directory, bool files) =>
_listings.GetOrAdd((directory, files), key =>
{
if (!_files.DirectoryExists(key.Item1))
return Array.Empty<string>();
return key.Item2 ? _files.GetFiles(key.Item1) : _files.GetDirectories(key.Item1);
});
private string? ResolveInclude(string name) => _names.Resolve(_paths.Scenery, name);
private IEnumerable<string> SceneryFiles() =>
_files.GetFiles(_paths.Scenery, "*.scn")

View File

@@ -14,12 +14,14 @@ public sealed class SceneryTranslations : ISceneryTranslations
private const string BaseLanguage = "en";
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
private readonly IDiagnosticsLog _log;
private readonly Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
public SceneryTranslations(IFileSystem files, IDiagnosticsLog log)
{
_files = files;
_names = new CaseInsensitivePaths(files);
_log = log;
}
@@ -29,12 +31,11 @@ public sealed class SceneryTranslations : ISceneryTranslations
string sceneryDir = Path.GetDirectoryName(Path.GetFullPath(scenery.Path)) ?? "scenery";
string id = Path.GetFileNameWithoutExtension(scenery.Path);
string i18nDir = Path.Combine(sceneryDir, "i18n");
string language = NormalizeLanguage(langCode);
TryLoad(Path.Combine(i18nDir, $"{id}_{BaseLanguage}.json"));
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{BaseLanguage}.json"));
if (!string.Equals(language, BaseLanguage, StringComparison.OrdinalIgnoreCase))
TryLoad(Path.Combine(i18nDir, $"{id}_{language}.json"));
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{language}.json"));
}
public string Translate(string? text)
@@ -50,9 +51,9 @@ public sealed class SceneryTranslations : ISceneryTranslations
return _map.TryGetValue(key, out string? translated) ? translated : text;
}
private void TryLoad(string path)
private void TryLoad(string? path)
{
if (!_files.FileExists(path))
if (path is null)
return;
try

View File

@@ -17,10 +17,12 @@ public sealed class TimetableLocator
RegexOptions.Multiline | RegexOptions.IgnoreCase);
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
public TimetableLocator(IFileSystem files)
{
_files = files;
_names = new CaseInsensitivePaths(files);
}
public string? Resolve(Scenery scenery, string? name)
@@ -30,17 +32,19 @@ public sealed class TimetableLocator
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
name = name.Replace('\\', '/');
string[] candidates =
(string Folder, string Name)[] candidates =
{
Path.Combine(root, "timetables", name + ".txt"),
Path.Combine(sceneryDir, name + ".txt"),
Path.Combine(root, "scenario", name + ".txt"),
Path.Combine(root, "timetables", name),
Path.Combine(sceneryDir, name)
(root, "timetables/" + name + ".txt"),
(sceneryDir, name + ".txt"),
(root, "scenario/" + name + ".txt"),
(root, "timetables/" + name),
(sceneryDir, name)
};
return candidates.FirstOrDefault(_files.FileExists);
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
.FirstOrDefault(found => found is not null);
}
/// <summary>The number the timetable gives its train; null with no timetable or no such heading in it.</summary>

View File

@@ -22,15 +22,37 @@ public sealed class ExecutableLocator
private string? _wine;
private bool _wineLookedUp;
private string? _missingPickLogged;
private readonly bool _lacksAvx2;
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log)
/// <param name="lacksAvx2">Whether this processor runs no AVX2; asked of it when left out.</param>
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log,
bool? lacksAvx2 = null)
{
_files = files;
_paths = paths;
_environment = environment;
_log = log;
_lacksAvx2 = lacksAvx2 ?? CpuFeatures.LacksAvx2;
}
/// <summary>
/// The end of the name of a simulator built without AVX2, last before any extension:
/// eu07-x64_2026-11-15_abc1234_noavx2.exe, eu07_noavx2. It runs on any x86-64 processor.
/// </summary>
public const string NoAvx2Suffix = "_noavx2";
public static bool IsNoAvx2(string path) =>
Path.GetFileNameWithoutExtension(path).EndsWith(NoAvx2Suffix, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether <paramref name="executable"/> stops at its first instruction here: a build
/// with AVX2 on a processor without it. Such a processor is told so before a start.
/// </summary>
public bool WillNotRunHere(string executable) => _lacksAvx2 && !IsNoAvx2(executable);
/// <summary>The newest build without AVX2 in the installation, or null where there is none.</summary>
public string? NewestNoAvx2() => ListCandidates().FirstOrDefault(IsNoAvx2);
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
/// <summary>
@@ -71,7 +93,8 @@ public sealed class ExecutableLocator
{
var candidates = _files.GetFiles(_paths.Root, "eu07*")
.Where(IsCandidate)
.OrderBy(path => IsExeOnLinux(path) ? 1 : 0)
.OrderBy(Rank)
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(path => Path.GetFileName(path).Length);
@@ -101,6 +124,18 @@ public sealed class ExecutableLocator
return CanonicalName;
}
/// <summary>
/// The order of the search. Without AVX2 a build without it comes first, the newest of
/// them, even through Wine: the others stop at once. With AVX2 one is the last resort,
/// as the build made for the processor runs faster; native before Wine either way.
/// </summary>
private int Rank(string path)
{
int wine = IsExeOnLinux(path) ? 1 : 0;
int noAvx2 = IsNoAvx2(path) ? 1 : 0;
return _lacksAvx2 ? (1 - noAvx2) * 2 + wine : wine * 2 + noAvx2;
}
public List<string> ListCandidates(string? directory = null)
{
try

View File

@@ -9,6 +9,21 @@ namespace StarterNG.Infrastructure.Settings;
public sealed class SettingsSerializer
{
/// <summary>
/// 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.
/// </summary>
public static void MoveToTrainTapes(SimulatorSettings s)
{
if (s.PhysicsLogTrainsInIni || !s.BlackBoxInIni || !s.BlackBox)
return;
s.PhysicsLogTrains = true;
s.PhysicsLogTrainsInIni = true;
s.PhysicsLog = false;
}
private readonly bool _dlssPlatform;
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
@@ -157,6 +172,11 @@ public sealed class SettingsSerializer
s.EnableTraction = c.GetBool("enabletraction", true);
s.LiveTraction = c.GetBool("livetraction", true);
s.PhysicsLog = c.GetBool("physicslog", false);
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.PhysicsLogTrains;
int debugLog = c.GetInt("debuglog", 3);
s.DebugLog = (debugLog & 1) != 0;
s.DebugLogVisible = (debugLog & 2) != 0;
@@ -370,6 +390,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 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 || 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);

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// Drawn by the processor instead of the graphics card, for a machine on which the
/// window comes up empty. Each platform reads only its own options, so both are given.
/// </summary>
public static class SoftwareRender
{
public const string Switch = "--software-render";
public static bool AskedIn(IEnumerable<string> args) =>
args.Any(a => string.Equals(a, Switch, StringComparison.OrdinalIgnoreCase));
public static Win32PlatformOptions Win32Options => new()
{
RenderingMode = new[] { Win32RenderingMode.Software },
CompositionMode = new[] { Win32CompositionMode.RedirectionSurface }
};
public static X11PlatformOptions X11Options => new()
{
RenderingMode = new[] { X11RenderingMode.Software }
};
public static AppBuilder ApplyTo(AppBuilder builder) =>
builder.With(Win32Options).With(X11Options);
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace StarterNG.Infrastructure;
/// <summary>
/// The starter sits in the simulator's folder, and so do the graphics wrappers a player
/// puts there for the simulator - ReShade and the like, named after the system library
/// they stand in for. Windows looks in the program's own folder first, so the starter's
/// window drew through them too, and with some of them it drew nothing at all.
/// Loaded from System32 by full path before anything asks for them, these names are
/// taken: a native library that asks by name gets the system one. .NET looks beside the
/// program by full path before it asks by name, so the window code's own imports are
/// handed the same libraries. The simulator is a process of its own and still finds its
/// wrappers.
/// Elsewhere there is nothing of the kind to keep out. Under Wine or Proton the system
/// folder is the prefix's, so what is taken there is what would have been taken anyway.
/// </summary>
public sealed class SystemGraphicsLibraries
{
public delegate bool Loader(string path, out IntPtr handle);
// dxgi ahead of d3d11, which asks for it.
public static readonly IReadOnlyList<string> Names = new[] { "dxgi", "d3d11", "d3d9", "opengl32" };
private readonly Dictionary<string, IntPtr> _loaded = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _shadowed = new();
private SystemGraphicsLibraries()
{
}
/// <summary>The files of these names that lay beside the starter.</summary>
public IReadOnlyList<string> Shadowed => _shadowed;
/// <summary>What goes to the log about them, or null when none lay there.</summary>
public string? Note => _shadowed.Count > 0
? $"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", _shadowed)}"
: null;
/// <summary>The libraries of this Windows, or null on any other system.</summary>
public static SystemGraphicsLibraries? TakeOnWindows() =>
OperatingSystem.IsWindows()
? Take(Environment.SystemDirectory, AppContext.BaseDirectory, File.Exists, NativeLibrary.TryLoad)
: null;
public static SystemGraphicsLibraries Take(string systemDirectory, string ownDirectory,
Func<string, bool> exists, Loader load)
{
var taken = new SystemGraphicsLibraries();
foreach (string name in Names)
{
string file = name + ".dll";
if (exists(Path.Combine(ownDirectory, file)))
taken._shadowed.Add(file);
if (load(Path.Combine(systemDirectory, file), out IntPtr handle))
taken._loaded[name] = handle;
}
return taken;
}
/// <summary>The system library for an import of one of these names; zero leaves it to the usual search.</summary>
public IntPtr Resolve(string libraryName)
{
string name = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
? libraryName[..^4]
: libraryName;
return _loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero;
}
/// <summary>
/// The assembly's imports of these names get the system libraries. False when it
/// has a resolver of its own already; that one decides.
/// </summary>
public bool ServeTo(Assembly importer)
{
try
{
NativeLibrary.SetDllImportResolver(importer, (name, _, _) => Resolve(name));
return true;
}
catch (InvalidOperationException)
{
return false;
}
}
}

View File

@@ -23,6 +23,7 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
};
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
private readonly IGamePaths _paths;
private readonly IDiagnosticsLog _log;
@@ -38,6 +39,7 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
public FizPhysicsRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log)
{
_files = files;
_names = new CaseInsensitivePaths(files);
_paths = paths;
_log = log;
}
@@ -165,8 +167,9 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
while (i < tokens.Count && !tokens[i].Equals("end", StringComparison.OrdinalIgnoreCase))
includeParameters.Add(Resolve(tokens[i++], parameters));
Parse(physics, Path.Combine(directory, includeFile), directory, includeParameters.ToArray(),
depth + 1);
// Named in the letter case of whoever wrote the include, not always that of the file.
string included = _names.Find(directory, includeFile) ?? Path.Combine(directory, includeFile);
Parse(physics, included, directory, includeParameters.ToArray(), depth + 1);
pendingKey = null;
continue;
}

View File

@@ -10,44 +10,53 @@ public sealed class MissingAssetScanner
private static readonly string[] TextureExtensions = { ".mat", ".bmp" };
private static readonly string[] ModelExtensions = { ".t3d", ".e3d" };
private readonly IFileSystem _files;
private readonly IGamePaths _paths;
private readonly CaseInsensitivePaths _names;
public MissingAssetScanner(IFileSystem files, IGamePaths paths)
{
_files = files;
_paths = paths;
_names = new CaseInsensitivePaths(files, keepListings: true);
}
public List<string> Scan(VehicleCatalog catalog)
{
var lines = new List<string>();
foreach (var texture in catalog.Textures)
try
{
string directory = Path.Combine(
_paths.Dynamic,
texture.Directory.Replace('/', Path.DirectorySeparatorChar).TrimEnd('\\', '/'));
foreach (var texture in catalog.Textures)
{
string directory = texture.Directory.Replace('\\', '/').TrimEnd('/');
if (!string.IsNullOrEmpty(texture.Skinfile) &&
!ExistsWithAnyExtension(Path.Combine(directory, texture.Skinfile), TextureExtensions))
lines.Add($"# no file: {texture.Directory}{texture.Skinfile}");
if (!string.IsNullOrEmpty(texture.Skinfile) &&
!ExistsWithAnyExtension(Under(directory, texture.Skinfile), TextureExtensions))
lines.Add($"# no file: {texture.Directory}{texture.Skinfile}");
if (!string.IsNullOrEmpty(texture.Model) &&
!ExistsWithAnyExtension(Path.Combine(directory, texture.Model), ModelExtensions))
lines.Add($"# no model: {texture.Directory}{texture.Model}");
if (!string.IsNullOrEmpty(texture.Model) &&
!ExistsWithAnyExtension(Under(directory, texture.Model), ModelExtensions))
lines.Add($"# no model: {texture.Directory}{texture.Model}");
}
}
finally
{
// The folders are listed once for the whole catalog, and not kept past it.
_names.Forget();
}
return lines;
}
private bool ExistsWithAnyExtension(string path, string[] extensions)
private static string Under(string directory, string name) =>
directory.Length == 0 ? name : directory + "/" + name;
/// <summary>Whether the file is under dynamic as named, or with one of the extensions, in any letter case.</summary>
private bool ExistsWithAnyExtension(string name, string[] extensions)
{
if (_files.FileExists(path))
if (_names.Resolve(_paths.Dynamic, name) is not null)
return true;
foreach (string extension in extensions)
if (_files.FileExists(Path.ChangeExtension(path, extension)))
if (_names.Resolve(_paths.Dynamic, Path.ChangeExtension(name, extension)) is not null)
return true;
return false;

View File

@@ -0,0 +1,24 @@
using System.IO;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Vehicles;
namespace StarterNG.Infrastructure.Vehicles;
public static class TextureFolder
{
/// <summary>
/// A livery's folder as it is named on disk: under dynamic, or from the game's folder
/// when its name starts there, in any letter case. Where it would be when it is not there.
/// </summary>
public static string Of(IFileSystem files, IGamePaths paths, VehicleTexture texture)
{
string directory = texture.Directory.Replace('\\', '/').TrimEnd('/');
if (directory.Length == 0)
return paths.Dynamic;
var names = new CaseInsensitivePaths(files);
return names.Find(paths.Dynamic, directory, directory: true) ??
names.Find(paths.Root, directory, directory: true) ??
Path.Combine(paths.Root, directory.Replace('/', Path.DirectorySeparatorChar));
}
}

View File

@@ -110,7 +110,13 @@ public partial class MainWindow : Window
_sceneryFilesTimer.Start();
FollowLastRun();
};
Activated += (_, _) => CheckExternalSettings();
Activated += (_, _) =>
{
CheckExternalSettings();
// Back from a build or a download: a new simulator is on the list already.
if (SettingsView.IsVisible)
SettingsView.RefreshExecutables();
};
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
Closed += (_, _) => _sceneryFilesTimer.Stop();
}
@@ -521,11 +527,34 @@ public partial class MainWindow : Window
private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started";
/// <summary>
/// Tells a user whose processor lacks AVX2 that the published simulator will
/// not run, and where the instructions for a build of their own are.
/// Tells a user whose processor lacks AVX2 that the simulator that would start will
/// not run. With a build without AVX2 in the folder, chosen away from by hand, the
/// notice offers to go back to the automatic choice, which takes it; with none, it
/// says what such a build is called and where the instructions for one's own are.
/// </summary>
public async Task ShowCpuNoticeAsync()
public async Task ShowCpuNoticeAsync(string executable)
{
var services = AppServices.Current;
if (services.Executables.NewestNoAvx2() is { } noAvx2)
{
var (useIt, quiet) = await MessageBox.ShowNotice(
this, string.Format(App.Loc["CpuNoAvx2Chosen"], Path.GetFileName(executable), noAvx2),
App.Loc["CpuNoAvx2Title"], App.Loc["CpuNoAvx2UseIt"], App.Loc["DontShowAgain"]);
if (useIt)
{
services.Settings.SelectExeAutomatically = true;
services.SettingsStore.Save();
SettingsView.ReloadFromSettings();
UpdateStartButton();
}
if (quiet)
{
services.Settings.CpuNotice = false;
services.SettingsStore.Save();
}
return;
}
var (open, silence) = await MessageBox.ShowNotice(
this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"],
App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]);
@@ -623,6 +652,29 @@ public partial class MainWindow : Window
App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo))
return;
// 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 == false)
SettingsView.DiscardEdits();
else
{
SettingsView.Save();
// 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);
return;
}
}
}
LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path));
await FollowStartAsync(() => AppServices.Current.StartSimulation.Execute(freeFly, saveSettings));
@@ -722,7 +774,8 @@ public partial class MainWindow : Window
/// </summary>
private static void FollowLastRun()
{
if (AppServices.Current.Settings.PhysicsLog)
var settings = AppServices.Current.Settings;
if (settings.PhysicsLog || settings.BlackBox || settings.PhysicsLogTrains)
_ = Task.Run(AppServices.Current.Tapes.FollowLastRun);
}

View File

@@ -10,12 +10,22 @@ namespace StarterNG;
static class Program
{
private static bool _softwareRender;
[STAThread]
public static void Main(string[] args)
{
// Ahead of everything that could draw: what lies beside the starter is the simulator's.
var graphics = SystemGraphicsLibraries.TakeOnWindows();
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
_softwareRender = SoftwareRender.AskedIn(args);
// Composition root first: everything below, including the crash handlers,
// resolves its collaborators from this graph.
AppServices.Initialize();
if (graphics?.Note is { } note)
Diagnostics.Log(note);
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
@@ -63,9 +73,13 @@ static class Program
};
}
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithSoftwareRenderIfAsked()
.WithInterFont()
.WithDiagnosticsLogging()
.AfterSetup(_ => LogUiExceptions());

View File

@@ -12,7 +12,7 @@
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<!-- Major and minor only: CI adds the patch, the number of commits, so every
build of main is a higher version without anyone bumping it. -->
<VersionPrefix>1.5</VersionPrefix>
<VersionPrefix>1.6</VersionPrefix>
<AssemblyName>Starter</AssemblyName>
<Company>eu07.pl</Company>
</PropertyGroup>

View File

@@ -1,8 +1,10 @@
using System.IO;
using Avalonia.Controls;
using Avalonia.Input.Platform;
using StarterNG.Application;
using StarterNG.Domain;
using StarterNG.Domain.Vehicles;
using StarterNG.Infrastructure.Vehicles;
namespace StarterNG.Views;
@@ -17,13 +19,7 @@ internal static class TextureMenuItems
if (TopLevel.GetTopLevel(owner)?.Clipboard is { } clipboard)
await clipboard.SetTextAsync(Consist.Base(texture.Skinfile));
});
menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport(FolderOf(texture)));
}
private static string FolderOf(VehicleTexture texture)
{
string dir = Path.Combine(Directory.GetCurrentDirectory(), "dynamic",
texture.Directory.Replace('/', Path.DirectorySeparatorChar).TrimEnd('\\', '/'));
return Directory.Exists(dir) ? dir : Path.Combine(Directory.GetCurrentDirectory(), texture.Directory);
menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport(
Path.GetFullPath(TextureFolder.Of(AppServices.Current.Files, AppServices.Current.Paths, texture))));
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StarterNG.Views;
/// <summary>
/// The simulators offered in the settings after the folder was looked at again: a build
/// copied in while the starter runs joins the list, and what was chosen stays chosen, even
/// a file picked from elsewhere or one since removed - looking again never changes the choice.
/// </summary>
public static class ExecutableList
{
/// <summary>The entries that follow "automatic", and the place of <paramref name="chosen"/> among them.</summary>
/// <param name="found">The simulators in the folder now, newest first.</param>
/// <param name="chosen">The entry chosen, or null for "automatic" or nothing chosen yet.</param>
/// <returns>Entries, and the index of the chosen one in them, -1 when <paramref name="chosen"/> is null.</returns>
public static (IReadOnlyList<string> Entries, int Chosen) Refreshed(IReadOnlyList<string> found, string? chosen)
{
var entries = found.ToList();
if (chosen is null)
return (entries, -1);
int at = entries.FindIndex(entry => string.Equals(entry, chosen, StringComparison.OrdinalIgnoreCase));
if (at >= 0)
return (entries, at);
entries.Add(chosen);
return (entries, entries.Count - 1);
}
}

View File

@@ -50,6 +50,35 @@ public static class MessageBox
return yes;
}
/// <summary>
/// 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.
/// </summary>
public static async Task<bool?> 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;
}
/// <summary>
/// A notice with one action besides closing it, and a box to stop it coming
/// back, which counts however the window is closed.

View File

@@ -496,20 +496,18 @@ public partial class Scenarios : UserControl
btn.Classes.Add("Flat");
ToolTip.SetTip(btn, att.FilePath);
// A button that does nothing is no way to say the file is not there.
btn.IsEnabled = File.Exists(Path.GetFullPath(att.FilePath));
btn.IsEnabled = AppServices.Current.Attachments.Resolve(att) is not null;
ToolTip.SetShowOnDisabled(btn, true);
btn.Click += (_, _) => OpenAttachment(att.FilePath);
btn.Click += (_, _) => OpenAttachment(att);
attachmentsPanel.Children.Add(btn);
}
}
private static void OpenAttachment(string relativePath)
private static void OpenAttachment(SceneryAttachment attachment)
{
string full = Path.GetFullPath(relativePath);
if (!File.Exists(full))
full = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath));
if (!File.Exists(full))
if (AppServices.Current.Attachments.Resolve(attachment) is not { } found)
return;
string full = Path.GetFullPath(found);
try
{
Process.Start(new ProcessStartInfo(full) { UseShellExecute = true });

View File

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

View File

@@ -554,6 +554,12 @@
<ctl:SettingRow ConfigKey="livetraction" Description="{Binding [PowerOverheadLineOnlyDesc], Source={x:Static starterNg:App.Loc}}">
<CheckBox x:Name="OverheadOnlyCb" Content="{Binding [PowerOverheadLineOnly], Source={x:Static starterNg:App.Loc}}" />
</ctl:SettingRow>
<ctl:SettingRow Description="{Binding [SaveBlackBoxDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="blackbox">
<CheckBox x:Name="BlackBoxCb" Content="{Binding [SaveBlackBox], Source={x:Static starterNg:App.Loc}}" />
</ctl:SettingRow>
<ctl:SettingRow Description="{Binding [SaveTrainTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog.trains">
<CheckBox x:Name="TrainTapesCb" Content="{Binding [SaveTrainTapes], Source={x:Static starterNg:App.Loc}}" />
</ctl:SettingRow>
<ctl:SettingRow Description="{Binding [SaveSpeedometerTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog">
<CheckBox x:Name="SpeedometerTapesCb" Content="{Binding [SaveSpeedometerTapes], Source={x:Static starterNg:App.Loc}}" />
</ctl:SettingRow>

View File

@@ -105,6 +105,13 @@ public partial class Settings : UserControl, ISettingsCapture
FeedbackCb.SelectionChanged += FeedbackCb_OnSelectionChanged;
SelectExeCb.SelectionChanged += (_, _) => UpdateIdleNotes();
// Coming to the page or to the list is when a new build is looked for.
SelectExeCb.GotFocus += (_, _) => RefreshExecutables();
PropertyChanged += (_, e) =>
{
if (e.Property == IsVisibleProperty && IsVisible)
RefreshExecutables();
};
FullscreenWindowedCb.IsCheckedChanged += (_, _) => UpdateIdleNotes();
App.Loc.LanguageChanged += UpdateIdleNotes;
App.Loc.LanguageChanged += UpdateGpuNote;
@@ -235,9 +242,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;
@@ -246,16 +252,33 @@ public partial class Settings : UserControl, ISettingsCapture
private void PopulateExeCombo()
{
string? current = (SelectExeCb.SelectedItem as ComboBoxItem)?.Content?.ToString();
int index = SelectExeCb.SelectedIndex;
string? chosen = index > 0 ? (SelectExeCb.SelectedItem as ComboBoxItem)?.Content?.ToString() : null;
var (entries, at) = ExecutableList.Refreshed(AppServices.Current.Executables.ListCandidates(), chosen);
// The same files as shown: left alone, so a reader on the list hears nothing change.
var shown = SelectExeCb.Items.Skip(1).Select(item => (item as ComboBoxItem)?.Content?.ToString() ?? "");
if (SelectExeCb.Items.Count > 0 && shown.SequenceEqual(entries, StringComparer.Ordinal))
return;
SelectExeCb.Items.Clear();
SelectExeCb.Items.Add(new ComboBoxItem { Content = App.Loc["SelectEXEAuto"] });
foreach (string exe in AppServices.Current.Executables.ListCandidates())
foreach (string exe in entries)
SelectExeCb.Items.Add(new ComboBoxItem { Content = exe });
if (current is not null)
{
int idx = FindComboIndexByContent(SelectExeCb, current);
SelectExeCb.SelectedIndex = idx >= 0 ? idx : 0;
}
if (index >= 0)
SelectExeCb.SelectedIndex = at >= 0 ? at + 1 : 0;
}
/// <summary>
/// Looks at the simulator folder again, so a build copied in while the starter runs is
/// on the list without reopening anything. The choice stays as it was and is no edit:
/// nothing waits for Save after it. Not while the list is open under the user's hand.
/// </summary>
public void RefreshExecutables()
{
if (SelectExeCb.IsDropDownOpen)
return;
WhileLoading(PopulateExeCombo);
}
private async void BrowseExeButton_OnClick(object? sender, RoutedEventArgs e) =>
@@ -316,7 +339,13 @@ public partial class Settings : UserControl, ISettingsCapture
SelectExeCb.SelectedIndex = index;
}
public void ReloadFromSettings() => ApplyToUi();
/// <summary>The settings read again from the file: the page shows them, no edit of its own left.</summary>
public void ReloadFromSettings()
{
ApplyToUi();
_dirty = false;
UpdateSaveState();
}
/// <summary>
/// True while a cab-control binding is waiting for a keypress. The window's own
@@ -329,6 +358,8 @@ public partial class Settings : UserControl, ISettingsCapture
WhileLoading(() =>
{
SpeedometerTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLog;
BlackBoxCb.IsChecked = AppServices.Current.Settings.BlackBox;
TrainTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLogTrains;
SimLogsCb.IsChecked = AppServices.Current.Settings.DebugLog;
});
@@ -441,6 +472,8 @@ public partial class Settings : UserControl, ISettingsCapture
PantographBreakCb.IsChecked = s.EnableTraction;
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;
@@ -876,6 +909,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.EnableTraction = IsChecked(PantographBreakCb);
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);
@@ -1152,6 +1187,18 @@ public partial class Settings : UserControl, ISettingsCapture
Announcer.Say(this, App.Loc["SettingsRestored"]);
}
/// <summary>
/// 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.
/// </summary>
public void DiscardEdits()
{
ApplyToUi();
_keyBindings.Reload();
_dirty = false;
UpdateSaveState();
}
/// <summary>The list as <see cref="ResolutionChoices"/> has it for the monitors there are now, with the size selected.</summary>
private void SelectResolution(int width, int height)
{
@@ -1490,9 +1537,12 @@ public partial class Settings : UserControl, ISettingsCapture
UpdateSaveState();
}
/// <summary>Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells.</summary>
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;
}

View File

@@ -74,6 +74,10 @@ 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;
// the file read last, kept by the tapes to be followed even once another is picked or none is shown
private string? _read;
/// <summary>A setting went on from here; the settings page's boxes have to follow it.</summary>
public event Action? LogEnabled;
@@ -166,7 +170,12 @@ public sealed class HaslerTapeWindow : Window
Content = _view
};
_recordingOff = Strip("HaslerRecordingOff", "HaslerRecordingEnable", settings => settings.PhysicsLog = 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"]);
@@ -222,7 +231,13 @@ public sealed class HaslerTapeWindow : Window
await RefreshListAsync();
};
Activated += (_, _) => ShowWhatIsKnown();
Closed += (_, _) => _timer.Stop();
Closed += (_, _) =>
{
_closed = true;
_timer.Stop();
if (_read is { } read)
_tapes.Forget(read);
};
}
/// <summary>
@@ -232,10 +247,12 @@ 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 || settings.PhysicsLogTrains;
_recordingOff.IsVisible = !recording;
_logOff.IsVisible = recording && !settings.DebugLog;
bool canFollow = _running && _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;
@@ -641,7 +658,15 @@ 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;
_read = file.Path;
var tape = await Task.Run(() => _tapes.Load(file, follow));
if (_closed)
{
_tapes.Forget(file.Path);
return;
}
bool another = file.Path != _shown?.Path;
_shown = file;
_tapeless = null;
@@ -656,10 +681,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)
@@ -693,6 +721,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)

View File

@@ -1,3 +1,5 @@
using System;
using System.Globalization;
using Eu07.BlackBox.Views;
namespace StarterNG.Views.Tapes;
@@ -15,7 +17,14 @@ internal sealed class StarterBlackBoxStrings : IBlackBoxStrings
get
{
string text = App.Loc.Opt("BlackBox" + key);
return text.Length > 0 ? text : _own[key];
if (text.Length > 0)
return text;
// The commands in a language of the old starter's key descriptions, as the keys tab names them; in Polish
// and English the window's own.
if (key.StartsWith(DefaultBlackBoxStrings.CommandPrefix, StringComparison.Ordinal) && App.Loc.CurrentLangCode is not ("pl" or "en")
&& App.Loc.Opt(key) is { Length: > 0 } described)
return char.ToUpper(described[0], CultureInfo.CurrentCulture) + described[1..];
return _own[key];
}
}
}

View File

@@ -364,8 +364,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>
@@ -497,7 +498,11 @@
<String key="PhysicsAccuracyIncreased">Zvýšená přesnost fyziky</String>
<String key="BreakingPantographPossibility">Možnost zlomení pantografu</String>
<String key="PowerOverheadLineOnly">Napájení jen pod trolejí</String>
<String key="SaveSpeedometerTapes">Ukládat pásky rychloměru</String>
<String key="SaveBlackBox">Nahrávat černou skříňku a pásky rychloměru</String>
<String key="SaveBlackBoxDesc">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.</String>
<String key="SaveTrainTapes">Nahrávat pásky rychloměru všech vlaků</String>
<String key="SaveTrainTapesDesc">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.</String>
<String key="SaveSpeedometerTapes">Ukládat fyzikální log všech vozidel</String>
<String key="SaveSimLogs">Ukládat log simulace</String>
<String key="KeepPrevLogs">Zachovat předchozí logy</String>
<String key="DisplaySimulation">Zobrazit simulaci</String>
@@ -633,8 +638,10 @@
<String key="About">O programu</String>
<String key="Close">Zavřít</String>
<String key="CpuNoAvx2Title">Procesor bez AVX2</String>
<String key="CpuNoAvx2">Tento procesor nemá AVX2 a oficiální simulátor ho vyžaduje: nespustí se.&#10;&#10;Simulátor lze sestavit bez AVX2 (CMake -DENABLE_AVX2=OFF). Návod:&#10;{0}</String>
<String key="CpuNoAvx2">Tento procesor nemá AVX2 a oficiální simulátor ho vyžaduje: nespustí se.&#10;&#10;Existuje verze simulátoru bez AVX2 - název jejího souboru končí na _noavx2. Vložte ji do složky hry a starter ji sám použije. Simulátor lze také sestavit sám (CMake -DENABLE_AVX2=OFF). Návod:&#10;{0}</String>
<String key="CpuNoAvx2Open">Otevřít návod</String>
<String key="CpuNoAvx2Chosen">Tento procesor nemá AVX2 a zvolený simulátor {0} ho vyžaduje: nespustí se.&#10;&#10;Ve složce hry je verze bez AVX2: {1}. Automatická volba vezme právě ji.</String>
<String key="CpuNoAvx2UseIt">Volit automaticky</String>
<String key="DontShowAgain">Znovu nezobrazovat</String>
<String key="SettingsPath">Nastavení načteno z:</String>
@@ -668,6 +675,9 @@
<String key="WarehouseAppend">Připojit soupravu ze skladu</String>
<String key="WarehouseImportFile">Přidat soupravy ze souboru...</String>
<String key="StartWithoutSaving">Spustit bez uložení nastavení</String>
<String key="StartUnsavedMessage">Nastavení obsahuje neuložené změny. Uložit je před spuštěním simulátoru?</String>
<String key="StartUnsavedSave">Uložit a spustit</String>
<String key="StartUnsavedWithout">Zahodit změny a spustit</String>
<String key="StartMore">Další způsoby spuštění</String>
<String key="StartFreeFly">Spustit bez vozidla</String>
<String key="StartEditorShort">Editor scenérie</String>
@@ -783,7 +793,6 @@
<String key="SyntaxVehicleOutsideTrainset">Vozidlo {0} stojí mimo soupravu: chybí záhlaví trainset?</String>
<String key="SyntaxNotANumber">{0}: „{1}“ místo čísla</String>
<String key="SyntaxMissingInclude">Soubor {1} nenalezen (include)</String>
<String key="SyntaxIncludeLetterCase">Soubor {1} je na disku jako {0}: linuxový eu07 ho nenačte</String>
<String key="SyntaxIncludeNotClosed">include {1} bez end</String>
<String key="SyntaxTrainsetUnreadable">Soupravu {0} se nepodařilo načíst</String>
<String key="SyntaxVehicleUnreadable">Vozidlo {0} se nepodařilo načíst</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>
@@ -516,8 +517,12 @@
<String key="BreakingPantographPossibilityDesc">Disabling protects the pantograph from breaking on faulty overhead line geometry.</String>
<String key="PowerOverheadLineOnly">Powered only under overhead line</String>
<String key="PowerOverheadLineOnlyDesc">When disabled, a raised pantograph can power the vehicle even without touching the wire.</String>
<String key="SaveSpeedometerTapes">Save physics parameters log</String>
<String key="SaveSpeedometerTapesDesc">Writes a detailed trip log to the physicslog/ folder.</String>
<String key="SaveBlackBox">Record the black box and the speedometer tapes</String>
<String key="SaveBlackBoxDesc">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.</String>
<String key="SaveTrainTapes">Record the speedometer tapes of every train</String>
<String key="SaveTrainTapesDesc">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.</String>
<String key="SaveSpeedometerTapes">Save the physics log of every vehicle</String>
<String key="SaveSpeedometerTapesDesc">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.</String>
<String key="SaveSimLogs">Save simulation log</String>
<String key="KeepPrevLogs">Keep previous logs</String>
<String key="KeepPrevLogsDesc">Creates a separate log file for each scenery instead of overwriting errors.txt.</String>
@@ -659,8 +664,10 @@
<String key="About">About</String>
<String key="Close">Close</String>
<String key="CpuNoAvx2Title">Processor without AVX2</String>
<String key="CpuNoAvx2">This processor has no AVX2 and the official simulator needs it: it will not start.&#10;&#10;You can build the simulator without AVX2 (CMake -DENABLE_AVX2=OFF). Instructions:&#10;{0}</String>
<String key="CpuNoAvx2">This processor has no AVX2 and the official simulator needs it: it will not start.&#10;&#10;There is a simulator build without AVX2 - its file name ends in _noavx2. Put it in the game folder and the starter will use it. You can also build the simulator yourself (CMake -DENABLE_AVX2=OFF). Instructions:&#10;{0}</String>
<String key="CpuNoAvx2Open">Open the instructions</String>
<String key="CpuNoAvx2Chosen">This processor has no AVX2 and the chosen simulator {0} needs it: it will not start.&#10;&#10;The game folder has a build without AVX2: {1}. The automatic choice takes that one.</String>
<String key="CpuNoAvx2UseIt">Choose automatically</String>
<String key="DontShowAgain">Don't show again</String>
<String key="SettingsPath">Settings loaded from:</String>
@@ -694,6 +701,9 @@
<String key="WarehouseAppend">Append warehouse consist</String>
<String key="WarehouseImportFile">Add consists from file...</String>
<String key="StartWithoutSaving">Start without saving settings</String>
<String key="StartUnsavedMessage">The settings have unsaved changes. Save them before starting the simulator?</String>
<String key="StartUnsavedSave">Save and start</String>
<String key="StartUnsavedWithout">Discard changes and start</String>
<String key="StartMore">More ways to start</String>
<String key="StartFreeFly">Start with no vehicle</String>
<String key="StartEditorShort">Scenery editor</String>
@@ -813,7 +823,6 @@
<String key="SyntaxVehicleOutsideTrainset">Vehicle {0} stands outside a trainset: header missing?</String>
<String key="SyntaxNotANumber">{0}: “{1}” instead of a number</String>
<String key="SyntaxMissingInclude">File {1} not found (include)</String>
<String key="SyntaxIncludeLetterCase">File {1} is on disk as {0}: the Linux eu07 will not load it</String>
<String key="SyntaxIncludeNotClosed">include {1} without end</String>
<String key="SyntaxTrainsetUnreadable">Trainset {0} could not be read</String>
<String key="SyntaxVehicleUnreadable">Vehicle {0} could not be read</String>
@@ -900,8 +909,8 @@
<String key="Cmd.trainbrakecharging">train brake valve: overcharge the brake pipe</String>
<String key="Cmd.trainbrakerelease">train brake valve: running position</String>
<String key="Cmd.trainbrakefirstservice">train brake valve: first braking step</String>
<String key="Cmd.trainbrakeservice">train brake valve: full service</String>
<String key="Cmd.trainbrakefullservice">train brake valve: supplementary braking</String>
<String key="Cmd.trainbrakeservice">train brake valve: service braking</String>
<String key="Cmd.trainbrakefullservice">train brake valve: full service</String>
<String key="Cmd.trainbrakehandleoff">train brake valve: lap position</String>
<String key="Cmd.trainbrakeemergency">emergency braking</String>
<String key="Cmd.trainbrakebasepressureincrease">raise the brake pipe pressure level</String>
@@ -1011,7 +1020,7 @@
<String key="Cmd.interiorlightdimtoggle">toggle cab light dimming</String>
<String key="Cmd.compartmentlightstoggle">toggle the compartment lights</String>
<String key="Cmd.instrumentlighttoggle">toggle the instrument lights</String>
<String key="Cmd.dashboardlighttoggle">toggle the desk lights</String>
<String key="Cmd.dashboardlighttoggle">toggle the dashboard light</String>
<String key="Cmd.timetablelighttoggle">toggle the timetable light</String>
<String key="Cmd.generictoggle0">generic switch 0</String>
<String key="Cmd.generictoggle1">generic switch 1</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>
@@ -497,7 +498,11 @@
<String key="PhysicsAccuracyIncreased">Növelt fizikai pontosság</String>
<String key="BreakingPantographPossibility">Áramszedő törésének lehetősége</String>
<String key="PowerOverheadLineOnly">Táplálás csak felsővezeték alatt</String>
<String key="SaveSpeedometerTapes">Sebességmérő-szalagok mentése</String>
<String key="SaveBlackBox">Fekete doboz és sebességmérő-szalagok rögzítése</String>
<String key="SaveBlackBoxDesc">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.</String>
<String key="SaveTrainTapes">Minden vonat sebességmérő-szalagjának rögzítése</String>
<String key="SaveTrainTapesDesc">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.</String>
<String key="SaveSpeedometerTapes">Minden jármű fizikai naplójának mentése</String>
<String key="SaveSimLogs">Szimulációs napló mentése</String>
<String key="KeepPrevLogs">Korábbi naplók megtartása</String>
<String key="DisplaySimulation">Szimuláció megjelenítése</String>
@@ -633,8 +638,10 @@
<String key="About">Névjegy</String>
<String key="Close">Bezárás</String>
<String key="CpuNoAvx2Title">AVX2 nélküli processzor</String>
<String key="CpuNoAvx2">Ez a processzor nem tudja az AVX2-t, a hivatalos szimulátornak pedig kell: nem indul el.&#10;&#10;A szimulátor lefordítható AVX2 nélkül (CMake -DENABLE_AVX2=OFF). Útmutató:&#10;{0}</String>
<String key="CpuNoAvx2">Ez a processzor nem tudja az AVX2-t, a hivatalos szimulátornak pedig kell: nem indul el.&#10;&#10;Van AVX2 nélküli szimulátor-változat - a fájl neve _noavx2-re végződik. Tegye a játék mappájába, és az indító magától azt használja. A szimulátor saját maga is lefordítható (CMake -DENABLE_AVX2=OFF). Útmutató:&#10;{0}</String>
<String key="CpuNoAvx2Open">Útmutató megnyitása</String>
<String key="CpuNoAvx2Chosen">Ez a processzor nem tudja az AVX2-t, a kiválasztott {0} szimulátornak pedig kell: nem indul el.&#10;&#10;A játék mappájában van AVX2 nélküli változat: {1}. Az automatikus választás ezt veszi.</String>
<String key="CpuNoAvx2UseIt">Automatikus választás</String>
<String key="DontShowAgain">Ne mutasd többé</String>
<String key="SettingsPath">Beállítások betöltve innen:</String>
@@ -668,6 +675,9 @@
<String key="WarehouseAppend">Raktári szerelvény hozzáfűzése</String>
<String key="WarehouseImportFile">Szerelvények hozzáadása fájlból...</String>
<String key="StartWithoutSaving">Indítás a beállítások mentése nélkül</String>
<String key="StartUnsavedMessage">A beállításokban nem mentett módosítások vannak. Menti őket a szimulátor indítása előtt?</String>
<String key="StartUnsavedSave">Mentés és indítás</String>
<String key="StartUnsavedWithout">Módosítások elvetése és indítás</String>
<String key="StartMore">További indítási módok</String>
<String key="StartFreeFly">Indítás jármű nélkül</String>
<String key="StartEditorShort">Pályaszerkesztő</String>
@@ -783,7 +793,6 @@
<String key="SyntaxVehicleOutsideTrainset">A(z) {0} jármű szerelvényen kívül áll: hiányzik a trainset fejléc?</String>
<String key="SyntaxNotANumber">{0}: „{1}” szám helyett</String>
<String key="SyntaxMissingInclude">A(z) {1} fájl nem található (include)</String>
<String key="SyntaxIncludeLetterCase">A(z) {1} fájl a lemezen {0} néven van: a linuxos eu07 nem tölti be</String>
<String key="SyntaxIncludeNotClosed">include {1} end nélkül</String>
<String key="SyntaxTrainsetUnreadable">A(z) {0} szerelvényt nem sikerült beolvasni</String>
<String key="SyntaxVehicleUnreadable">A(z) {0} járművet nem sikerült beolvasni</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>
@@ -516,8 +517,12 @@
<String key="BreakingPantographPossibilityDesc">Wyłączenie chroni pantograf przed uszkodzeniem przy błędnej geometrii sieci.</String>
<String key="PowerOverheadLineOnly">Zasilanie tylko pod siecią trakcyjna</String>
<String key="PowerOverheadLineOnlyDesc">Gdy wyłączone, podniesiony pantograf zasila pojazd nawet bez kontaktu z drutem.</String>
<String key="SaveSpeedometerTapes">Zapisuj log parametrów fizycznych</String>
<String key="SaveSpeedometerTapesDesc">Zapisuje szczegółowy log jazdy do folderu physicslog/.</String>
<String key="SaveBlackBox">Zapisuj czarną skrzynkę i taśmy prędkościomierza</String>
<String key="SaveBlackBoxDesc">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ś.</String>
<String key="SaveTrainTapes">Zapisuj taśmy prędkościomierza wszystkich pociągów</String>
<String key="SaveTrainTapesDesc">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.</String>
<String key="SaveSpeedometerTapes">Zapisuj log parametrów fizycznych wszystkich pojazdów</String>
<String key="SaveSpeedometerTapesDesc">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.</String>
<String key="SaveSimLogs">Zapisuj log z symulacji</String>
<String key="KeepPrevLogs">Zachowuj poprzednie logi</String>
<String key="KeepPrevLogsDesc">Tworzy osobny plik logu dla każdej scenerii zamiast nadpisywać errors.txt.</String>
@@ -659,8 +664,10 @@
<String key="About">O programie</String>
<String key="Close">Zamknij</String>
<String key="CpuNoAvx2Title">Procesor bez AVX2</String>
<String key="CpuNoAvx2">Ten procesor nie ma AVX2, a oficjalny symulator go wymaga: nie uruchomi się.&#10;&#10;Można zbudować symulator bez AVX2 (CMake -DENABLE_AVX2=OFF). Instrukcja:&#10;{0}</String>
<String key="CpuNoAvx2">Ten procesor nie ma AVX2, a oficjalny symulator go wymaga: nie uruchomi się.&#10;&#10;Istnieje wersja symulatora bez AVX2 - nazwa jej pliku kończy się na _noavx2. Umieść ją w folderze gry, a starter sam jej użyje. Można też zbudować symulator samemu (CMake -DENABLE_AVX2=OFF). Instrukcja:&#10;{0}</String>
<String key="CpuNoAvx2Open">Otwórz instrukcję</String>
<String key="CpuNoAvx2Chosen">Ten procesor nie ma AVX2, a wybrany symulator {0} go wymaga: nie uruchomi się.&#10;&#10;W folderze gry jest wersja bez AVX2: {1}. Wybór automatyczny weźmie właśnie ją.</String>
<String key="CpuNoAvx2UseIt">Wybieraj automatycznie</String>
<String key="DontShowAgain">Nie pokazuj więcej</String>
<String key="SettingsPath">Lokalizacja wczytanych ustawień:</String>
@@ -694,6 +701,9 @@
<String key="WarehouseAppend">Dołącz skład z magazynu</String>
<String key="WarehouseImportFile">Dodaj składy z pliku...</String>
<String key="StartWithoutSaving">Uruchom bez zapisu ustawień</String>
<String key="StartUnsavedMessage">Ustawienia mają niezapisane zmiany. Zapisać je przed uruchomieniem symulatora?</String>
<String key="StartUnsavedSave">Zapisz i uruchom</String>
<String key="StartUnsavedWithout">Odrzuć zmiany i uruchom</String>
<String key="StartMore">Inne sposoby uruchomienia</String>
<String key="StartFreeFly">Uruchom bez pojazdu</String>
<String key="StartEditorShort">Edytor scenerii</String>
@@ -810,7 +820,6 @@
<String key="SyntaxVehicleOutsideTrainset">Pojazd {0} stoi poza składem: brak nagłówka trainset?</String>
<String key="SyntaxNotANumber">{0}: „{1}” zamiast liczby</String>
<String key="SyntaxMissingInclude">Brak pliku {1} (include)</String>
<String key="SyntaxIncludeLetterCase">Plik {1} jest na dysku jako {0}: linuksowy eu07 go nie wczyta</String>
<String key="SyntaxIncludeNotClosed">include {1} bez end</String>
<String key="SyntaxTrainsetUnreadable">Nie udało się odczytać składu {0}</String>
<String key="SyntaxVehicleUnreadable">Nie udało się odczytać pojazdu {0}</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>
@@ -497,7 +498,11 @@
<String key="PhysicsAccuracyIncreased">Повышенная точность физики</String>
<String key="BreakingPantographPossibility">Возможность излома пантографа</String>
<String key="PowerOverheadLineOnly">Питание только под контактной сетью</String>
<String key="SaveSpeedometerTapes">Сохранять ленты скоростемера</String>
<String key="SaveBlackBox">Записывать чёрный ящик и ленты скоростемера</String>
<String key="SaveBlackBoxDesc">Записывает поездку в один файл в папке physicslog/ и по ходу, каждые 2 с, сохраняет ленты (.dat) тех единиц, в которых вы находитесь.</String>
<String key="SaveTrainTapes">Записывать ленты скоростемера всех поездов</String>
<String key="SaveTrainTapesDesc">По ходу, каждые 2 с, сохраняет ленты (.dat) каждого поезда сценария в папку physicslog/: по одной на машиниста рельсового состава, без автомобилей и пассажиров. Гораздо меньше файлов, чем физический журнал каждой единицы.</String>
<String key="SaveSpeedometerTapes">Сохранять физический лог всех единиц</String>
<String key="SaveSimLogs">Сохранять журнал симуляции</String>
<String key="KeepPrevLogs">Сохранять предыдущие журналы</String>
<String key="DisplaySimulation">Показывать симуляцию</String>
@@ -633,8 +638,10 @@
<String key="About">О программе</String>
<String key="Close">Закрыть</String>
<String key="CpuNoAvx2Title">Процессор без AVX2</String>
<String key="CpuNoAvx2">Этот процессор не поддерживает AVX2, а официальному симулятору он нужен: симулятор не запустится.&#10;&#10;Можно собрать симулятор без AVX2 (CMake -DENABLE_AVX2=OFF). Инструкция:&#10;{0}</String>
<String key="CpuNoAvx2">Этот процессор не поддерживает AVX2, а официальному симулятору он нужен: симулятор не запустится.&#10;&#10;Есть версия симулятора без AVX2 - имя её файла оканчивается на _noavx2. Положите её в папку игры, и стартер сам её использует. Симулятор можно также собрать самому (CMake -DENABLE_AVX2=OFF). Инструкция:&#10;{0}</String>
<String key="CpuNoAvx2Open">Открыть инструкцию</String>
<String key="CpuNoAvx2Chosen">Этот процессор не поддерживает AVX2, а выбранному симулятору {0} он нужен: он не запустится.&#10;&#10;В папке игры есть версия без AVX2: {1}. Автоматический выбор возьмёт именно её.</String>
<String key="CpuNoAvx2UseIt">Выбирать автоматически</String>
<String key="DontShowAgain">Больше не показывать</String>
<String key="SettingsPath">Настройки загружены из:</String>
@@ -668,6 +675,9 @@
<String key="WarehouseAppend">Присоединить состав со склада</String>
<String key="WarehouseImportFile">Добавить составы из файла...</String>
<String key="StartWithoutSaving">Запустить без сохранения настроек</String>
<String key="StartUnsavedMessage">В настройках есть несохранённые изменения. Сохранить их перед запуском симулятора?</String>
<String key="StartUnsavedSave">Сохранить и запустить</String>
<String key="StartUnsavedWithout">Отменить изменения и запустить</String>
<String key="StartMore">Другие способы запуска</String>
<String key="StartFreeFly">Запустить без транспорта</String>
<String key="StartEditorShort">Редактор сценария</String>
@@ -783,7 +793,6 @@
<String key="SyntaxVehicleOutsideTrainset">Транспорт {0} стоит вне состава: нет заголовка trainset?</String>
<String key="SyntaxNotANumber">{0}: «{1}» вместо числа</String>
<String key="SyntaxMissingInclude">Файл {1} не найден (include)</String>
<String key="SyntaxIncludeLetterCase">Файл {1} на диске назван {0}: eu07 на Linux его не загрузит</String>
<String key="SyntaxIncludeNotClosed">include {1} без end</String>
<String key="SyntaxTrainsetUnreadable">Не удалось прочитать состав {0}</String>
<String key="SyntaxVehicleUnreadable">Не удалось прочитать единицу {0}</String>