Compare commits

..

57 Commits

Author SHA1 Message Date
dd25372bd0 Merge pull request #60 from MaSzyna-EU07/feat/settings-standard-mode
feat(settings): standard mode, consist minis, scenery and map fixes
2026-11-23 17:07:07 +00:00
maj00r
5d8790301d Merge branch 'main' into feat/settings-standard-mode
# Conflicts:
#	StarterNG/Views/Settings.axaml.cs
2026-11-23 17:41:33 +01:00
e0d3988d4a Merge pull request #58 from MaSzyna-EU07/chore/net10
build: the starter, the black box and the tests move to .NET 10
2026-11-23 16:37:41 +00:00
57821887e4 Merge pull request #57 from MaSzyna-EU07/feat/sbt-cleanup
Feat/sbt cleanup
2026-11-23 16:37:28 +00:00
maj00r
900161a6c4 fix(sceneries): an .sbt goes only when every scenery reading it can do without
With an .sbt there the simulator passes over the triangles and lines of every
file of the scenery, so a scenery file (.scm, .scn) that is gone keeps the
.sbt whatever its name, not only one named *_ter.scm. A small terrain file is
read too: some only list the files that hold the terrain. Node templates
(.inc) still do not count.

A word reading "terrain" outside a directive - the name of a node, of a
texture - no longer hides the includes after it.

An .sbt is judged by all the sceneries reading it: the one it is named after,
that one with a $ ahead of its name, and any other naming it in a terrain
directive. What such a scenery lacks comes with its name.

Each file is read once for a cleanup, however many sceneries include it, and
only around the words that matter: on an installation of 180 sceneries the
cleanup at the first start took minutes and takes seconds.
2026-11-22 15:30:51 +01:00
maj00r
5ec7a4b539 fix(settings): a borderless screen draws into a buffer of the monitor's size, not the resolution row's
With fullscreenwindowed the simulator takes the window's size from the monitor and leaves width and height unread (application.cpp), but its full renderer still draws into gfx.framebuffer.width and height (opengl33renderer.cpp). Those were written from the resolution row, greyed out in that mode: 1280x720 stretched over a larger monitor. Borderless, they are now -1, the simulator's own word for a buffer of the window's size, or with a smaller render scale that part of the chosen monitor's size, the primary one's when none is chosen. A size left in a borderless file goes on the next save.
2026-11-22 14:53:18 +01:00
maj00r
d429d041ff fix(settings): a monitor's name outside ASCII is written as the UTF-8 the simulator compares
The simulator compares the word after fullscreenmonitor byte by byte with GLFW's name of the monitor, which is UTF-8 (application.cpp, find_monitor), and has no other way to name one. eu07.ini is written in code page 1250, so a name with a letter outside ASCII never matched and the game opened on the primary monitor. That one word now goes into the file as its UTF-8 bytes, the rest staying in the code page; a name an earlier save left in the code page is read as it is and put right by the next save.
2026-11-22 14:52:51 +01:00
maj00r
f7a58e8431 fix(settings): the move to the standard mode puts the render scale back with the frame buffer
The row of the render scale, which only the advanced mode shows, has the keys of the frame buffer's size, while the scale itself is read from starter.bufferscale: put back without it, the two came out as they were, and a player moved to the standard mode kept a blurred picture with no setting for it on the screen. The percent now goes wherever the buffer's size does, on the move, on leaving the advanced mode and on a section put back.
2026-11-22 14:51:59 +01:00
maj00r
77b0c23cea fix(settings): the cursor's speed is read and written as the old starter did, its four levels
The old starter (src/uSettings.pas) showed a mousescale as one of four levels - low below 1.3, high above 1.9, very high above 2.7, standard between - and wrote 1.0, 1.5, 2.3 or 3.2 for them, with 0.5 after it, the signs being the inversions. The slider had three whole steps instead, so a 3.2 was the top only by rounding and anything above 3 was cut to 3 on the move to the standard mode.
2026-11-22 14:47:05 +01:00
maj00r
de4eb99ea1 docs(readme): a native build needs the .NET 10 SDK 2026-11-22 13:00:10 +01:00
maj00r
34beec588d fix(settings): an import or a profile keeps the mode, the move keeps the card and GLES
Importing an eu07.ini or applying a profile took starter.settings.standard and
starter.settings.advanced from the other file. An older one says "standard no",
so the next start moved the player again and reset what was just imported, this
time with no copy kept; "advanced yes" opened the advanced mode past the
warning. Both are now this installation's, like its simulator and its card.

The one-time move to the standard mode no longer resets starter.gpu and
gfx.usegles: some machines run the simulator only on the integrated card or
with OpenGL ES, and the move is done without asking.
2026-11-22 12:40:46 +01:00
maj00r
bc4adfe6fa perf(blackbox): the map's marks thin out where they crowd, the most telling kept
From afar the signals, stop and horn points, signal passings and vehicles of a
scenery covered each other. Each now takes a square of a few pixels, asked for
in the order of what it tells - a signal at stop, a missed stop, a horn not
sounded, the user's train - so a crowd shows its most telling mark on top, and
close up, where they stand apart, every one is drawn. The stop wedges show only
close enough to tell apart.
2026-11-22 12:40:45 +01:00
maj00r
c70fd94783 fix(sonar): numbers read from the file are compared within a tolerance
Equals is as exact as == to SonarCloud (S1244). Two numbers count as the
same within a billionth of the larger one, and mousescale's second number
as 0.5 within a billionth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:14:49 +01:00
maj00r
5d966be11c fix(sonar): no exact float compares, xrandr from its own path, its regexes timed
The quality gate of SonarCloud stopped on three exact compares of doubles
(S1244), the regexes reading xrandr without a timeout (S6444) and xrandr run
from whatever PATH finds (S4036). The compares meant to tell one number from
another keep doing so with Equals; the scroll lane's margin is compared within
a tenth of a pixel. xrandr is run from where distributions put it, or not at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:11:28 +01:00
maj00r
93f914c868 feat(settings): a standard mode as the old starter's panel, the rest behind a warning
The settings keep only the keys master reads, Vulkan left out. The standard
mode is the old starter's panel; the advanced mode opens behind a warning
whose yes takes a click only after 20 seconds in front of the player.

- Sliders go by fixed steps (SliderRanges), held to the standard ranges there:
  fpslimit up to 240, sleeperdistance up to 1000 m.
- On the first start everyone is moved to the standard mode once: what is
  outside it goes back to its default, the sliders' values to their ranges,
  and a copy of eu07.ini is kept as eu07.ini.before-standard.
- "Restore defaults" puts every setting back, the language, the simulator,
  the UART port and the control keys kept.
- Monitors and renderers are found anew (Monitors, Renderers), Displays and
  SettingReach gone.
- mousescale writes its second number as the old starter did, 0.5 or -0.5
  for an inverted vertical axis; an axis that would not move gets the default.
- Depot, in the standard mode: no AI or drivable-only filters, empty consists
  not listed, the crew shown but not changed.
- Randomizing the textures of a whole scenery no longer rebuilds the view per
  consist, and finds its candidates by mini, so the window keeps answering.
- A long operator in the vehicle list is cut short instead of over the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:29 +01:00
maj00r
de943cf461 perf(blackbox): the map draws its rails by cells in view, at a detail its zoom needs
The tracks are cut into 500 m cells, so only those in view are drawn, and kept
at a few levels of detail, so that from afar a track is drawn with fewer points
than the pixels it covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:20 +01:00
maj00r
e63aa71bf8 fix(scenery): a vehicle without its .fiz is a fault, an include ending the file is read
A vehicle whose .fiz is not in its folder under dynamic is left out by the
simulator, so its trainset runs short: the scenery check now names the
missing file. An include that is the last thing in the file, with no end,
is inlined as the simulator reads it, and still reported as not closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:20 +01:00
maj00r
ecf3067d85 feat(consists): the consist lists show the vehicles' minis, alike ones under one caption
The scenery's consists and the warehouse's are listed as a strip of minis at
their own 30 px, vehicles alike next to each other taken together under one
caption ("412W ×20"). A consist wider than the list scrolls sideways in its
row, with a lane for the bar under the captions. A warehouse consist's strip
follows an edit as soon as it is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 22:47:39 +01:00
maj00r
4b3ee43e4a build: the starter, the black box and the tests move to .NET 10
.NET 9 was a short-term release and its support has ended; .NET 10 is the
long-term one. Avalonia 12 already ships a build for net10.0, the other
packages run on it as they are. CI sets up the 10.0 SDK, and Rider's publish
configurations point at the new output folder.
2026-11-18 13:04:13 +01:00
maj00r
7e249a7a9a fix(settings): a first start has nothing to save before the simulator starts
With no eu07.ini of the player's own, starting the simulator asked to save
changes nobody made. The UART tune box and the Vulkan device box went by
TextChanged, which Avalonia raises later from the dispatcher: the text the
page put there while loading came back as an edit once the window was shown.

Both now go by their Text property, which changes at once and is passed over
while the page loads; typing in them still counts.
2026-11-17 22:14:45 +01:00
maj00r
97a2c2c75c fix(sceneries): an .sbt in the way of terrain files that are there can go
Any terrain directive kept the scenery's .sbt, as if it brought the terrain
from elsewhere. The directive names either .sbt files, which nothing makes
again, or terrain files (.txtf) with their binary copies (.btf). A scenery
with the terrain files has no use for its own .sbt: the simulator never
writes one for it, and an old one keeps the terrain files from being used.

- An .sbt named by the directive still keeps the scenery's own.
- A .txtf, or its .btf, on disk lets the scenery's .sbt go; with neither,
  the .sbt stays and the missing .txtf is given as the reason.
2026-11-17 22:14:45 +01:00
maj00r
943b855f20 feat(warehouse): the old starter's magazyn.ini joins the warehouse at every start
The old starter read starter\magazyn.ini each time it opened and wrote it on
every change; this one kept its warehouse apart and took the file in only from
the list's menu, so a consist saved there never showed here.

- At the start, ahead of the scenery list, the consists of magazyn.ini not
  taken in before join the warehouse. Each one taken is remembered in
  userpresets.json by its name and vehicles, so one removed here stays removed
  while the old starter keeps it as it was.
- A consist changed there replaces the one here when that one is as an earlier
  start brought it; one of the same name made here stays, and the old one comes
  in beside it as "name (magazyn.ini)".
- A warehouse file that cannot be read is left alone by the import.
- The file is read as UTF-8 or code page 1250, whichever it is, by hand too.
2026-11-17 14:55:04 +01:00
maj00r
797e2e70a7 feat(sceneries): a release clears the .sbt files once, and a scenery's menu deletes its own
The simulator makes a scenery's .sbt on its first load and never checks it
against the text again, so an older simulator's file, or one made before a
scenery update, keeps showing the old terrain.

- CleanupGeneration, raised by a release, clears the .sbt files once per
  installation on the first start, ahead of the scenery list. A file goes only
  while its scenery's terrain files (*_ter.scm) are all there and no terrain
  directive brings terrain from elsewhere; an .sbt standing in for missing
  terrain stays, and the log says what is missing. Which cleanup each
  installation had is kept in sbt-cleanup.txt in the user's folder.
- "Delete SBT" in the scenery list's menu does the same for one scenery,
  asking first and refusing where nothing could make the file again.
- The .sbt is among the files a scenery is watched by, so one made or removed
  reaches the list without a reload.
2026-11-17 02:15:45 +01:00
c07ed2fb4d Merge pull request #54 from MaSzyna-EU07/feat/tapes-from-blackbox
feat(tapes): tapes from the black box, live view that keeps up, train tapes setting
2026-11-16 16:00:52 +00:00
cfea240243 Merge pull request #53 from MaSzyna-EU07/fix/scenery-file-events
fix: scenery files are looked at when they change, not every two seconds
2026-11-16 16:00:36 +00:00
maj00r
f0fa2d1768 test(tapes): the tapes window, the choice asked before a start, the wheels and the doors from the other cab
- HaslerTapeWindow: with nothing recorded it offers to record and turns on the
  black box and the trains' tapes; a tape of the last launch is summed up with
  its scenario and train, and is no longer followed once the window closes.
- HaslerTapes.Load: a log begun anew over the end that was read is read whole
  once its time goes back; an unreadable tape is none and told in the log; a
  file read only forward is read whole each time. Empty log lines are passed over.
- MessageBox.Choose: the answer clicked, or none on the way back or on closing.
- CabPanel: wheels turning apart from the train are said beside its speed.
- EventList: going to the other cab tells nothing of the doors, still the switches.
- WarehouseEditTests and ConsistOrientationTests put in app-wide services of
  their own: they now wait their turn with the controls that read them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:58:31 +01:00
maj00r
2a85ca384a refactor(scenery): the looks at the scenery files timed by a class of their own, under test
When the main window looks at the scenery files - once the reports of a
save stop, back at the window, now and then anyway, seldom where the
system reports changes and often where it does not - is FolderLooks now,
on TimeProvider timers, so the tests drive the clock. The window keeps
only the look itself. A report coming as the window closes leaves the
disposed timers be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:55:22 +01:00
maj00r
fa8ae760e1 fix(tests): the black box text tests wait their turn with the other Avalonia ones
EventTextsTests and SecurityBrakingTests from #55 ran beside the Avalonia
controls collection; their AppBuilder setup raced it and 28 UI tests failed
with "Setup was already called" on every runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:42:56 +01:00
maj00r
100bbea83e fix(tests): the black box text tests wait their turn with the other Avalonia ones
EventTextsTests and SecurityBrakingTests from #55 ran beside the Avalonia
controls collection; their AppBuilder setup raced it and 28 UI tests failed
with "Setup was already called" on every runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:42:56 +01:00
maj00r
195f358e55 refactor(tapes): the line of a tape drawn by a class of its own, so Sonar sees a figure ended after a gap
Sonar (S2583, the reliability rating of #54) took the end of a figure after a gap in Trace for code
never run: begun was changed by the local function Flush, and its analysis doesn't follow a local
changed that way. Nothing was wrong in what was drawn.

The columns of the line are kept by ColumnLine, in its fields, and drawn through the three calls it is
given, the figure begun, a line to the next point and its end; Trace hands it those of the
StreamGeometry. What is drawn is the same. Tests: a column entered where it started and left where it
ended through its lowest and highest, a break ending the figure and the next point beginning another,
a break with nothing drawn ending nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:06:58 +01:00
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
maj00r
c370d1509e Merge main into fix/scenery-file-events
Conflict in MainWindow.axaml.cs, the Activated handler: main (#52) refreshes the list of simulators when
the settings are shown, this branch looks at the scenery files through _sceneryLook. Both kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:02:45 +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
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
31fc4c3fdc fix: scenery files are looked at when they change, not every two seconds
The starter compared every file of every scenery each two seconds: on a full
installation 175 sceneries and 378 files, 15-18 ms a look, thirty looks a
minute with nothing changed. The system now reports changes in the scenery
folder and a look follows once the burst of a save has passed, 400 ms after
the last report.

The reports are only a hint. A look still comes on coming back to the window
and right after the simulator or its editor closes, and every 30 seconds
anyway, for network drives, Wine and Linux past its limit of watches, where
reports may not come. Where the folder cannot be watched at all the look
stays every two seconds as before. A change reported during a look is not
lost: one more look follows it.
2026-11-15 21:18:20 +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
123 changed files with 7898 additions and 3838 deletions

View File

@@ -51,10 +51,10 @@ jobs:
with:
persist-credentials: false
- name: Setup .NET 9
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
- name: Test
run: >
@@ -141,10 +141,10 @@ jobs:
with:
persist-credentials: false
- name: Setup .NET 9
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
# NativeAOT on Linux needs a native compiler/linker toolchain.
- name: Install NativeAOT dependencies

View File

@@ -61,10 +61,10 @@ jobs:
fetch-depth: 0
persist-credentials: false
- name: Setup .NET 9
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
- name: Restore tools
run: dotnet tool restore

View File

@@ -3,7 +3,7 @@
command line, or one picked. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>

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

@@ -3,7 +3,7 @@
only, no XAML loaded at run time, so it goes through NativeAOT and trimming
in the starter and in the viewer alike. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>

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

@@ -25,8 +25,12 @@ public sealed class MapView : Control
private Recording? _recording;
private int _builtRevision = -1;
private int _builtTracks = -1;
private StreamGeometry? _tracks;
private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new();
private TrackLayer? _tracks;
private readonly List<(int Index, int Branch, IReadOnlyList<System.Numerics.Vector3> Points)> _switchWays = new();
// The switches as they lay when last drawn, and their ways in two geometries: not taken, taken.
private int[] _switchStates = Array.Empty<int>();
private StreamGeometry? _waysOff, _waysOn;
private string? _hoverShown;
private readonly StreamGeometry?[] _trail = new StreamGeometry?[5];
private Rect _world;
@@ -135,33 +139,24 @@ public sealed class MapView : Control
{
_builtTracks = recording.Tracks.Count;
_switchWays.Clear();
var tracks = new StreamGeometry();
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
using (var g = tracks.Open())
foreach (var track in recording.Tracks)
{
foreach (var track in recording.Tracks)
if (track.Points.Count < 2)
continue;
foreach (var p in track.Points)
{
if (track.Points.Count < 2)
continue;
foreach (var p in track.Points)
{
left = Math.Min(left, -p.X);
right = Math.Max(right, -p.X);
top = Math.Min(top, -p.Z);
bottom = Math.Max(bottom, -p.Z);
}
if (track.Kind == TrackKind.SwitchBranch)
{
var way = new StreamGeometry();
using (var w = way.Open())
Polyline(w, track.Points);
_switchWays.Add((track.Index, track.Branch, way));
}
else
Polyline(g, track.Points);
left = Math.Min(left, -p.X);
right = Math.Max(right, -p.X);
top = Math.Min(top, -p.Z);
bottom = Math.Max(bottom, -p.Z);
}
if (track.Kind == TrackKind.SwitchBranch)
_switchWays.Add((track.Index, track.Branch, track.Points));
}
_tracks = tracks;
_tracks = new TrackLayer(recording.Tracks);
_switchStates = Array.Empty<int>();
_waysOff = _waysOn = null;
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
}
BuildTrail(recording);
@@ -247,29 +242,26 @@ public sealed class MapView : Control
double pixel = 1 / _scale;
using (context.PushTransform(toScreen))
{
// The tracks on a dark casing, so they stand out where they cross and run close.
// The tracks on a dark casing, so they stand out where they cross and run close. Only the
// cells in view, at the detail a pixel can show.
var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round);
if (_tracks is not null)
context.DrawGeometry(null, casing, _tracks);
foreach (var (_, _, way) in _switchWays)
context.DrawGeometry(null, casing, way);
if (_tracks is not null)
context.DrawGeometry(null, new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round), _tracks);
var off = new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round);
var on = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
// The ways not taken under those taken.
foreach (var (index, branch, way) in _switchWays)
var fill = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
if (_tracks is { } layer)
{
int state = recording.SwitchAt(index, _time);
if (state >= 0 && state != branch)
context.DrawGeometry(null, off, way);
}
foreach (var (index, branch, way) in _switchWays)
{
int state = recording.SwitchAt(index, _time);
if (state < 0 || state == branch)
context.DrawGeometry(null, on, way);
var view = PlaneInView(size, 6 * pixel);
int level = TrackLayer.LevelFor(_scale);
foreach (var cell in layer.CellsIn(view, level))
context.DrawGeometry(null, casing, cell.Casing);
foreach (var cell in layer.CellsIn(view, level))
if (cell.Fill is { } tracks)
context.DrawGeometry(null, fill, tracks);
}
// The ways not taken under those taken, each set one geometry, made again only when a switch moves.
UpdateSwitchWays(recording);
if (_waysOff is not null)
context.DrawGeometry(null, new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round), _waysOff);
if (_waysOn is not null)
context.DrawGeometry(null, fill, _waysOn);
// The way the train went, in the colour of the judgement.
for (int kind = 0; kind < _trail.Length; kind++)
if (_trail[kind] is { } trail)
@@ -280,12 +272,67 @@ public sealed class MapView : Control
DrawHornPoints(context, recording);
DrawSignals(context, recording);
DrawPassings(context, recording);
DrawVehicles(context, recording);
// Once a frame: the vehicles and the hover both go by them.
var vehicles = recording.VehiclesAt(_time);
DrawVehicles(context, recording, vehicles);
DrawUserTrain(context, recording);
DrawCamera(context, recording);
DrawScale(context, size);
DrawLegend(context, size);
DrawHover(context, recording);
DrawHover(context, recording, vehicles);
}
/// <summary>The part of the map's plane on screen, with a margin in plane units.</summary>
private Rect PlaneInView(Size size, double margin)
{
double halfWidth = size.Width / 2 / _scale, halfHeight = size.Height / 2 / _scale;
return new Rect(-_centerX - halfWidth - margin, -_centerZ - halfHeight - margin,
2 * (halfWidth + margin), 2 * (halfHeight + margin));
}
private void UpdateSwitchWays(Recording recording)
{
bool changed = _switchStates.Length != _switchWays.Count;
if (changed)
_switchStates = new int[_switchWays.Count];
for (int i = 0; i < _switchWays.Count; i++)
{
int state = recording.SwitchAt(_switchWays[i].Index, _time);
if (state != _switchStates[i] || changed)
{
_switchStates[i] = state;
changed = true;
}
}
if (!changed && (_waysOff is not null || _waysOn is not null || _switchWays.Count == 0))
return;
var off = new StreamGeometry();
var on = new StreamGeometry();
bool anyOff = false, anyOn = false;
using (var gOff = off.Open())
using (var gOn = on.Open())
{
for (int i = 0; i < _switchWays.Count; i++)
{
var (_, branch, points) = _switchWays[i];
if (points.Count < 2)
continue;
int state = _switchStates[i];
if (state >= 0 && state != branch)
{
Polyline(gOff, points);
anyOff = true;
}
else
{
Polyline(gOn, points);
anyOn = true;
}
}
}
_waysOff = anyOff ? off : null;
_waysOn = anyOn ? on : null;
}
private bool Visible(Point p, double margin = 20) =>
@@ -295,15 +342,24 @@ public sealed class MapView : Control
{
double radius = _scale > 0.5 ? 4.5 : _scale > 0.1 ? 3.5 : 2.5;
var outline = new Pen(Palette.Background, 1);
// From afar a station's signals are one crowd: one dot to a few pixels, those at stop kept first.
var marks = new List<(AspectChange? Aspect, Point At, int Rank)>();
foreach (var signal in recording.Signals)
{
var p = ToScreen(signal.Position.X, signal.Position.Z);
if (!Visible(p))
continue;
context.DrawEllipse(Palette.Of(recording.AspectAt(signal.Index, _time)), outline, p, radius, radius);
var aspect = recording.AspectAt(signal.Index, _time);
marks.Add((aspect, p, SignalRank(aspect)));
}
foreach (var (aspect, p) in MarkGrid.Thin(marks, radius * 2 + 1))
context.DrawEllipse(Palette.Of(aspect), outline, p, radius, radius);
}
/// <summary>How much a signal's dot tells: at stop most, then a speed, then go, then nothing known.</summary>
internal static int SignalRank(AspectChange? aspect) =>
aspect is not { } a ? 3 : a.Speed1 == 0 ? 0 : a.Speed1 < 0 && a.Speed2 != 0 ? 2 : 1;
/// <summary>
/// The stop points (W4): a white plate, blue where the user's train stopped, red where it
/// missed the stop; the name of the station once close enough to read it.
@@ -345,21 +401,28 @@ public sealed class MapView : Control
double size = _scale > 0.5 ? 4 : 3;
var outline = new Pen(Palette.MapBackground, 1);
var labels = new List<(Point At, string Name, IBrush Fill)>();
// A station has a plate for each track and length of train: from afar one to a few pixels,
// a missed stop kept first, then one stopped at. The wedges only close enough to tell apart.
var marks = new List<((MapStopPoint Point, IBrush Fill) Item, Point At, int Rank)>();
foreach (var point in recording.StopPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var fill = outcomes.TryGetValue((Math.Round(point.Position.X, 1), Math.Round(point.Position.Z, 1)), out var kind)
? kind == StationKind.Missed ? Palette.Bad : Palette.Station
: Palette.StopPoint;
bool known = outcomes.TryGetValue((Math.Round(point.Position.X, 1), Math.Round(point.Position.Z, 1)), out var kind);
var fill = known ? kind == StationKind.Missed ? Palette.Bad : Palette.Station : Palette.StopPoint;
int rank = !known ? 2 : kind == StationKind.Missed ? 0 : 1;
marks.Add(((point, fill), p, rank));
}
foreach (var ((point, fill), p) in MarkGrid.Thin(marks, near ? size * 2 + 1 : size * 3))
{
var plate = new Rect(p.X - size, p.Y - size * 1.3, size * 2, size * 2.6);
// a W32 hollow, in the colour a W4 would be filled with
if (point.ForShortTrains)
context.DrawRectangle(Palette.MapBackground, new Pen(fill, 1.5), plate, 1.5, 1.5);
else
context.DrawRectangle(fill, outline, plate, 1.5, 1.5);
if (point.HasHeading)
if (point.HasHeading && near)
DrawStopWay(context, p, point.Heading, size, fill, outline);
labels.Add((p, StationNames.Display(point.Station), fill));
}
@@ -373,7 +436,8 @@ public sealed class MapView : Control
taken.Add(new Rect(mark.X - 10, mark.Y - 24, 170, 34));
}
var culture = System.Globalization.CultureInfo.CurrentCulture;
foreach (var (p, name, fill) in labels)
// The plates came the least telling first; the names go the other way, a missed stop's first.
foreach (var (p, name, fill) in Enumerable.Reverse(labels))
{
if (!near && !named.Add(name))
continue;
@@ -401,15 +465,18 @@ public sealed class MapView : Control
var checks = recording.UserHornChecks().Where(c => c.Request.Time <= _time).ToList();
double size = _scale > 0.5 ? 5 : 3.5;
var outline = new Pen(Palette.MapBackground, 1);
// One to a few pixels from afar: a horn not sounded kept first, then one sounded.
var marks = new List<(IBrush Fill, Point At, int Rank)>();
foreach (var point in recording.HornPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var check = checks.LastOrDefault(c => c.Request.Position.DistanceTo(point.Position) < 1);
var fill = check is null ? Palette.HornPoint : check.Sounded ? Palette.Good : Palette.Bad;
context.DrawGeometry(fill, outline, Diamond(p, size));
marks.Add(check is null ? (Palette.HornPoint, p, 2) : check.Sounded ? (Palette.Good, p, 1) : (Palette.Bad, p, 0));
}
foreach (var (fill, p) in MarkGrid.Thin(marks, size * 2 + 1))
context.DrawGeometry(fill, outline, Diamond(p, size));
}
internal static StreamGeometry Diamond(Point p, double size)
@@ -454,37 +521,48 @@ public sealed class MapView : Control
{
var passed = new Pen(Palette.Within, 1.5);
var danger = new Pen(Palette.Over, 2.5);
// One ring to a few pixels, one at danger kept first.
var marks = new List<(bool AtDanger, Point At, int Rank)>();
foreach (var passing in recording.UserPassings())
{
if (passing.Time > _time)
continue;
var p = ToScreen(passing.Position.X, passing.Position.Z);
if (!Visible(p))
continue;
if (passing.AtDanger)
if (Visible(p))
marks.Add((passing.AtDanger, p, passing.AtDanger ? 0 : 1));
}
foreach (var (atDanger, p) in MarkGrid.Thin(marks, 12))
{
if (atDanger)
context.DrawEllipse(null, danger, p, 10, 10);
else
context.DrawEllipse(null, passed, p, 7, 7);
}
}
private void DrawVehicles(DrawingContext context, Recording recording)
private void DrawVehicles(DrawingContext context, Recording recording, IReadOnlyList<VehicleState> vehicles)
{
int user = recording.CabAt(_time) is { } sample && _time - sample.Time < 1.5 ? sample.Vehicle : 0;
foreach (var state in recording.VehiclesAt(_time))
// From afar a train's cars are each wider on screen than they are long: one to a few
// pixels, the user's own kept first, then those driven by the AI.
var marks = new List<(VehicleState State, Point At, int Rank)>();
foreach (var state in vehicles)
{
var center = ToScreen(state.Position.X, state.Position.Z);
if (Visible(center, (recording.Vehicle(state.Id)?.Length ?? 15) * _scale + 10))
marks.Add((state, center, state.Id == user ? 0 : state.Driving == Driver.Ai ? 1 : 2));
}
foreach (var (state, center) in MarkGrid.Thin(marks, 5))
{
var info = recording.Vehicle(state.Id);
var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle;
DrawVehicle(context, state.Position.X, state.Position.Z, state.Heading, info?.Length ?? 15, info?.Width ?? 3, brush);
DrawVehicle(context, center, state.Heading, info?.Length ?? 15, info?.Width ?? 3, brush);
}
}
private void DrawVehicle(DrawingContext context, double x, double z, double heading, double length, double width,
private void DrawVehicle(DrawingContext context, Point center, double heading, double length, double width,
IBrush brush)
{
var center = ToScreen(x, z);
if (!Visible(center, length * _scale + 10))
return;
// The front from +z towards +x: up the screen and to the left.
double fx = Math.Sin(heading), fz = Math.Cos(heading);
double half = Math.Max(length * _scale, 5) / 2, side = Math.Max(width * _scale, 3) / 2;
@@ -602,10 +680,19 @@ public sealed class MapView : Control
}
/// <summary>The name of the signal or the vehicle under the pointer.</summary>
private void DrawHover(DrawingContext context, Recording recording)
private void DrawHover(DrawingContext context, Recording recording, IReadOnlyList<VehicleState> vehicles)
{
if (_pointer is not { } pointer || _dragFrom is not null)
_hoverShown = _pointer is { } at && _dragFrom is null ? HoverLabel(recording, at, vehicles) : null;
if (_hoverShown is not { } label || _pointer is not { } pointer)
return;
var text = Text(label, Palette.Text, 12);
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
}
private string? HoverLabel(Recording recording, Point pointer, IReadOnlyList<VehicleState> vehicles)
{
string? label = null;
double best = 10;
foreach (var signal in recording.Signals)
@@ -646,7 +733,7 @@ public sealed class MapView : Control
label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration);
}
}
foreach (var state in recording.VehiclesAt(_time))
foreach (var state in vehicles)
{
double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer);
if (d < best && recording.Vehicle(state.Id) is { } info)
@@ -657,12 +744,7 @@ public sealed class MapView : Control
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
}
}
if (label is null)
return;
var text = Text(label, Palette.Text, 12);
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
return label;
}
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
@@ -724,8 +806,13 @@ public sealed class MapView : Control
_centerX = _dragCenter.X + moved.X / _scale;
_centerZ = _dragCenter.Z + moved.Y / _scale;
}
InvalidateVisual();
return;
}
InvalidateVisual();
// Not dragged, the map is the same: drawn again only for a label to show, follow the pointer or go.
if (_hoverShown is not null ||
(_recording is { } recording && HoverLabel(recording, position, recording.VehiclesAt(_time)) is not null))
InvalidateVisual();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using Avalonia;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The marks of a map thinned out on the screen: one to a square of a few pixels, the first
/// to ask for a square keeps it. Asked in the order of how much a mark tells, a crowd seen from
/// afar shows its most telling marks, each clear of the next, and close up, where the marks
/// stand apart anyway, every one is drawn.
/// </summary>
internal sealed class MarkGrid
{
private readonly double _cell;
private readonly HashSet<(long, long)> _taken = new();
/// <param name="cell">The side of a square in pixels: about the size of the mark.</param>
public MarkGrid(double cell) => _cell = Math.Max(cell, 1);
/// <summary>Whether the mark at this point of the screen is drawn: its square was free.</summary>
public bool Take(Point p) =>
_taken.Add(((long)Math.Floor(p.X / _cell), (long)Math.Floor(p.Y / _cell)));
/// <summary>
/// The items whose marks are drawn: those in view, the most telling first - a lower rank
/// tells more - each in a square no other took before it.
/// </summary>
public static List<(T Item, Point At)> Thin<T>(IEnumerable<(T Item, Point At, int Rank)> marks, double cell)
{
var ranked = new List<(T Item, Point At, int Rank)>(marks);
// Stable: of marks alike, the one first in the recording keeps its square, frame after frame.
var order = new int[ranked.Count];
for (int i = 0; i < order.Length; i++)
order[i] = i;
Array.Sort(order, (a, b) => ranked[a].Rank != ranked[b].Rank ? ranked[a].Rank.CompareTo(ranked[b].Rank) : a.CompareTo(b));
var grid = new MarkGrid(cell);
var kept = new List<(T, Point)>();
foreach (int i in order)
if (grid.Take(ranked[i].At))
kept.Add((ranked[i].Item, ranked[i].At));
// Drawn the least telling first: where marks of next squares touch, the telling one lies on top.
kept.Reverse();
return kept;
}
}

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

@@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using Avalonia;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The rails of a scenery made ready to draw fast: cut into square cells so that only those in
/// view are drawn, and kept at a few levels of detail so that from afar a track is drawn with
/// fewer points than there are pixels it covers. The casing takes the switches' ways too, which
/// it is drawn under in one colour; the fill is the plain tracks alone.
/// </summary>
public sealed class TrackLayer
{
/// <summary>The side of a cell in metres.</summary>
public const double CellSize = 500;
/// <summary>The points of a track closer than this to the last kept are left out, by level.</summary>
public static readonly double[] Tolerances = { 0, 2, 8, 32, 128 };
/// <summary>A part of the map: what is drawn of it, and where it lies in the map's plane.</summary>
public sealed record Cell(Rect Bounds, StreamGeometry Casing, StreamGeometry? Fill);
private readonly List<Cell>[] _levels;
public TrackLayer(IReadOnlyList<MapTrack> tracks)
{
_levels = new List<Cell>[Tolerances.Length];
for (int level = 0; level < Tolerances.Length; level++)
_levels[level] = BuildLevel(tracks, Tolerances[level]);
}
/// <summary>The level whose left-out points stay within <paramref name="pixels"/> on screen at this scale.</summary>
public static int LevelFor(double scale, double pixels = 0.75)
{
int level = 0;
for (int i = 1; i < Tolerances.Length; i++)
if (Tolerances[i] * scale <= pixels)
level = i;
return level;
}
/// <summary>The cells of the level that reach into <paramref name="view"/>, a rectangle of the map's plane.</summary>
public IEnumerable<Cell> CellsIn(Rect view, int level)
{
foreach (var cell in _levels[Math.Clamp(level, 0, _levels.Length - 1)])
if (cell.Bounds.Intersects(view))
yield return cell;
}
public int CellCount(int level) => _levels[level].Count;
/// <summary>The points of a track with those nearer than <paramref name="tolerance"/> to the last kept left out; its ends stay.</summary>
public static List<Vector3> Simplified(IReadOnlyList<Vector3> points, double tolerance)
{
var kept = new List<Vector3>(points.Count);
if (points.Count == 0)
return kept;
kept.Add(points[0]);
double square = tolerance * tolerance;
for (int i = 1; i < points.Count - 1; i++)
{
var last = kept[^1];
double dx = points[i].X - last.X, dz = points[i].Z - last.Z;
if (dx * dx + dz * dz >= square)
kept.Add(points[i]);
}
if (points.Count > 1)
kept.Add(points[^1]);
return kept;
}
private sealed class Builder
{
public readonly List<List<Point>> Casing = new();
public readonly List<List<Point>> Fill = new();
public double Left = double.MaxValue, Top = double.MaxValue, Right = double.MinValue, Bottom = double.MinValue;
public void Grow(Point p)
{
Left = Math.Min(Left, p.X);
Right = Math.Max(Right, p.X);
Top = Math.Min(Top, p.Y);
Bottom = Math.Max(Bottom, p.Y);
}
}
private static List<Cell> BuildLevel(IReadOnlyList<MapTrack> tracks, double tolerance)
{
var cells = new Dictionary<(long, long), Builder>();
foreach (var track in tracks)
{
if (track.Points.Count < 2)
continue;
bool fill = track.Kind != TrackKind.SwitchBranch;
var points = tolerance > 0 ? Simplified(track.Points, tolerance) : (IReadOnlyList<Vector3>)track.Points;
// A run of the track's points in one cell; a segment over a border goes with the cell it ends in,
// which starts from the point before, so its bounds cover the whole segment.
List<Point>? casingRun = null, fillRun = null;
(long, long) current = default;
for (int i = 0; i < points.Count; i++)
{
var p = Plane(points[i]);
var key = ((long)Math.Floor(p.X / CellSize), (long)Math.Floor(p.Y / CellSize));
if (casingRun is null || key != current)
{
var builder = Of(cells, key);
var start = casingRun is null ? (Point?)null : casingRun[^1];
casingRun = new List<Point>();
builder.Casing.Add(casingRun);
fillRun = null;
if (fill)
{
fillRun = new List<Point>();
builder.Fill.Add(fillRun);
}
if (start is { } joined)
{
// The segment from the last cell starts there, so the line has no gap at the border.
casingRun.Add(joined);
fillRun?.Add(joined);
builder.Grow(joined);
}
current = key;
}
casingRun.Add(p);
fillRun?.Add(p);
Of(cells, key).Grow(p);
}
}
var result = new List<Cell>(cells.Count);
foreach (var builder in cells.Values)
{
var casing = Geometry(builder.Casing);
if (casing is null)
continue;
var bounds = new Rect(new Point(builder.Left, builder.Top), new Point(builder.Right, builder.Bottom));
result.Add(new Cell(bounds, casing, Geometry(builder.Fill)));
}
return result;
}
private static Builder Of(Dictionary<(long, long), Builder> cells, (long, long) key)
{
if (!cells.TryGetValue(key, out var builder))
cells[key] = builder = new Builder();
return builder;
}
private static StreamGeometry? Geometry(List<List<Point>> runs)
{
StreamGeometry? geometry = null;
StreamGeometryContext? g = null;
try
{
foreach (var run in runs)
{
if (run.Count < 2)
continue;
if (geometry is null)
{
geometry = new StreamGeometry();
g = geometry.Open();
}
g!.BeginFigure(run[0], false);
for (int i = 1; i < run.Count; i++)
g.LineTo(run[i]);
g.EndFigure(false);
}
}
finally
{
g?.Dispose();
}
return geometry;
}
// As MapView draws the plane: x to the left, z up the screen.
private static Point Plane(Vector3 p) => new(-p.X, -p.Z);
}

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

@@ -3,7 +3,7 @@
base library: the starter, the viewer and any other program can use it, and
it goes through NativeAOT and trimming as they do. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>

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

@@ -10,7 +10,7 @@ needed on the target machine. The commands below are the same ones CI runs, see
Requirements:
- .NET SDK 9
- .NET SDK 10
- Linux: a native toolchain and zlib headers — `sudo apt install clang zlib1g-dev`
(Debian/Ubuntu) or `sudo dnf install clang zlib-devel` (Fedora)
- Windows: the Visual Studio C++ build tools (Desktop development with C++)

View File

@@ -0,0 +1,404 @@
using System.Reflection;
using StarterNG.Application.Abstractions;
using StarterNG.Infrastructure.Adapters;
using StarterNG.Infrastructure.Sceneries;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class BinaryTerrainFilesTests
{
private const string Record = "user/sbt-cleanup.txt";
private static BinaryTerrainFiles Build(InMemoryFileSystem files, string root = "game") =>
new(files, new GamePaths(root), TestLog.Over(files), Record);
private static string Scenery(string name) => $"game/scenery/{name}";
[Fact]
public void An_sbt_whose_terrain_files_are_all_there_goes()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("kato.scn"), "include kato/kato_ter.scm end\nFirstInit\n")
.WithFile(Scenery("kato/kato_ter.scm"), "node")
.WithFile(Scenery("kato.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal("kato.sbt", Assert.Single(cleanup.Deleted));
Assert.False(files.FileExists(Scenery("kato.sbt")));
}
[Fact]
public void An_sbt_standing_in_for_missing_terrain_files_stays()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("Lk2_Sandbox.scn"), "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n")
.WithFile(Scenery("lk2_sandbox.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Empty(cleanup.Deleted);
Assert.Equal(("lk2_sandbox.sbt", "nmt/nmt100_mazowieckie_ter.scm"), Assert.Single(cleanup.Kept));
Assert.True(files.FileExists(Scenery("lk2_sandbox.sbt")));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Terrain_included_through_another_file_is_looked_for_too(bool present)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "include td/base.inc end\nFirstInit\n")
.WithLegacyFile(Scenery("td/base.inc"), "include td/td_ter.scm 1 2 end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
if (present)
files.WithFile(Scenery("td/td_ter.scm"), "node");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal(present, cleanup.Deleted.Count == 1);
Assert.Equal(present, !files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void A_missing_include_other_than_terrain_does_not_keep_the_sbt()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("tomaszewo.scn"), "include tomaszewo/modele.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("tomaszewo/modele.scm"),
"include;przejazdy_kombud\\1t12m_0rog_2zar_1x_1dzw.inc;p_czernica15;0;0;0;end\n")
.WithFile(Scenery("tomaszewo.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
[Fact]
public void An_include_commented_out_needs_no_file()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "// include gone_ter.scm end\n/* include gone.inc end */\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
[Fact]
public void A_scenery_bringing_terrain_by_a_terrain_directive_keeps_its_sbt()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td.sbt endterrain\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal("td.sbt", Assert.Single(Build(files).CleanUpOnce(1)!.Kept).File);
}
[Theory]
[InlineData("td/teren.txtf")]
[InlineData("td/Teren.btf")]
public void An_sbt_in_the_way_of_terrain_files_that_are_there_goes(string onDisk)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("td.scn"), "terrain td/teren.txtf endterrain\nFirstInit\n")
.WithFile(Scenery(onDisk), "x")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
Assert.False(files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void An_sbt_standing_in_for_a_missing_terrain_file_stays()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf td/b.txtf endterrain\nFirstInit\n")
.WithFile(Scenery("td/a.txtf"), "x")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal(("td.sbt", "td/b.txtf"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
}
[Fact]
public void An_sbt_named_beside_terrain_files_keeps_the_scenery_s_own()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf wspolny.sbt endterrain\nFirstInit\n")
.WithFile(Scenery("td/a.txtf"), "x")
.WithFile(Scenery("wspolny.sbt"), "EU07SBT2")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Empty(cleanup.Deleted);
Assert.Contains(("td.sbt", "terrain wspolny.sbt"), cleanup.Kept);
}
[Fact]
public void An_sbt_of_no_scenery_stays()
{
var files = new InMemoryFileSystem()
.WithFile(Scenery("old.sbt"), "EU07SBT2");
Assert.Equal(("old.sbt", "old.scn"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
}
[Fact]
public void Each_generation_clears_an_installation_once()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
var sbt = Build(files);
Assert.NotNull(sbt.CleanUpOnce(1));
files.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Null(sbt.CleanUpOnce(1));
Assert.True(files.FileExists(Scenery("td.sbt")));
Assert.Single(sbt.CleanUpOnce(2)!.Deleted);
}
[Fact]
public void Generation_zero_clears_nothing()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Null(Build(files).CleanUpOnce(0));
Assert.True(files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void Another_installation_has_a_cleanup_of_its_own()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithLegacyFile("other/scenery/td.scn", "FirstInit\n")
.WithFile("other/scenery/td.sbt", "EU07SBT2");
Assert.NotNull(Build(files).CleanUpOnce(1));
Assert.Single(Build(files, "other").CleanUpOnce(1)!.Deleted);
}
[Fact]
public void One_scenery_s_sbt_is_found_whatever_its_case_and_deleted()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("Kato.scn"), "FirstInit\n")
.WithFile(Scenery("kato.sbt"), "EU07SBT2");
var sbt = Build(files);
Assert.Equal(Path.Combine("game", "scenery", "kato.sbt"), sbt.Of(Scenery("Kato.scn")));
Assert.Null(sbt.MissingOriginal(Scenery("Kato.scn")));
Assert.True(sbt.Delete(Scenery("Kato.scn")));
Assert.Null(sbt.Of(Scenery("Kato.scn")));
}
// With an .sbt there the simulator passes over the triangles and lines of every file, not
// only of those named *_ter.scm: a scenery file that is gone took its shapes with it.
[Theory]
[InlineData("td/teren.scm", true)]
[InlineData("td/teren.scm", false)]
[InlineData("TD\\Czesc.SCN", false)]
public void A_missing_scenery_file_keeps_the_sbt_whatever_its_name(string include, bool present)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), $"include td/base.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("td/base.scm"), $"include {include} 1 2 end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
if (present)
files.WithLegacyFile(Scenery(include), "node -1 0 none triangles grass 0 0 0 endtri\n");
var cleanup = Build(files).CleanUpOnce(1)!;
if (present)
Assert.Equal("td.sbt", Assert.Single(cleanup.Deleted));
else
Assert.Equal(("td.sbt", include), Assert.Single(cleanup.Kept));
Assert.Equal(present, !files.FileExists(Scenery("td.sbt")));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_terrain_file_that_only_lists_others_is_read_for_them(bool present)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "include td/citygml_ter.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("td/citygml_ter.scm"), "include td/citygml/n-34.scm end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
if (present)
files.WithFile(Scenery("td/citygml/n-34.scm"), "node");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal(present, cleanup.Deleted.Count == 1);
if (!present)
Assert.Equal(("td.sbt", "td/citygml/n-34.scm"), Assert.Single(cleanup.Kept));
}
[Fact]
public void A_large_terrain_file_is_not_opened()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "include td/td_ter.scm end\nFirstInit\n")
.WithFile(Scenery("td/td_ter.scm"), new string(' ', 1024 * 1024) + "include td/gone.scm end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
// "terrain" starts a directive only where the simulator looks for one. As the name of a
// node or of a texture it starts nothing, and the includes after it count as any other.
[Theory]
[InlineData("node -1 0 terrain triangles grass 0 0 0 endtri")]
[InlineData("node -1 0 none triangles terrain 0 0 0 endtri")]
public void A_word_reading_terrain_hides_no_include_after_it(string node)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), $"{node}\ninclude td/gone_ter.scm end\ninclude td/more.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("td/more.scm"), "include td/gone.scm end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal(("td.sbt", "td/gone_ter.scm"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
files.WithFile(Scenery("td/gone_ter.scm"), "node");
var again = Build(files).CleanUpOnce(2)!;
Assert.Equal(("td.sbt", "td/gone.scm"), Assert.Single(again.Kept));
}
[Fact]
public void A_word_reading_terrain_alone_does_not_keep_the_sbt()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"),
"node -1 0 terrain triangles grass 0 0 0 endtri\ninclude td/td_ter.scm end\nFirstInit\n")
.WithFile(Scenery("td/td_ter.scm"), "node")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
[Fact]
public void A_terrain_directive_is_still_read_after_a_word_reading_terrain()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"),
"node -1 0 terrain triangles grass 0 0 0 endtri\nterrain td/a.txtf endterrain\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal(("td.sbt", "td/a.txtf"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
}
// An .sbt serves every scenery naming it in a terrain directive, not only the one it is
// named after. With it gone such a scenery is read from its own text, until the simulator
// writes the file again on a load of the scenery it belongs to.
[Theory]
[InlineData("wspolny.sbt")]
[InlineData("Wspolny.SBT")]
[InlineData("$wspolny.sbt")]
public void An_sbt_another_scenery_cannot_do_without_stays(string named)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("wspolny.scn"), "include wspolny/wspolny_ter.scm end\nFirstInit\n")
.WithFile(Scenery("wspolny/wspolny_ter.scm"), "node")
.WithFile(Scenery("wspolny.sbt"), "EU07SBT2")
.WithLegacyFile(Scenery("nocny.scn"), $"include nocny/base.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("nocny/base.scm"), $"terrain {named} endterrain\ninclude nmt/nmt100_ter.scm end\n");
var sbt = Build(files);
Assert.Equal("nmt/nmt100_ter.scm (nocny.scn)", sbt.MissingOriginal(Scenery("wspolny.scn")));
var cleanup = sbt.CleanUpOnce(1)!;
Assert.Empty(cleanup.Deleted);
Assert.Equal(("wspolny.sbt", "nmt/nmt100_ter.scm (nocny.scn)"), Assert.Single(cleanup.Kept));
Assert.True(files.FileExists(Scenery("wspolny.sbt")));
}
[Fact]
public void An_sbt_another_scenery_can_do_without_goes()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("wspolny.scn"), "include wspolny/wspolny_ter.scm end\nFirstInit\n")
.WithFile(Scenery("wspolny/wspolny_ter.scm"), "node")
.WithFile(Scenery("wspolny.sbt"), "EU07SBT2")
.WithLegacyFile(Scenery("nocny.scn"),
"terrain wspolny.sbt endterrain\ninclude wspolny/wspolny_ter.scm end\nFirstInit\n");
var sbt = Build(files);
Assert.Null(sbt.MissingOriginal(Scenery("wspolny.scn")));
Assert.Equal("wspolny.sbt", Assert.Single(sbt.CleanUpOnce(1)!.Deleted));
}
[Fact]
public void An_sbt_of_the_same_name_in_another_folder_is_another_file()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("teren.scn"), "FirstInit\n")
.WithFile(Scenery("teren.sbt"), "EU07SBT2")
.WithFile(Scenery("l107/teren.sbt"), "EU07SBT2")
.WithLegacyFile(Scenery("lupkow.scn"),
"terrain l107/teren.sbt endterrain\ninclude nmt/nmt100_ter.scm end\nFirstInit\n");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal("teren.sbt", Assert.Single(cleanup.Deleted));
Assert.True(files.FileExists(Scenery("l107/teren.sbt")));
}
// The simulator drops the $ a scenery editor puts ahead of the name of a changed scenery,
// and reads and writes the .sbt of the one it was made from.
[Fact]
public void An_sbt_also_serves_the_scenery_named_with_a_dollar_ahead()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithLegacyFile(Scenery("$td.scn"), "include td/nowy_ter.scm end\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal(("td.sbt", "td/nowy_ter.scm ($td.scn)"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
files.WithFile(Scenery("td/nowy_ter.scm"), "node");
Assert.Single(Build(files).CleanUpOnce(2)!.Deleted);
}
[Fact]
public void A_file_many_sceneries_include_is_read_once()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("dzien.scn"), "include td/base.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("noc.scn"), "include td/base.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("td/base.scm"), "include td/td_ter.scm end\n")
.WithFile(Scenery("td/td_ter.scm"), "node")
.WithFile(Scenery("dzien.sbt"), "EU07SBT2")
.WithFile(Scenery("noc.sbt"), "EU07SBT2");
var counted = DispatchProxy.Create<IFileSystem, ReadCounter>();
var counter = (ReadCounter)(object)counted;
counter.Files = files;
var sbt = new BinaryTerrainFiles(counted, new GamePaths("game"), TestLog.Over(files), Record);
Assert.Equal(2, sbt.CleanUpOnce(1)!.Deleted.Count);
Assert.Single(counter.Read, path => Path.GetFileName(path) == "base.scm");
}
public class ReadCounter : DispatchProxy
{
public IFileSystem Files { get; set; } = null!;
public List<string> Read { get; } = new();
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
{
if (targetMethod!.Name == nameof(IFileSystem.ReadAllBytes))
Read.Add((string)args![0]!);
return targetMethod.Invoke(Files, args);
}
}
}

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

@@ -222,6 +222,34 @@ public class BlackBoxViewsTests
Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText());
}
[Fact]
public void Wheels_turning_apart_from_the_train_are_said_beside_its_speed()
{
var f = new BlackBoxFile().Info()
.Vehicle(Head, "EU07-005", "ROJ1")
.User(0, Head, true, 1);
// slipping for the first ten seconds, then the wheels as fast as the train, give or take the rounding
for (double t = 0; t <= 20; t += 0.5)
f.Cab(t, Head, 1150 + t * 10, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1,
wheelSpeed: t < 10 ? 55.4f : 40.3f);
var cab = new CabPanel
{
Recording = BlackBoxReader.Read(f.End(20).Stream()),
Strings = new DefaultBlackBoxStrings("en"),
Time = 5
};
Controls.Lay(cab, 600, 900);
Controls.Draw(cab);
Assert.Contains("40 km/h", cab.Said);
Assert.Contains("wheels 55", cab.Said);
cab.Time = 15;
Controls.Draw(cab);
Assert.Contains("40 km/h", cab.Said);
Assert.DoesNotContain("wheels", cab.Said);
}
[Fact]
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
{

View File

@@ -0,0 +1,49 @@
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
// The events are coloured with the views' brushes.
[Collection(AvaloniaControls.Name)]
public class CabDoorsTests
{
private static CabSample Sample(sbyte cab, CabDevices devices) =>
default(CabSample) with { CabEnd = cab, Devices = devices | CabDevices.Radio };
[Fact]
public void From_the_rear_cab_the_vehicles_right_doors_are_the_drivers_left()
{
var seen = Sample(-1, CabDevices.DoorsRight | CabDevices.DoorPermitRight).AsTheCabSees;
Assert.True(seen.Has(CabDevices.DoorsLeft));
Assert.True(seen.Has(CabDevices.DoorPermitLeft));
Assert.False(seen.Has(CabDevices.DoorsRight));
Assert.False(seen.Has(CabDevices.DoorPermitRight));
Assert.True(seen.Has(CabDevices.Radio));
}
[Theory]
[InlineData(1)]
[InlineData(0)]
public void From_the_front_cab_or_out_of_one_the_sides_are_the_vehicles(sbyte cab)
{
var sample = Sample(cab, CabDevices.DoorsLeft | CabDevices.DoorPermitRight);
Assert.Equal(sample, sample.AsTheCabSees);
}
[Fact]
public void Going_to_the_other_cab_tells_nothing_of_the_doors_and_still_tells_the_switches()
{
var f = new BlackBoxFile().Info().Vehicle(1, "EN57-1001").User(0, 1, true);
// the left doors permitted from the front cab; in the rear one the permit is still on, and the radio turned off
f.Cab(0, 1, 1000, 0, cabEnd: 1, devices: 0x0007 | (uint)(CabDevices.DoorPermitLeft | CabDevices.Radio));
f.Cab(1, 1, 1000, 0, cabEnd: -1, devices: 0x0007 | (uint)CabDevices.DoorPermitLeft);
var events = EventList.Collect(BlackBoxReader.Read(f.End(1).Stream()), new DefaultBlackBoxStrings("en"))
.Select(e => e.Text).ToList();
Assert.Contains("Radio: off", events);
Assert.DoesNotContain(events, e => e.Contains("doors permitted"));
}
}

View File

@@ -0,0 +1,44 @@
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
[Collection(AvaloniaControls.Name)]
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,67 @@
using Avalonia;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>The marks of the black box map thinned out where they crowd, the most telling kept.</summary>
public class MarkGridTests
{
[Fact]
public void A_crowd_in_one_square_leaves_its_most_telling_mark()
{
var kept = MarkGrid.Thin(new[]
{
("go", new Point(1, 1), 2),
("stop", new Point(3, 2), 0),
("speed", new Point(4, 4), 1)
}, 6);
Assert.Equal(["stop"], kept.Select(k => k.Item));
}
[Fact]
public void Marks_apart_by_more_than_a_square_are_all_kept()
{
var marks = Enumerable.Range(0, 20).Select(i => (i, new Point(i * 10, 5), 1)).ToList();
Assert.Equal(20, MarkGrid.Thin(marks, 6).Count);
}
[Fact]
public void Of_marks_alike_the_first_keeps_its_square_and_the_telling_ones_are_drawn_last()
{
var kept = MarkGrid.Thin(new[]
{
("first", new Point(1, 1), 1),
("second", new Point(2, 2), 1),
("apart", new Point(50, 50), 0)
}, 6);
Assert.Equal(["first", "apart"], kept.Select(k => k.Item));
}
[Fact]
public void A_row_closer_than_a_square_keeps_one_to_each()
{
// A hundred marks a pixel apart are as many squares of six as they cover.
var marks = Enumerable.Range(0, 100).Select(i => (i, new Point(i, 0), 1)).ToList();
Assert.Equal(17, MarkGrid.Thin(marks, 6).Count);
}
[Theory]
[InlineData(0f, 40f, 0)] // at stop
[InlineData(40f, -1f, 1)] // a speed
[InlineData(-1f, -1f, 2)] // go
public void A_signal_at_stop_tells_most(float speed1, float speed2, int rank)
{
Assert.Equal(rank, MapView.SignalRank(new AspectChange(0, 1, speed1, speed2, "")));
}
[Fact]
public void A_signal_not_yet_seen_tells_least()
{
Assert.Equal(3, MapView.SignalRank(null));
}
}

View File

@@ -0,0 +1,89 @@
using System.Globalization;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
[Collection(AvaloniaControls.Name)]
public class SecurityBrakingTests
{
// as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too
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,79 @@
using System.Numerics;
using Avalonia;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>The rails of the black box map made ready to draw only what is in view, at the detail a pixel shows.</summary>
[Collection(AvaloniaControls.Name)]
public class TrackLayerTests
{
public TrackLayerTests() => HeadlessDrawing.Ensure();
private static MapTrack Track(int index, TrackKind kind, params (float X, float Z)[] points) =>
new(index, $"t{index}", kind, kind == TrackKind.SwitchBranch ? 0 : -1, 0,
points.Select(p => new Vector3(p.X, 0, p.Z)).ToList());
[Theory]
[InlineData(2.0, 0)] // close up: every point
[InlineData(0.3, 1)] // 2 m are 0.6 px, 8 m would be 2.4
[InlineData(0.05, 2)] // 8 m are 0.4 px, 32 m would be 1.6
[InlineData(0.002, 4)] // the whole of a big scenery: 128 m are 0.26 px
public void The_level_leaves_out_no_more_than_a_pixel_shows(double scale, int level)
{
Assert.Equal(level, TrackLayer.LevelFor(scale));
}
[Fact]
public void Only_the_cells_in_view_are_drawn()
{
var layer = new TrackLayer(new[]
{
Track(1, TrackKind.Normal, (0, 0), (100, 0)),
Track(2, TrackKind.Normal, (-5000, -5000), (-5100, -5000))
});
// The plane shows x to the left: the first track lies at -100..0, the second at 5000..5100.
var near = layer.CellsIn(new Rect(-200, -50, 300, 100), 0).ToList();
Assert.Single(near);
Assert.Equal(2, layer.CellCount(0));
}
[Fact]
public void A_track_across_cells_is_drawn_without_a_gap_at_the_border()
{
var layer = new TrackLayer(new[] { Track(1, TrackKind.Normal, (-400, 0), (-600, 0), (-800, 0)) });
var cells = layer.CellsIn(new Rect(-10000, -10000, 20000, 20000), 0).ToList();
// The segment over the border goes with the cell it ends in, from the point the line left the last one:
// that cell reaches back to it, so it is drawn whenever any of the segment is in view.
var cell = Assert.Single(cells);
Assert.Equal(400, cell.Bounds.Left);
Assert.Equal(800, cell.Bounds.Right);
Assert.Single(layer.CellsIn(new Rect(450, -10, 20, 20), 0));
}
[Fact]
public void A_switch_way_is_in_the_casing_but_not_in_the_plain_fill()
{
var layer = new TrackLayer(new[] { Track(7, TrackKind.SwitchBranch, (0, 0), (30, 5)) });
var cell = Assert.Single(layer.CellsIn(new Rect(-100, -100, 200, 200), 0));
Assert.NotNull(cell.Casing);
Assert.Null(cell.Fill);
}
[Fact]
public void Simplifying_keeps_the_ends_and_drops_points_closer_than_the_tolerance()
{
var points = new[] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(2, 0, 0), new Vector3(10, 0, 0), new Vector3(11, 0, 0) };
var kept = TrackLayer.Simplified(points, 5);
Assert.Equal(new[] { 0f, 10f, 11f }, kept.Select(p => p.X));
}
}

View File

@@ -0,0 +1,55 @@
using Avalonia;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>The line of a tape, drawn a column of pixels at a time and broken off at a gap.</summary>
public class ColumnLineTests
{
private readonly List<string> _drawn = [];
private ColumnLine Line() =>
new(p => _drawn.Add($"begin {p.X} {p.Y}"), p => _drawn.Add($"line {p.X} {p.Y}"), () => _drawn.Add("end"));
[Fact]
public void A_column_is_entered_where_it_started_and_left_where_it_ended_through_its_lowest_and_highest()
{
var line = Line();
// Falling within the column: from its first through its highest and its lowest to its last.
foreach (double v in new[] { 3.0, 1.0, 4.0, 2.0 })
line.Add(5, v);
// Rising: through its lowest first.
foreach (double v in new[] { 2.0, 4.0, 1.0, 3.0 })
line.Add(6, v);
line.Break();
Assert.Equal(["begin 5 3", "line 5 4", "line 5 1", "line 5 2",
"line 6 2", "line 6 1", "line 6 4", "line 6 3", "end"], _drawn);
}
[Fact]
public void A_break_ends_the_figure_and_the_next_point_begins_another()
{
var line = Line();
line.Add(0, 10);
line.Break();
line.Add(9, 20);
line.Break();
Assert.Equal(["begin 0 10", "line 0 10", "line 0 10", "line 0 10", "end",
"begin 9 20", "line 9 20", "line 9 20", "line 9 20", "end"], _drawn);
}
[Fact]
public void A_break_with_nothing_drawn_ends_nothing()
{
var line = Line();
line.Break();
line.Break();
Assert.Empty(_drawn);
}
}

View File

@@ -6,6 +6,8 @@ using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
// Puts in services of its own: not while the controls read theirs.
[Collection(AvaloniaControls.Name)]
public class ConsistOrientationTests
{
private readonly VehicleCatalog _catalog;

View File

@@ -0,0 +1,68 @@
using StarterNG.Classes;
using StarterNG.Domain;
namespace StarterNG.Tests;
public class ConsistRunsTests
{
private static List<Dynamic> Vehicles(params string[] skins) =>
new Trainset(string.Concat(
"trainset a tor 0 0\n",
string.Concat(skins.Select((s, i) => $"node -1 0 v{i} dynamic d {s} m 0 nobody 3 0 enddynamic\n")),
"endtrainset")).Vehicles;
private static List<(string Skin, int Count)> Runs(List<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf) =>
ConsistRuns.Of(vehicles, keyOf).Select(r => (r.First.SkinFile!, r.Count)).ToList();
[Fact]
public void Vehicles_alike_next_to_each_other_make_one_run()
{
var vehicles = Vehicles("eu07", "412w", "412w", "412w", "eaos", "eaos");
Assert.Equal(
[("eu07", 1), ("412w", 3), ("eaos", 2)],
Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void Vehicles_alike_apart_stay_apart()
{
var vehicles = Vehicles("412w", "eaos", "412w");
Assert.Equal(
[("412w", 1), ("eaos", 1), ("412w", 1)],
Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void Alike_goes_by_the_key_whatever_its_case()
{
var vehicles = Vehicles("412W", "412w");
Assert.Equal([("412W", 2)], Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void A_vehicle_with_no_key_stands_alone()
{
var vehicles = Vehicles("x", "x", "x");
Assert.Equal(
[("x", 1), ("x", 1), ("x", 1)],
Runs(vehicles, (_, _) => null));
}
[Fact]
public void The_place_in_the_consist_can_set_a_vehicle_apart()
{
var vehicles = Vehicles("sm42", "sm42", "sm42");
Assert.Equal(
[("sm42", 1), ("sm42", 2)],
Runs(vehicles, (v, i) => i == 0 ? "head" : v.SkinFile));
}
[Fact]
public void No_vehicles_no_runs() =>
Assert.Empty(ConsistRuns.Of([], (v, _) => v.SkinFile));
}

View File

@@ -1,100 +0,0 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class DisplaysTests
{
/// <summary>A 128-byte block with an 18-byte timing at 54, as a panel's base EDID has it.</summary>
private static byte[] BaseBlock(int pixelClock10KHz, int hActive, int hBlank, int vActive, int vBlank,
int extensions = 0)
{
var edid = new byte[128];
new byte[] { 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }.CopyTo(edid, 0);
edid[126] = (byte)extensions;
int at = 54;
edid[at] = (byte)pixelClock10KHz;
edid[at + 1] = (byte)(pixelClock10KHz >> 8);
edid[at + 2] = (byte)hActive;
edid[at + 3] = (byte)hBlank;
edid[at + 4] = (byte)((hActive >> 8) << 4 | hBlank >> 8);
edid[at + 5] = (byte)vActive;
edid[at + 6] = (byte)vBlank;
edid[at + 7] = (byte)((vActive >> 8) << 4 | vBlank >> 8);
return edid;
}
/// <summary>A DisplayID 2.0 block with one type VII timing (kHz, sizes less one).</summary>
private static byte[] DisplayIdBlock(int pixelClockKHz, int hActive, int hBlank, int vActive, int vBlank)
{
var block = new byte[128];
block[0] = 0x70;
block[1] = 0x20;
block[2] = 23; // one data block: 3 bytes of header, 20 of timing
block[3] = 2;
int at = 5;
block[at] = 0x22;
block[at + 2] = 20;
int t = at + 3, clock = pixelClockKHz - 1;
block[t] = (byte)clock;
block[t + 1] = (byte)(clock >> 8);
block[t + 2] = (byte)(clock >> 16);
void Put(int offset, int value)
{
block[t + offset] = (byte)(value - 1);
block[t + offset + 1] = (byte)((value - 1) >> 8);
}
Put(4, hActive);
Put(6, hBlank);
Put(12, vActive);
Put(14, vBlank);
return block;
}
[Fact]
public void A_plain_monitor_gives_its_preferred_timing()
{
// 1920x1080 at 148.5 MHz: the usual 60 Hz.
Assert.Equal(60, Edid.HighestRefreshRate(BaseBlock(14850, 1920, 280, 1080, 45)));
}
[Fact]
public void A_fast_panel_found_only_in_displayid_is_read_there()
{
// As the eDP panel of a gaming laptop: 60 Hz in the base block, 165 Hz in DisplayID.
var edid = BaseBlock(15394, 1920, 160, 1200, 35, extensions: 1)
.Concat(DisplayIdBlock(423250, 1920, 160, 1200, 33)).ToArray();
Assert.Equal(165, Edid.HighestRefreshRate(edid));
}
[Fact]
public void Something_too_short_for_an_edid_has_no_rate()
{
Assert.Equal(0, Edid.HighestRefreshRate(new byte[] { 0, 0xFF }));
Assert.Equal(0, Edid.HighestRefreshRate(new byte[128]));
}
[Fact]
public void Only_connected_screens_are_listed_by_their_connector()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile("/sys/class/drm/card1-eDP-1/status", "connected\n")
.WithFile("/sys/class/drm/card1-HDMI-A-1/status", "disconnected\n")
.WithFile("/sys/class/drm/card1/device/uevent", "DRIVER=amdgpu\n");
files.WriteAllBytes("/sys/class/drm/card1-eDP-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
files.WriteAllBytes("/sys/class/drm/card1-HDMI-A-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
var displays = new Displays(files, new FakeEnvironment()).List();
Assert.Equal(new[] { new Display("eDP-1", 60) }, displays);
}
[Fact]
public void Off_linux_without_windows_nothing_is_read()
{
var environment = new FakeEnvironment { IsLinux = false, IsMacOS = true };
Assert.Empty(new Displays(new InMemoryFileSystem(), environment).List());
}
}

View File

@@ -0,0 +1,158 @@
using StarterNG.Classes;
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>eu07.ini as other hands leave it: edited while the starter runs, and with lines the starter does not know.</summary>
public class ExternalIniTests
{
private static readonly string UserIni = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
private static TestInstallation WithIni(string text)
{
var installation = new TestInstallation(new InMemoryFileSystem().WithFile(UserIni, text));
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
return installation;
}
private static SimulatorSettings Read(string text)
{
var s = new SimulatorSettings();
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
return s;
}
[Fact]
public void A_key_inside_a_block_comment_is_not_read()
{
Assert.False(Read("/*\nfullscreen yes\n*/\n").Fullscreen);
Assert.False(Read("/* fullscreen yes */\n").Fullscreen);
}
[Fact]
public void A_comment_glued_to_a_value_is_not_part_of_it()
{
Assert.True(Read("fullscreen yes//na pelnym ekranie\n").Fullscreen);
}
[Fact]
public void A_save_keeps_what_was_changed_on_disk_meanwhile()
{
var installation = WithIni("fieldofview 45\n");
Edited(installation, "fieldofview 45\nvsync yes\ncalibratein 1 2 3 4\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("fieldofview 60", saved);
Assert.Contains("calibratein 1 2 3 4", saved);
Assert.Contains("vsync yes", saved);
// What is held is the file again: a later save does not take the other change back.
Assert.True(installation.SettingsStore.Settings.VSync);
Assert.True(installation.SettingsStore.LastSaveMerged);
}
[Fact]
public void A_key_changed_both_here_and_on_disk_takes_the_players_value()
{
var installation = WithIni("fieldofview 45\n");
Edited(installation, "fieldofview 70\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_file_nobody_else_touched_saves_as_before()
{
var installation = WithIni("fieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
Assert.False(installation.SettingsStore.LastSaveMerged);
Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_known_key_with_a_value_the_starter_cannot_read_is_named_with_that_value()
{
var installation = WithIni("fieldofview abc\nfullscreen moze\nui.scale duzo\nvsync tak\nwidth 1920.0\n" +
"gfxrenderer legacy\nwidth 1920\ngfx.framebuffer.width 960\ncalibratein 1 2\n");
var unreadable = installation.SettingsStore.UnreadableValues();
Assert.Equal("abc", unreadable["fieldofview"]);
Assert.Equal("moze", unreadable["fullscreen"]);
Assert.Equal("duzo", unreadable["ui.scale"]);
// Read another way, derived from other keys, or not the starter's: none of them unknown.
Assert.False(unreadable.ContainsKey("vsync"));
Assert.False(unreadable.ContainsKey("width"));
Assert.False(unreadable.ContainsKey("gfxrenderer"));
Assert.False(unreadable.ContainsKey("gfx.framebuffer.width"));
Assert.False(unreadable.ContainsKey("calibratein"));
// The file keeps what it says until the setting is changed.
installation.SettingsStore.Save();
Assert.Contains("fieldofview abc", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void Values_above_what_the_old_starter_gave_are_brought_down_on_the_next_save()
{
var installation = WithIni("maxcabtexturesize 8192\nshadowtune 4096 250 600 300\n" +
"width 1920\nheight 1080\ngfx.framebuffer.width 2880\ngfx.framebuffer.height 1620\n" +
"fieldofview 50\n");
var store = installation.SettingsStore;
Assert.Equal(GraphicsRules.MaxCabTextureSize, store.Settings.MaxCabTextureSize);
Assert.Equal(GraphicsRules.MaxShadowRange, store.Settings.ShadowProjectionRange);
Assert.Equal(GraphicsRules.MaxBufferScale, store.Settings.BufferScalePercent);
// Read, only brought down: not a value the starter cannot read.
Assert.Empty(store.UnreadableValues());
store.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("maxcabtexturesize 4096", saved);
Assert.Contains("shadowtune 4096 250 400 300", saved);
Assert.Contains("gfx.framebuffer.width 1920", saved);
Assert.Contains("gfx.framebuffer.height 1080", saved);
Assert.Contains("fieldofview 50", saved);
}
[Fact]
public void Values_within_the_caps_are_left_as_the_file_has_them()
{
var installation = WithIni("maxcabtexturesize 2048\nshadowtune 2048 250 300 300\n");
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("maxcabtexturesize 2048", saved);
Assert.Contains("shadowtune 2048 250 300 300", saved);
}
// Another program writes the file a minute after the starter read it.
private static void Edited(TestInstallation installation, string text) =>
installation.Files.WithFile(UserIni, text)
.WrittenAt(UserIni, installation.Files.GetLastWriteTimeUtc(UserIni).AddMinutes(1));
[Fact]
public void Lines_the_starter_does_not_know_survive_a_save_in_place()
{
const string ini = "// moj komentarz\nfoo bar baz\n\nfullscreen no\nzmq.address tcp://*:5555\n";
var installation = WithIni(ini);
installation.SettingsStore.Settings.Fullscreen = true;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni).Replace("\r\n", "\n");
Assert.StartsWith("// moj komentarz\nfoo bar baz\n\nfullscreen yes\nzmq.address tcp://*:5555\n", saved);
}
}

View File

@@ -0,0 +1,29 @@
namespace StarterNG.Tests.Fakes;
/// <summary>A stream read from its start to its end and no other way: no length, no seeking.</summary>
internal sealed class ForwardOnlyStream(Stream inner) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush() { }
protected override void Dispose(bool disposing)
{
if (disposing)
inner.Dispose();
base.Dispose(disposing);
}
}

View File

@@ -20,6 +20,7 @@ public sealed class InMemoryFileSystem : IFileSystem
private readonly HashSet<string> _executable;
private readonly Dictionary<string, string> _links;
private readonly HashSet<string> _unreadable;
private readonly HashSet<string> _unseekable;
private readonly HashSet<string> _unlistable;
private readonly Dictionary<string, DateTime> _written;
@@ -32,6 +33,7 @@ public sealed class InMemoryFileSystem : IFileSystem
_executable = new HashSet<string>(comparer);
_links = new Dictionary<string, string>(comparer);
_unreadable = new HashSet<string>(comparer);
_unseekable = new HashSet<string>(comparer);
_unlistable = new HashSet<string>(comparer);
_written = new Dictionary<string, DateTime>(comparer);
}
@@ -51,6 +53,13 @@ public sealed class InMemoryFileSystem : IFileSystem
return this;
}
/// <summary>The file opens as a stream read only forward, as a pipe or some network shares give it.</summary>
public InMemoryFileSystem OpenedForwardOnly(string path)
{
_unseekable.Add(Normalize(path));
return this;
}
public InMemoryFileSystem AllowReading(string path)
{
_unreadable.Remove(Normalize(path));
@@ -115,7 +124,11 @@ public sealed class InMemoryFileSystem : IFileSystem
public byte[] ReadAllBytes(string path) => Bytes(path);
public Stream OpenRead(string path) => new MemoryStream(Bytes(path), writable: false);
public Stream OpenRead(string path)
{
var stream = new MemoryStream(Bytes(path), writable: false);
return _unseekable.Contains(Normalize(path)) ? new ForwardOnlyStream(stream) : stream;
}
public void WriteAllText(string path, string contents) => WithFile(path, contents);

View File

@@ -0,0 +1,65 @@
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Tests;
public sealed class FolderChangesTests : IDisposable
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-changes-" + Guid.NewGuid().ToString("N"));
public FolderChangesTests() => Directory.CreateDirectory(Path.Combine(_root, "sub"));
public void Dispose() => Directory.Delete(_root, recursive: true);
private static async Task<bool> Reported(FolderChanges changes, Action change)
{
var told = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
changes.Changed += () => told.TrySetResult();
change();
return await Task.WhenAny(told.Task, Task.Delay(Patience)) == told.Task;
}
[Fact]
public async Task A_file_written_below_the_folder_is_reported()
{
string file = Path.Combine(_root, "sub", "a.scm");
File.WriteAllText(file, "old");
using var changes = new FolderChanges(_root);
Assert.True(changes.Watching);
Assert.True(await Reported(changes, () => File.WriteAllText(file, "new text")));
}
[Fact]
public async Task A_save_through_a_renamed_temp_file_is_reported()
{
string file = Path.Combine(_root, "test.scn");
File.WriteAllText(file, "old");
using var changes = new FolderChanges(_root);
Assert.True(await Reported(changes, () =>
{
string temp = file + ".tmp";
File.WriteAllText(temp, "new");
File.Move(temp, file, overwrite: true);
}));
}
[Fact]
public async Task A_file_removed_is_reported()
{
string file = Path.Combine(_root, "gone.scn");
File.WriteAllText(file, "x");
using var changes = new FolderChanges(_root);
Assert.True(await Reported(changes, () => File.Delete(file)));
}
[Fact]
public void A_missing_folder_is_not_watched_and_does_not_throw()
{
using var changes = new FolderChanges(Path.Combine(_root, "nowhere"));
Assert.False(changes.Watching);
}
}

View File

@@ -0,0 +1,192 @@
using Avalonia.Controls;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public sealed class FolderLooksTests : IDisposable
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-looks-" + Guid.NewGuid().ToString("N"));
private readonly ManualTime _time = new();
private readonly Window _window;
private int _looks;
public FolderLooksTests()
{
Directory.CreateDirectory(_root);
HeadlessDrawing.Ensure();
_window = new Window();
}
public void Dispose()
{
_window.Close();
Directory.Delete(_root, recursive: true);
}
private FolderLooks Opened(string folder)
{
var looks = new FolderLooks(_window, () => folder, () =>
{
_looks++;
return Task.CompletedTask;
}, _time);
_window.Show();
Controls.Settle();
_looks = 0;
return looks;
}
private ManualTimer Quiet => _time.Timers.Single(t => t.Period == Timeout.InfiniteTimeSpan);
private ManualTimer Often => _time.Timers.Single(t => t.Period != Timeout.InfiniteTimeSpan);
// Waited for without leaving the thread: the window belongs to it.
private static void Until(Func<bool> condition) => Assert.True(SpinWait.SpinUntil(condition, Patience), "waited too long");
[Fact]
public void Nothing_is_watched_before_the_window_opens()
{
_ = new FolderLooks(_window, () => _root, () => Task.CompletedTask, _time);
Assert.Empty(_time.Timers);
}
[Fact]
public void A_watched_folder_is_looked_at_anyway_seldom()
{
var looks = Opened(_root);
Assert.True(looks.Watching);
Assert.Equal(FolderLooks.Watched, Often.Due);
Assert.Equal(FolderLooks.Watched, Often.Period);
Assert.Equal(Timeout.InfiniteTimeSpan, Quiet.Due);
}
[Fact]
public void A_folder_the_system_reports_nothing_of_is_looked_at_often()
{
var looks = Opened(Path.Combine(_root, "nowhere"));
Assert.False(looks.Watching);
Assert.Equal(FolderLooks.Unwatched, Often.Period);
}
[Fact]
public void A_tick_looks_on_the_ui_thread_once_it_gets_there()
{
Opened(_root);
Often.Fire();
Assert.Equal(0, _looks);
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void A_change_is_looked_at_once_the_reports_stop()
{
Opened(_root);
File.WriteAllText(Path.Combine(_root, "test.scn"), "new");
Until(() => Quiet.Due == FolderLooks.Quiet);
Controls.Settle();
Assert.Equal(0, _looks);
Quiet.Fire();
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void Coming_back_to_the_window_looks()
{
Opened(_root);
_window.Activate();
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void Asked_it_looks()
{
var looks = Opened(_root);
Assert.True(looks.LookAsync().IsCompletedSuccessfully);
Assert.Equal(1, _looks);
}
[Fact]
public void Closed_it_stops_the_timers()
{
Opened(_root);
_window.Close();
Assert.Equal(2, _time.Timers.Count);
Assert.All(_time.Timers, t => Assert.True(t.Disposed));
}
private sealed class ManualTime : TimeProvider
{
private readonly List<ManualTimer> _timers = new();
public IReadOnlyList<ManualTimer> Timers
{
get
{
lock (_timers)
return _timers.ToList();
}
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new ManualTimer(() => callback(state), dueTime, period);
lock (_timers)
_timers.Add(timer);
return timer;
}
}
private sealed class ManualTimer : ITimer
{
private readonly Action _tick;
private long _dueTicks;
public ManualTimer(Action tick, TimeSpan due, TimeSpan period)
{
_tick = tick;
_dueTicks = due.Ticks;
Period = period;
}
public TimeSpan Due => TimeSpan.FromTicks(Interlocked.Read(ref _dueTicks));
public TimeSpan Period { get; private set; }
public bool Disposed { get; private set; }
public void Fire() => _tick();
public bool Change(TimeSpan dueTime, TimeSpan period)
{
if (Disposed)
throw new ObjectDisposedException(nameof(ManualTimer));
Interlocked.Exchange(ref _dueTicks, dueTime.Ticks);
Period = period;
return true;
}
public void Dispose() => Disposed = true;
public ValueTask DisposeAsync()
{
Dispose();
return ValueTask.CompletedTask;
}
}
}

View File

@@ -26,16 +26,13 @@ public class GraphicsPresetTests
var store = new TestInstallation().SettingsStore;
var low = Defaults().Copy();
var top = Defaults().Copy();
// Ray tracing is one of them, and only Vulkan has it.
low.RenderEngine = top.RenderEngine = SimulatorSettings.VulkanEngine;
(GraphicsPreset.Minimal with { Extras = null }).ApplyTo(low);
(GraphicsPreset.Ultra with { Extras = null, Top = null }).ApplyTo(top);
var lowKeys = store.Render(low);
var topKeys = store.Render(top);
var differing = lowKeys.Keys.Union(topKeys.Keys)
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key))
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal));
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key));
Assert.Equal(GraphicsPreset.Keys.OrderBy(k => k), differing.OrderBy(k => k));
}
@@ -55,7 +52,7 @@ public class GraphicsPresetTests
{
// Sizes and filtering run out of steps above High.
Climbs(p => p.TextureSize, 1);
Climbs(p => p.CabTextureSize, 1);
Climbs(p => p.CabTextureSize, 2);
Climbs(p => p.Anisotropy, 1);
// Four steps or three for six levels.
@@ -65,28 +62,23 @@ public class GraphicsPresetTests
Climbs(p => p.ReflectionsFidelity, 3);
Climbs(p => p.ShadowRank, 3);
// The simulator takes no more than its own 7 lights, and draws no less than 2 km.
// The simulator takes no more than its own 7 lights.
Climbs(p => p.DynamicLights, 2);
Climbs(p => p.DrawRange, 1);
Climbs(p => p.DrawRangeFactor, 2);
Climbs(p => p.DrawRangeFactor, 3);
Climbs(p => p.CabShadowsRange, 1);
Climbs(p => p.ShadowMap, 1);
Climbs(p => p.ShadowRange, 0);
Climbs(p => p.ReflectionsRate, 0);
Climbs(p => p.DistanceFactor, 0);
Climbs(p => p.BufferScale, 0);
Climbs(p => p.SleeperDistance, 0);
Climbs(p => p.ReflectedInstances, 0);
Climbs(p => p.ReflectedVehicles, 0);
Climbs(p => p.ShadowMap, 2);
Climbs(p => p.ShadowRange, 1);
// The old starter's steps begin at once a second: the lower levels share it.
Climbs(p => p.ReflectionsRate, 2);
}
[Fact]
public void No_step_up_a_scale_is_more_than_a_few_steps_of_its_slider()
{
// In steps of what the screen offers, so Ultra does not jump to the top from far below.
var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(Steps.ReflectionUpdates, p.ReflectionsRate)).ToList();
Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 1, 4));
var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(SliderRanges.ReflectionUpdates, p.ReflectionsRate)).ToList();
Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 0, 2));
foreach (Func<GraphicsPreset, int> fidelity in new Func<GraphicsPreset, int>[] { p => p.SmokeFidelity, p => p.SplineFidelity })
{
@@ -103,9 +95,7 @@ public class GraphicsPresetTests
var high = store.Render(AtHigh());
var differing = own.Keys.Union(high.Keys)
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key))
.Where(key => !GraphicsPreset.RowKeys.Contains(key))
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal) && key != "gfx.buffer.percent");
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key));
Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range",
"gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k));
@@ -128,6 +118,8 @@ public class GraphicsPresetTests
var again = new TestInstallation(installation.Files).SettingsStore;
again.Load();
Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(again.Settings));
// Nothing of an older starter to bring into the standard mode.
Assert.True(again.Settings.MovedToStandard);
}
[Fact]
@@ -144,158 +136,102 @@ public class GraphicsPresetTests
again.StartAtHighWithoutOwnSettings();
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(again.Settings));
Assert.False(again.Settings.MovedToStandard);
}
[Fact]
public void High_is_what_the_new_simulator_does_with_nothing_set()
public void A_copy_of_the_file_is_kept_once_and_not_written_over()
{
Assert.Equal(GraphicsPreset.High.NewRenderer, GraphicsNewRenderer.Of(Defaults()));
var installation = new TestInstallation();
var store = installation.SettingsStore;
store.Load();
store.Settings.FieldOfView = 50;
store.Save();
string copy = store.SavePath + ".before-standard";
store.KeepCopy(".before-standard");
string first = installation.Files.ReadAllText(copy);
Assert.Equal(installation.Files.ReadAllText(store.SavePath), first);
store.Settings.FieldOfView = 60;
store.Save();
store.KeepCopy(".before-standard");
Assert.Equal(first, installation.Files.ReadAllText(copy));
}
[Fact]
public void The_new_renderers_scales_never_go_down()
{
void NeverDown(Func<GraphicsNewRenderer, double> value) => Climbs(p => value(p.NewRenderer), 5);
void TurnsOn(Func<GraphicsNewRenderer, bool> on)
{
var values = GraphicsPreset.All.Select(p => on(p.NewRenderer)).ToList();
Assert.Equal(values.OrderBy(value => value), values);
}
NeverDown(r => r.LampShadows);
NeverDown(r => r.ContactShadows);
NeverDown(r => r.Occlusion);
NeverDown(r => r.OcclusionSlices);
NeverDown(r => r.OcclusionSteps);
NeverDown(r => r.CabProbe);
NeverDown(r => r.ScreenReflections);
NeverDown(r => r.FogQuality);
NeverDown(r => r.Clouds);
TurnsOn(r => r.OcclusionLighting);
TurnsOn(r => r.CabProbeReflections);
TurnsOn(r => r.RayTracing);
TurnsOn(r => r.VolumetricFog);
TurnsOn(r => r.CloudShadows);
TurnsOn(r => r.Grass);
TurnsOn(r => r.Bloom);
Climbs(p => p.NewRenderer.GrassDistance, 0);
Climbs(p => p.NewRenderer.GrassDensity, 0);
Climbs(p => p.NewRenderer.Precipitation, 1);
// Frames between refreshes, so the dearer the fewer.
Climbs(p => -p.NewRenderer.CabProbeInterval, 2);
}
[Fact]
public void Ultra_is_the_top_of_the_new_renderers_scales()
{
var ultra = GraphicsPreset.Ultra.NewRenderer;
Assert.Equal(3, ultra.LampShadows);
Assert.Equal(3, ultra.ContactShadows);
Assert.Equal(2, ultra.Occlusion);
Assert.Equal((6, 8), (ultra.OcclusionSlices, ultra.OcclusionSteps));
Assert.Equal(3, ultra.CabProbe);
Assert.Equal(3, ultra.ScreenReflections);
Assert.True(ultra.RayTracing && ultra.VolumetricFog);
Assert.Equal(4, ultra.FogQuality);
Assert.Equal(4, ultra.Clouds);
Assert.Equal(300, ultra.GrassDistance);
Assert.Equal(2.0, ultra.GrassDensity);
Assert.Equal(262144, ultra.Precipitation);
}
[Fact]
public void Grass_fades_out_beyond_where_it_is_drawn_in_full()
{
var store = new TestInstallation().SettingsStore;
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
preset.ApplyTo(settings);
Assert.True(int.Parse(store.Render(settings)["gfx.grass.fadedistance"]) > preset.NewRenderer.GrassDistance, preset.NameKey);
}
}
[Fact]
public void A_level_set_in_the_new_renderers_rows_is_told_from_the_others()
{
var settings = Defaults().Copy();
GraphicsPreset.Medium.ApplyTo(settings);
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
settings.FogQuality = 4;
Assert.Null(GraphicsPreset.Matching(settings));
}
[Fact]
public void What_is_left_to_the_player_stays_through_a_level()
{
var settings = Defaults().Copy();
settings.RenderEngine = SimulatorSettings.VulkanEngine;
settings.AntiAliasing = AntiAliasingMode.Dlss;
settings.FrameGeneration = 2;
settings.VulkanDevice = "RTX";
foreach (var preset in GraphicsPreset.All)
{
preset.ApplyTo(settings);
Assert.Same(preset, GraphicsPreset.Matching(settings));
Assert.Equal(AntiAliasingMode.Dlss, settings.AntiAliasing);
Assert.Equal(2, settings.FrameGeneration);
Assert.Equal("RTX", settings.VulkanDevice);
}
}
[Fact]
public void Ultra_is_the_top_of_everything_the_screen_offers()
public void Ultra_is_the_top_of_what_the_old_starter_offered()
{
var ultra = GraphicsPreset.Ultra;
double Top(string key) => SimulatorKeys.Named(key).Maximum;
Assert.Equal(8192, ultra.TextureSize);
Assert.Equal(8192, ultra.CabTextureSize);
Assert.Equal(GraphicsRules.MaxCabTextureSize, ultra.CabTextureSize);
Assert.Equal(8192, ultra.ShadowMap);
Assert.Equal(600, ultra.ShadowRange);
Assert.Equal(GraphicsRules.MaxShadowRange, ultra.ShadowRange);
Assert.Equal(Steps.Anisotropy.Max(), ultra.Anisotropy);
Assert.Equal(AntiAliasingMode.Msaa8, ultra.AntiAliasing);
Assert.Equal(Steps.ReflectionUpdates.Max(), ultra.ReflectionsRate);
Assert.Equal(SliderRanges.ReflectionUpdates.Max(), ultra.ReflectionsRate);
Assert.Equal(4, ultra.SmokeFidelity);
Assert.Equal(4, ultra.SplineFidelity);
Assert.Equal(200, ultra.BufferScale);
Assert.Equal(Top(GraphicsPreset.DrawRangeKey), ultra.DrawRange);
Assert.Equal(Top(GraphicsPreset.DistanceFactorKey), ultra.DistanceFactor);
Assert.Equal(Top(GraphicsPreset.SleeperKey), ultra.SleeperDistance);
Assert.Equal(Steps.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
Assert.Equal(Top(GraphicsPreset.ReflectedInstancesKey), ultra.ReflectedInstances);
Assert.Equal(Top(GraphicsPreset.ReflectedVehiclesKey), ultra.ReflectedVehicles);
Assert.Equal(SliderRanges.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
Assert.Equal(100, ultra.CabShadowsRange);
var extras = ultra.Extras!;
Assert.Equal(200, extras.PythonUpdateMs);
Assert.True(extras.MotionBlur && extras.ChromaticAberration && extras.Smoke);
var top = ultra.Top!;
Assert.Equal(Top(GraphicsTop.ScreenWindowFpsKey), top.ScreenWindowFps);
Assert.True(top.Screens && top.ScreenMipmaps && top.Sky && top.Cab && top.AirCouplers && top.SmoothTraction);
Assert.True(ultra.Top!.Screens);
}
[Fact]
public void At_ultra_what_would_only_take_away_is_off()
public void No_level_goes_past_what_the_old_starter_gave()
{
var top = GraphicsPreset.Ultra.Top!;
foreach (var preset in GraphicsPreset.All)
{
Assert.True(preset.ShadowRange <= GraphicsRules.MaxShadowRange, preset.NameKey);
Assert.True(preset.CabTextureSize <= GraphicsRules.MaxCabTextureSize, preset.NameKey);
}
}
// The longest shadows, the bottom of that scale.
Assert.Equal(0.2, top.ShadowAngleLimit);
Assert.Equal(0, top.TargetFps);
Assert.Equal(0, top.TextureRelease);
Assert.False(top.CompressTextures);
Assert.False(top.SkipDecor);
[Fact]
public void No_level_sets_what_only_the_advanced_mode_shows()
{
var set = GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys).ToList();
// The rows of keys by name, the buffer and the resources are all the advanced mode's.
Assert.Empty(set.Intersect(SimulatorKeys.All.Select(key => key.Key)));
Assert.Empty(set.Intersect(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height",
"compresstex", "python.mipmaps", "gfx.skippipeline" }));
}
[Fact]
public void A_level_leaves_what_only_the_advanced_mode_shows_as_it_is()
{
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
settings.BufferScalePercent = 80;
settings.CompressTextures = false;
settings.ScreenMipmaps = false;
settings.Extra["basedrawrange"] = "3000";
settings.Extra["targetfps"] = "60";
preset.ApplyTo(settings);
Assert.Equal(80, settings.BufferScalePercent);
Assert.False(settings.CompressTextures);
Assert.False(settings.ScreenMipmaps);
Assert.Equal("3000", settings.Extra["basedrawrange"]);
Assert.Equal("60", settings.Extra["targetfps"]);
Assert.Same(preset, GraphicsPreset.Matching(settings));
}
}
[Fact]
public void At_ultra_the_shadows_are_longest()
{
// The bottom of that scale.
Assert.Equal(0.2, GraphicsPreset.Ultra.Top!.ShadowAngleLimit);
}
[Fact]
@@ -304,16 +240,14 @@ public class GraphicsPresetTests
var settings = Defaults().Copy();
settings.ShadowAngleLimit = 0.8;
settings.IgnoreIrrelevantTrains = true;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
settings.Extra[GraphicsTop.TextureReleaseKey] = "2";
settings.PythonScreens = false;
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
Assert.Equal(0.2, settings.ShadowAngleLimit);
Assert.False(settings.IgnoreIrrelevantTrains);
Assert.Equal("0", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Equal("0", settings.Extra[GraphicsTop.TextureReleaseKey]);
Assert.True(settings.PythonScreens);
Assert.True(settings.IgnoreIrrelevantTrains);
}
[Fact]
@@ -335,12 +269,12 @@ public class GraphicsPresetTests
{
var settings = Defaults().Copy();
settings.IgnoreIrrelevantTrains = true;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
settings.ShadowAngleLimit = 0.8;
preset.ApplyTo(settings);
Assert.True(settings.IgnoreIrrelevantTrains, preset.NameKey);
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Equal(0.8, settings.ShadowAngleLimit);
Assert.Same(preset, GraphicsPreset.Matching(settings));
}
}
@@ -352,26 +286,11 @@ public class GraphicsPresetTests
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
settings.Extra[GraphicsPreset.ReflectedVehiclesKey] = "250";
settings.ReflectionsFramerate = 25;
Assert.Null(GraphicsPreset.Matching(settings));
}
[Fact]
public void No_level_asks_for_a_range_the_renderer_would_raise_anyway()
{
Assert.All(GraphicsPreset.All, preset => Assert.True(preset.DrawRange >= 2000, preset.NameKey));
}
[Fact]
public void The_view_only_shortens_going_down_the_levels()
{
var factors = GraphicsPreset.All.Select(preset => preset.DistanceFactor).ToList();
Assert.Equal(factors.OrderBy(factor => factor), factors);
Assert.Equal(1, GraphicsPreset.High.DistanceFactor);
}
[Fact]
public void Shadows_reach_further_with_every_level_that_has_them()
{
@@ -405,29 +324,17 @@ public class GraphicsPresetTests
}
[Fact]
public void Every_level_sets_the_buffer_and_is_not_recognised_with_another()
public void Every_level_is_within_what_the_sliders_offer()
{
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
settings.BufferScalePercent = 120;
preset.ApplyTo(settings);
Assert.Equal(preset.BufferScale, settings.BufferScalePercent);
settings.BufferScalePercent = 120;
Assert.Null(GraphicsPreset.Matching(settings));
Assert.True(preset.TextureSize >= SliderRanges.MinTextureSize, preset.NameKey);
Assert.True(preset.ShadowMap >= SliderRanges.MinShadowMap, preset.NameKey);
Assert.True(preset.DynamicLights >= SliderRanges.MinDynamicLights, preset.NameKey);
Assert.Contains(preset.ReflectionsRate, SliderRanges.ReflectionUpdates);
}
}
[Fact]
public void The_buffer_is_the_screen_at_high_and_climbs_through_it()
{
Assert.Equal(100, GraphicsPreset.High.BufferScale);
Assert.Equal(200, GraphicsPreset.Ultra.BufferScale);
Assert.InRange(GraphicsPreset.Minimal.BufferScale, 50, 100);
}
[Fact]
public void The_lowest_level_is_not_recognised_with_one_of_its_extras_undone()
{
@@ -453,14 +360,13 @@ public class GraphicsPresetTests
{
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
settings.ShadowAngleLimit = 0.8;
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Medium, settings);
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
Assert.False(settings.MotionBlur);
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
Assert.Equal(0.8, settings.ShadowAngleLimit);
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
}
@@ -474,14 +380,12 @@ public class GraphicsPresetTests
var entering = memory.Apply(GraphicsPreset.Minimal, settings);
Assert.Equal(GraphicsPreset.Minimal.Extras, GraphicsExtras.Of(settings));
Assert.Equal(GraphicsPreset.RowKeys, entering.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), entering.ChosenKeys);
var leaving = memory.Apply(GraphicsPreset.Medium, settings);
Assert.Equal(before, GraphicsExtras.Of(settings));
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys, leaving.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), leaving.ChosenKeys);
}
@@ -492,7 +396,6 @@ public class GraphicsPresetTests
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.ShadowAngleLimit = 0.8;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
var extras = GraphicsExtras.Of(settings);
var top = GraphicsTop.Of(settings);
@@ -502,7 +405,6 @@ public class GraphicsPresetTests
Assert.Equal(extras, GraphicsExtras.Of(settings));
Assert.Equal(top, GraphicsTop.Of(settings));
Assert.Same(GraphicsPreset.VeryHigh, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys), applied.ChosenKeys);
}
@@ -512,12 +414,11 @@ public class GraphicsPresetTests
var settings = Defaults().Copy();
GraphicsPreset.Ultra.ApplyTo(settings);
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings);
new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings);
Assert.Equal(GraphicsExtras.None, GraphicsExtras.Of(settings));
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(settings));
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
}
[Fact]
@@ -526,19 +427,18 @@ public class GraphicsPresetTests
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.ShadowAngleLimit = 0.8;
var extras = GraphicsExtras.Of(settings);
var top = GraphicsTop.Of(settings);
memory.Apply(GraphicsPreset.Minimal, settings);
var toUltra = memory.Apply(GraphicsPreset.Ultra, settings);
memory.Apply(GraphicsPreset.Ultra, settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toUltra.RowKeys);
var toMinimal = memory.Apply(GraphicsPreset.Minimal, settings);
memory.Apply(GraphicsPreset.Minimal, settings);
Assert.Same(GraphicsPreset.Minimal, GraphicsPreset.Matching(settings));
// Ultra's own values go, Minimal has no say over them.
Assert.Equal(top, GraphicsTop.Of(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toMinimal.RowKeys);
memory.Apply(GraphicsPreset.Medium, settings);
Assert.Equal(extras, GraphicsExtras.Of(settings));
@@ -560,7 +460,6 @@ public class GraphicsPresetTests
var applied = memory.Apply(GraphicsPreset.High, settings);
Assert.True(settings.MotionBlur);
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
}
@@ -596,33 +495,15 @@ public class GraphicsPresetTests
[Fact]
public void Every_level_sits_on_the_steps_the_screen_offers()
{
void OnSteps(double value, string name)
{
var key = SimulatorKeys.Named(name);
Assert.InRange(value, key.Minimum, key.Maximum);
double steps = value / key.Step;
Assert.Equal(Math.Round(steps), steps, 6);
}
foreach (var preset in GraphicsPreset.All)
{
OnSteps(preset.DistanceFactor, GraphicsPreset.DistanceFactorKey);
OnSteps(preset.DrawRange, GraphicsPreset.DrawRangeKey);
OnSteps(preset.SleeperDistance, GraphicsPreset.SleeperKey);
OnSteps(preset.ReflectedInstances, GraphicsPreset.ReflectedInstancesKey);
OnSteps(preset.ReflectedVehicles, GraphicsPreset.ReflectedVehiclesKey);
Assert.InRange(preset.NewRenderer.CabProbeInterval, 1, 120);
Assert.InRange(preset.NewRenderer.GrassDistance, 20, 300);
Assert.Equal(0, preset.NewRenderer.GrassDistance % 10);
Assert.Equal(0, preset.NewRenderer.GrassDensity % 0.25);
Assert.Contains(preset.NewRenderer.Precipitation, new[] { 16384, 32768, 65536, 131072, 262144 });
Assert.True(Steps.IndexOf(Steps.Anisotropy, preset.Anisotropy) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(Steps.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(Steps.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(SliderRanges.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(SliderRanges.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
foreach (int size in new[] { preset.TextureSize, preset.CabTextureSize, preset.ShadowMap })
Assert.True(size is >= 512 and <= 8192 && (size & (size - 1)) == 0, preset.NameKey);
Assert.True(preset.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), preset.NameKey);
Assert.Equal(0, preset.CabShadowsRange % 10);
Assert.True(Steps.IndexOf(SliderRanges.CabShadowRanges, preset.CabShadowsRange) >= 0, preset.NameKey);
}
}
@@ -637,7 +518,7 @@ public class GraphicsPresetTests
Assert.Equal(inGroups.Distinct(), inGroups);
Assert.Empty(inGroups.Except(GraphicsPreset.Keys).Except(GraphicsExtras.Keys).Except(GraphicsTop.Keys));
Assert.Equal(new[] { "gfx.antialiasing", "gfx.buffer.percent", "gfx.extraeffects", "gfx.postfx.bloom", "multisampling", "starter.bufferscale" },
Assert.Equal(new[] { "dynamiclights", "gfx.extraeffects", "gfx.smoke.fidelity", "multisampling" },
GraphicsPreset.Keys.Except(inGroups).OrderBy(key => key, StringComparer.Ordinal));
}
@@ -669,27 +550,22 @@ public class GraphicsPresetTests
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.All(Groups().LevelsOf(settings).Values, level => Assert.Same(GraphicsPreset.Ultra, level));
// The row of a key at the simulator's own value leaves it out of the file.
settings.Extra.Remove(GraphicsTop.TextureReleaseKey);
Assert.Same(GraphicsPreset.Ultra, Groups().LevelsOf(settings)[GraphicsGroup.Textures]);
}
[Fact]
public void A_part_moved_by_hand_is_at_no_level_and_the_others_keep_theirs()
{
var settings = AtHigh();
settings.DynamicLights = 6;
settings.ReflectionsFidelity = 0;
var levels = Groups().LevelsOf(settings);
Assert.Null(levels[GraphicsGroup.Lights]);
Assert.Null(levels[GraphicsGroup.Reflections]);
Assert.Same(GraphicsPreset.High, levels[GraphicsGroup.Shadows]);
}
[Fact]
public void Every_part_at_a_level_and_the_buffer_with_it_is_that_level()
public void Every_part_at_a_level_and_the_rest_with_it_is_that_level()
{
var groups = Groups();
foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null))
@@ -697,8 +573,9 @@ public class GraphicsPresetTests
var settings = Defaults().Copy();
foreach (var group in GraphicsGroup.All)
settings = groups.Apply(group, level, settings);
settings.BufferScalePercent = level.BufferScale;
settings.AntiAliasing = level.AntiAliasing;
settings.DynamicLights = level.DynamicLights;
settings.SmokeFidelity = level.SmokeFidelity;
Assert.Same(level, GraphicsPreset.Matching(settings));
}
@@ -718,14 +595,15 @@ public class GraphicsPresetTests
{
var groups = Groups();
var settings = AtHigh();
settings.ShadowAngleLimit = 0.8;
var ultra = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.Ultra, settings);
Assert.False(ultra.CompressTextures);
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Textures]);
var ultra = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.Ultra, settings);
Assert.Equal(0.2, ultra.ShadowAngleLimit);
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Shadows]);
var back = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.High, ultra);
Assert.Equal(GraphicsTop.None.CompressTextures, back.CompressTextures);
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Textures]);
var back = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.High, ultra);
Assert.Equal(GraphicsTop.None.ShadowAngleLimit, back.ShadowAngleLimit);
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Shadows]);
}
[Fact]
@@ -736,8 +614,9 @@ public class GraphicsPresetTests
settings.Smoke = false;
var nature = Groups().Apply(GraphicsGroup.Nature, GraphicsPreset.VeryHigh, settings);
Assert.False(nature.Smoke);
Assert.Equal(GraphicsPreset.VeryHigh.SmokeFidelity, nature.SmokeFidelity);
var shadows = Groups().Apply(GraphicsGroup.Shadows, GraphicsPreset.VeryHigh, settings);
Assert.False(shadows.Smoke);
Assert.False(shadows.MotionBlur);
Assert.Equal(GraphicsPreset.VeryHigh.ShadowMap, shadows.ShadowMapResolution);
}
}

View File

@@ -17,17 +17,17 @@ public class GraphicsSettingsTests
return installation;
}
private static SimulatorSettings Read(string text, bool dlssPlatform = true)
private static SimulatorSettings Read(string text)
{
var s = new SimulatorSettings();
new SettingsSerializer(dlssPlatform).Read(s, ConfigFile.Parse(text));
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
return s;
}
private static string Write(SimulatorSettings s, string text = "", bool dlssPlatform = true)
private static string Write(SimulatorSettings s, string text = "")
{
var c = ConfigFile.Parse(text);
new SettingsSerializer(dlssPlatform).Write(s, c);
new SettingsSerializer().Write(s, c);
return c.ToText();
}
@@ -37,63 +37,54 @@ public class GraphicsSettingsTests
private static string? Line(string text, string key) =>
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
// As application.cpp on master has them: a word it does not know gets the full renderer.
[Theory]
[InlineData("full", GraphicsBackend.OpenGL)]
[InlineData("default", GraphicsBackend.OpenGL)]
[InlineData("gl46", GraphicsBackend.OpenGL)]
[InlineData("legacy", GraphicsBackend.OpenGL)]
[InlineData("experimental", GraphicsBackend.OpenGL)]
[InlineData("vulkan", GraphicsBackend.Vulkan)]
[InlineData("vulkan14", GraphicsBackend.Vulkan)]
public void The_renderer_is_read_with_the_aliases_the_simulator_takes(string value, GraphicsBackend expected)
{
Assert.Equal(expected, Read($"gfxrenderer {value}\n").Backend);
}
[Theory]
[InlineData("full", "full")]
[InlineData("gl46", "full")]
[InlineData("default", "default")]
[InlineData("full", "default")]
[InlineData("gl46", "default")]
[InlineData("vulkan", "default")]
[InlineData("vulkan14", "default")]
[InlineData("legacy", "legacy")]
[InlineData("simpleshader", "legacy")]
[InlineData("off", "legacy")]
[InlineData("simple", "simple")]
[InlineData("experimental", "experimental")]
[InlineData("vulkan14", "vulkan")]
public void A_renderer_is_written_by_its_name(string read, string written)
[InlineData("experimental", "default")]
public void A_renderer_is_written_by_the_name_master_knows(string read, string written)
{
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
}
[Fact]
public void Without_a_renderer_in_the_file_the_full_one_is_chosen()
{
Assert.Equal(0, Read("").RenderEngine);
Assert.Equal("gfxrenderer default", Line(Write(Read("")), "gfxrenderer"));
}
[Fact]
public void An_older_renderer_stays_chosen_and_can_be_chosen_again()
{
var installation = WithIni("gfxrenderer legacy\n");
var store = installation.SettingsStore;
store.Settings.Clouds = 3;
store.Settings.FieldOfView = 50;
store.Save();
Assert.Contains("gfxrenderer legacy", installation.Files.ReadAllText(UserIni));
store.Settings.RenderEngine = SimulatorSettings.VulkanEngine;
store.Save();
Assert.Contains("gfxrenderer vulkan", installation.Files.ReadAllText(UserIni));
Assert.Equal(GraphicsBackend.Vulkan, store.Settings.Backend);
store.Settings.RenderEngine = SimulatorSettings.RenderEngineOf("simple");
store.Save();
Assert.Contains("gfxrenderer simple", installation.Files.ReadAllText(UserIni));
Assert.Equal(GraphicsBackend.OpenGL, store.Settings.Backend);
}
[Fact]
public void Keys_only_an_older_simulator_reads_stay_in_the_file()
public void Keys_only_the_legacy_renderer_or_windows_read_stay_in_the_file()
{
string[] old =
{
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes",
"gfx.framebuffer.width 1920", "gfx.framebuffer.height 1080", "gfx.shadows.cab.range 20"
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes", "gfx.shadows.cab.range 20"
};
var installation = WithIni(string.Join("\n", old) + "\n");
installation.SettingsStore.Settings.Clouds = 3;
installation.SettingsStore.Settings.FieldOfView = 50;
installation.SettingsStore.Save();
@@ -101,6 +92,24 @@ public class GraphicsSettingsTests
Assert.All(old, line => Assert.Contains(line, saved));
}
[Fact]
public void Keys_of_the_vulkan_renderer_master_does_not_have_go_on_a_save()
{
string[] vulkan =
{
"gfx.antialiasing dlss", "gfx.dlss.preset k", "gfx.framegeneration x2", "gfx.reflex on",
"gfx.raytracing yes", "gfx.ssr high", "gfx.postfx.ao gtao", "gfx.clouds ultra", "gfx.grass yes",
"gfx.buffer.percent 0.67", "gfx.vulkan.device RTX", "gfx.fog yes", "gfx.cabprobe medium"
};
var installation = WithIni("calibratein 0 0 0 0\n" + string.Join("\n", vulkan) + "\n");
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0])));
}
[Fact]
public void Levels_leave_the_switches_only_an_older_simulator_reads()
{
@@ -111,160 +120,26 @@ public class GraphicsSettingsTests
Assert.Equal((false, true, true), (s.UseVbo, s.UseGLES, s.RenderAngleVulkan));
}
[Fact]
public void The_new_graphics_keys_are_read()
[Theory]
[InlineData("multisampling 0\n", AntiAliasingMode.Off)]
[InlineData("multisampling 1\n", AntiAliasingMode.Msaa2)]
[InlineData("multisampling 2\n", AntiAliasingMode.Msaa4)]
[InlineData("multisampling 3\n", AntiAliasingMode.Msaa8)]
[InlineData("", AntiAliasingMode.Msaa4)]
public void Multisampling_is_read_as_master_reads_it(string text, AntiAliasingMode expected)
{
var s = Read("gfxrenderer vulkan\n" +
"gfx.antialiasing dlss\ngfx.dlss.preset K\ngfx.framegeneration x3\ngfx.reflex boost\n" +
"gfx.raytracing yes\ngfx.raytracing.range 800\ngfx.ssr high\ngfx.postfx.ao ssao\ngfx.postfx.ao.quality 4 6\n" +
"gfx.lights.shadows low\ngfx.contactshadows 3\ngfx.fog analytic\ngfx.fog.quality ultra\n" +
"gfx.clouds ultra\ngfx.clouds.shadows no\ngfx.grass no\ngfx.grass.distance 120\ngfx.grass.density 1.5\n" +
"gfx.buffer.percent 0.67\ngfx.vulkan.device RTX\n");
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
Assert.Equal("k", s.DlssPreset);
Assert.Equal(3, s.FrameGeneration);
Assert.Equal(2, s.Reflex);
Assert.True(s.RayTracing);
Assert.Equal(800, s.RayTracingRange);
Assert.Equal(3, s.Ssr);
Assert.Equal(1, s.AmbientOcclusion);
Assert.Equal((4, 6), (s.AoSlices, s.AoSteps));
Assert.Equal(1, s.LightShadows);
Assert.Equal(3, s.ContactShadows);
Assert.False(s.VolumetricFog);
Assert.Equal(4, s.FogQuality);
Assert.Equal(4, s.Clouds);
Assert.False(s.CloudShadows);
Assert.False(s.Grass);
Assert.Equal(120, s.GrassDistance);
Assert.Equal(1.5, s.GrassDensity);
Assert.Equal(67, s.BufferScalePercent);
Assert.Equal("RTX", s.VulkanDevice);
Assert.Equal(expected, Read(text).AntiAliasing);
}
[Fact]
public void Missing_keys_take_the_simulators_defaults()
{
var s = Read("");
Assert.Equal(GraphicsBackend.OpenGL, s.Backend);
Assert.Equal(AntiAliasingMode.Msaa4, s.AntiAliasing);
Assert.Equal(2, s.Ssr);
Assert.Equal(2, s.AmbientOcclusion);
Assert.Equal(2, s.LightShadows);
Assert.Equal(0, s.ContactShadows);
Assert.True(s.VolumetricFog);
Assert.Equal(2, s.FogQuality);
Assert.Equal(2, s.Clouds);
Assert.False(s.RayTracing);
Assert.Equal(1, s.FrameGeneration);
}
[Fact]
public void The_tokens_written_are_the_ones_the_simulator_parses()
{
var s = Read("gfxrenderer vulkan\n");
s.AntiAliasing = AntiAliasingMode.Dlaa;
s.FrameGeneration = 4;
s.Reflex = 1;
s.LightShadows = 3;
s.ContactShadows = 0;
s.Clouds = 4;
s.VolumetricFog = false;
s.FogQuality = 1;
s.AmbientOcclusion = 1;
s.Ssr = 2;
s.RayTracing = true;
string text = Write(s);
Assert.Equal("gfx.antialiasing dlaa", Line(text, "gfx.antialiasing"));
Assert.Equal("multisampling 0", Line(text, "multisampling"));
Assert.Equal("gfx.framegeneration x4", Line(text, "gfx.framegeneration"));
Assert.Equal("gfx.reflex on", Line(text, "gfx.reflex"));
Assert.Equal("gfx.lights.shadows high", Line(text, "gfx.lights.shadows"));
Assert.Equal("gfx.contactshadows no", Line(text, "gfx.contactshadows"));
Assert.Equal("gfx.clouds ultra", Line(text, "gfx.clouds"));
Assert.Equal("gfx.fog analytic", Line(text, "gfx.fog"));
Assert.Equal("gfx.fog.quality low", Line(text, "gfx.fog.quality"));
Assert.Equal("gfx.postfx.ao ssao", Line(text, "gfx.postfx.ao"));
Assert.Equal("gfx.ssr medium", Line(text, "gfx.ssr"));
Assert.Equal("gfx.raytracing yes", Line(text, "gfx.raytracing"));
Assert.Equal("gfx.buffer.percent 100", Line(text, "gfx.buffer.percent"));
}
[Fact]
public void Msaa_is_written_to_both_keys_for_older_simulators()
public void Multisampling_is_written_to_its_own_key_only()
{
var s = Read("multisampling 1\n");
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
string text = Write(s);
Assert.Equal("multisampling 1", Line(text, "multisampling"));
Assert.Equal("gfx.antialiasing msaax2", Line(text, "gfx.antialiasing"));
}
[Fact]
public void Of_the_two_anti_aliasing_keys_the_later_one_wins_as_in_the_simulator()
{
Assert.Equal(AntiAliasingMode.Taa, Read("multisampling 2\ngfx.antialiasing taa\n").AntiAliasing);
Assert.Equal(AntiAliasingMode.Msaa4, Read("gfx.antialiasing taa\nmultisampling 2\n").AntiAliasing);
}
[Fact]
public void On_opengl_the_vulkan_only_features_are_written_off()
{
var s = Read("gfxrenderer full\ngfx.antialiasing dlss\ngfx.framegeneration x2\ngfx.reflex on\ngfx.raytracing yes\n");
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
Assert.Equal(1, s.FrameGeneration);
Assert.Equal(0, s.Reflex);
Assert.False(s.RayTracing);
string text = Write(s);
Assert.Equal("gfx.antialiasing taa", Line(text, "gfx.antialiasing"));
Assert.Equal("gfx.framegeneration off", Line(text, "gfx.framegeneration"));
Assert.Equal("gfx.reflex off", Line(text, "gfx.reflex"));
Assert.Equal("gfx.raytracing no", Line(text, "gfx.raytracing"));
}
[Fact]
public void Frame_generation_needs_dlss_even_on_vulkan()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing taa\ngfx.framegeneration x2\ngfx.reflex on\n");
Assert.Equal(1, s.FrameGeneration);
Assert.Equal(1, s.Reflex);
Assert.False(GraphicsRules.ReflexForced(s, true));
}
[Fact]
public void Frame_generation_turns_reflex_on()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\ngfx.framegeneration x2\n");
Assert.True(GraphicsRules.ReflexForced(s, true));
}
[Fact]
public void Without_a_dlss_platform_dlss_falls_back_to_taa()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\n", dlssPlatform: false);
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
}
[Fact]
public void Dlaa_ignores_the_render_scale()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlaa\n");
Assert.False(GraphicsRules.BufferScaleUsed(s, true));
s.AntiAliasing = AntiAliasingMode.Dlss;
Assert.True(GraphicsRules.BufferScaleUsed(s, true));
Assert.Null(Line(text, "gfx.antialiasing"));
}
[Fact]
@@ -278,10 +153,101 @@ public class GraphicsSettingsTests
}
[Fact]
public void The_render_scale_reads_the_old_starter_key_when_the_new_one_is_missing()
public void The_render_scale_is_the_starters_own_key_or_the_framebuffer_against_the_window()
{
Assert.Equal(75, Read("starter.bufferscale 75\n").BufferScalePercent);
Assert.Equal(50, Read("starter.bufferscale 75\ngfx.buffer.percent 50\n").BufferScalePercent);
Assert.Equal(50, Read("width 1920\ngfx.framebuffer.width 960\n").BufferScalePercent);
Assert.Equal(100, Read("").BufferScalePercent);
}
[Fact]
public void The_render_scale_is_written_as_the_framebuffer_master_reads()
{
var s = Read("width 1920\nheight 1080\nstarter.bufferscale 50\n");
string text = Write(s);
Assert.Equal("gfx.framebuffer.width 960", Line(text, "gfx.framebuffer.width"));
Assert.Equal("gfx.framebuffer.height 540", Line(text, "gfx.framebuffer.height"));
Assert.Null(Line(text, "gfx.buffer.percent"));
}
// Borderless, the simulator takes the window's size from the monitor (application.cpp) and
// leaves width and height unread; -1 is its own word for a buffer of the window's size
// (opengl33renderer.cpp).
[Fact]
public void A_borderless_screen_draws_into_a_buffer_of_the_windows_own_size()
{
var s = Read("fullscreenwindowed yes\nwidth 1280\nheight 720\n");
string text = Write(s);
Assert.Equal("gfx.framebuffer.width -1", Line(text, "gfx.framebuffer.width"));
Assert.Equal("gfx.framebuffer.height -1", Line(text, "gfx.framebuffer.height"));
Assert.Equal("width 1280", Line(text, "width"));
Assert.Equal(100, Read(text).BufferScalePercent);
}
[Fact]
public void A_borderless_screen_with_a_smaller_buffer_takes_its_part_of_the_monitor()
{
var s = Read("fullscreenwindowed yes\nfullscreenmonitor HDMI-1:1920,0\nwidth 1280\nheight 720\nstarter.bufferscale 50\n");
var asked = new List<string>();
var serializer = new SettingsSerializer(id =>
{
asked.Add(id);
return (2560, 1440);
});
var c = new ConfigFile();
serializer.Write(s, c);
Assert.Equal("1280", c.GetRaw("gfx.framebuffer.width"));
Assert.Equal("720", c.GetRaw("gfx.framebuffer.height"));
Assert.Equal("50", c.GetRaw("starter.bufferscale"));
Assert.Equal(new[] { "HDMI-1:1920,0" }, asked.Distinct());
var read = new SimulatorSettings();
serializer.Read(read, c);
Assert.Equal(50, read.BufferScalePercent);
}
[Fact]
public void A_borderless_screen_on_a_monitor_of_unknown_size_keeps_the_windows_own_buffer()
{
var s = Read("fullscreenwindowed yes\nwidth 1280\nheight 720\nstarter.bufferscale 50\n");
var c = new ConfigFile();
new SettingsSerializer(_ => null).Write(s, c);
Assert.Equal("-1", c.GetRaw("gfx.framebuffer.width"));
Assert.Equal("-1", c.GetRaw("gfx.framebuffer.height"));
}
[Fact]
public void A_buffer_of_the_window_left_in_a_borderless_file_goes_on_a_save()
{
// As this starter wrote it before: the size of the resolution row, which borderless does not use.
var installation = WithIni("fullscreenwindowed yes\nwidth 1280\nheight 720\nstarter.bufferscale 100\n" +
"gfx.framebuffer.width 1280\ngfx.framebuffer.height 720\n");
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Equal("gfx.framebuffer.width -1", Line(saved, "gfx.framebuffer.width"));
Assert.Equal("gfx.framebuffer.height -1", Line(saved, "gfx.framebuffer.height"));
}
[Fact]
public void A_buffer_the_file_has_for_a_window_or_a_full_screen_stays_until_changed()
{
var installation = WithIni("fullscreenwindowed no\nwidth 1280\nheight 720\nstarter.bufferscale 100\n" +
"gfx.framebuffer.width 1280\ngfx.framebuffer.height 720\n");
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Equal("gfx.framebuffer.width 1280", Line(saved, "gfx.framebuffer.width"));
Assert.Equal("gfx.framebuffer.height 720", Line(saved, "gfx.framebuffer.height"));
}
[Fact]
@@ -312,7 +278,7 @@ public class GraphicsSettingsTests
{
var s = new SimulatorSettings();
GraphicsPreset.High.ApplyTo(s);
s.Clouds = 4;
s.DynamicLights = 2;
Assert.Null(GraphicsPreset.Matching(s));
}
@@ -328,82 +294,62 @@ public class GraphicsSettingsTests
}
[Fact]
public void Ray_tracing_comes_with_ultra_on_vulkan_only()
public void No_level_leaves_decorative_consists_out()
{
var vulkan = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine };
var opengl = new SimulatorSettings();
foreach (var level in GraphicsPreset.All)
{
var s = new SimulatorSettings { IgnoreIrrelevantTrains = false };
level.ApplyTo(s);
Assert.False(s.IgnoreIrrelevantTrains, level.NameKey);
GraphicsPreset.Ultra.ApplyTo(vulkan);
GraphicsPreset.Ultra.ApplyTo(opengl);
Assert.True(vulkan.RayTracing);
Assert.False(opengl.RayTracing);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(opengl));
}
[Fact]
public void A_level_keeps_dlss_on_vulkan()
{
var s = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine, AntiAliasing = AntiAliasingMode.Dlss };
GraphicsPreset.Ultra.ApplyTo(s);
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(s));
}
[Fact]
public void A_level_replaces_taa_with_its_own_multisampling()
{
var s = new SimulatorSettings { AntiAliasing = AntiAliasingMode.Taa };
GraphicsPreset.Medium.ApplyTo(s);
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
s.IgnoreIrrelevantTrains = true;
level.ApplyTo(s);
Assert.True(s.IgnoreIrrelevantTrains, level.NameKey);
}
}
[Fact]
public void An_import_takes_the_settings_but_keeps_this_installations_simulator_and_the_unmanaged_lines()
{
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\ngfx.clouds low\n");
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\ngfx.clouds ultra\ngfxrenderer vulkan\n");
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\nfieldofview 45\n");
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\nfieldofview 60\ngfxrenderer legacy\n");
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
var s = installation.SettingsStore.Settings;
Assert.Equal(4, s.Clouds);
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
Assert.Equal(60, s.FieldOfView);
Assert.Equal(SimulatorSettings.RenderEngineOf("legacy"), s.RenderEngine);
Assert.Equal("eu07_local.exe", s.ExecutablePath);
// Nothing is written until saved, and the save keeps the user's own lines.
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
Assert.Contains("gfx.clouds ultra", saved);
Assert.Contains("fieldofview 60", saved);
Assert.Contains("starter.exe.path eu07_local.exe", saved);
}
[Fact]
public void An_import_of_a_missing_file_changes_nothing()
{
var installation = WithIni("gfx.clouds low\n");
var installation = WithIni("fieldofview 50\n");
Assert.False(installation.SettingsStore.ImportFrom("/nowhere/eu07.ini"));
Assert.Equal(1, installation.SettingsStore.Settings.Clouds);
Assert.Equal(50, installation.SettingsStore.Settings.FieldOfView);
}
[Fact]
public void An_export_writes_a_complete_file_elsewhere_and_leaves_the_users_one_alone()
{
var installation = WithIni("calibratein 0 0 0 0\ngfx.clouds low\n");
installation.SettingsStore.Settings.Clouds = 3;
var installation = WithIni("calibratein 0 0 0 0\nfieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
Assert.True(installation.SettingsStore.ExportTo("/export/eu07.ini"));
string exported = installation.Files.ReadAllText("/export/eu07.ini");
Assert.Contains("calibratein 0 0 0 0", exported);
Assert.Contains("gfx.clouds high", exported);
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
Assert.Contains("fieldofview 60", exported);
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
}
[Fact]
@@ -417,30 +363,34 @@ public class GraphicsSettingsTests
}
[Fact]
public void The_dlss_libraries_are_looked_for_next_to_a_windows_build()
public void The_gamepad_is_ignored_unless_the_file_turns_it_on()
{
var files = new InMemoryFileSystem()
.WithDirectory(TestInstallation.Root)
.WithExecutable(TestInstallation.At("eu07.exe"), "MZ binary")
.WithFile(TestInstallation.At("nvngx_dlss.dll"), "dll");
var installation = new TestInstallation(files);
Assert.Equal((true, false), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
files.WithFile(TestInstallation.At("nvngx_dlssg.dll"), "dll");
Assert.Equal((true, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
Assert.True(Read("").IgnoreGamepad);
Assert.Equal("input.gamepad no", Line(Write(Read("")), "input.gamepad"));
Assert.False(Read("input.gamepad yes\n").IgnoreGamepad);
Assert.True(Read("input.gamepad no\n").IgnoreGamepad);
}
[Fact]
public void The_dlss_libraries_of_a_linux_build_are_the_shared_objects()
public void The_standard_mode_is_where_a_player_starts_and_the_choice_is_kept()
{
var files = new InMemoryFileSystem()
.WithDirectory(TestInstallation.Root)
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
.WithFile(TestInstallation.At("libnvidia-ngx-dlssg.so.310.4.0"), "so");
var installation = new TestInstallation(files);
Assert.False(Read("").AdvancedSettings);
Assert.True(Read("starter.settings.advanced yes\n").AdvancedSettings);
Assert.Equal((false, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07")));
var s = Read("");
s.AdvancedSettings = true;
Assert.Equal("starter.settings.advanced yes", Line(Write(s), "starter.settings.advanced"));
}
[Fact]
public void The_move_to_the_standard_mode_is_marked_in_the_file()
{
Assert.False(Read("").MovedToStandard);
Assert.True(Read("starter.settings.standard yes\n").MovedToStandard);
var s = Read("");
s.MovedToStandard = true;
Assert.Equal("starter.settings.standard yes", Line(Write(s), "starter.settings.standard"));
}
[Fact]
@@ -455,139 +405,4 @@ public class GraphicsSettingsTests
c.Set("b", "9");
Assert.Equal("b 9\nc 3\na 1\n", c.ToText().Replace("\r\n", "\n"));
}
[Fact]
public void The_ao_lighting_and_cab_probe_keys_survive_a_round_trip_in_the_simulators_form()
{
var s = Read("gfx.postfx.ao.lighting no\ngfx.cabprobe high\ngfx.cabprobe.interval 12\ngfx.cabprobe.bounce 2.5\ngfx.cabprobe.reflections no\n");
Assert.False(s.AoLighting);
Assert.Equal(3, s.CabProbe);
Assert.Equal(12, s.CabProbeInterval);
Assert.Equal(2.5, s.CabProbeBounce);
Assert.False(s.CabProbeReflections);
string text = Write(s);
Assert.Equal("gfx.postfx.ao.lighting no", Line(text, "gfx.postfx.ao.lighting"));
Assert.Equal("gfx.cabprobe high", Line(text, "gfx.cabprobe"));
Assert.Equal("gfx.cabprobe.interval 12", Line(text, "gfx.cabprobe.interval"));
Assert.Equal("gfx.cabprobe.bounce 2.5", Line(text, "gfx.cabprobe.bounce"));
Assert.Equal("gfx.cabprobe.reflections no", Line(text, "gfx.cabprobe.reflections"));
var again = Read(text);
Assert.Equal((s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections),
(again.AoLighting, again.CabProbe, again.CabProbeInterval, again.CabProbeBounce, again.CabProbeReflections));
}
[Fact]
public void Missing_ao_lighting_and_cab_probe_keys_take_the_simulators_defaults_and_are_written_like_its_export()
{
var s = Read("");
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
string text = Write(s);
Assert.Equal("gfx.postfx.ao.lighting yes", Line(text, "gfx.postfx.ao.lighting"));
Assert.Equal("gfx.cabprobe medium", Line(text, "gfx.cabprobe"));
Assert.Equal("gfx.cabprobe.interval 4", Line(text, "gfx.cabprobe.interval"));
Assert.Equal("gfx.cabprobe.bounce 1", Line(text, "gfx.cabprobe.bounce"));
Assert.Equal("gfx.cabprobe.reflections yes", Line(text, "gfx.cabprobe.reflections"));
}
[Fact]
public void Unknown_ao_lighting_and_cab_probe_values_fall_back_to_the_simulators_defaults()
{
var s = Read("gfx.postfx.ao.lighting maybe\ngfx.cabprobe bogus\ngfx.cabprobe.interval abc\ngfx.cabprobe.bounce x\ngfx.cabprobe.reflections ?\n");
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
}
[Theory]
[InlineData("no", 0)]
[InlineData("0", 0)]
[InlineData("low", 1)]
[InlineData("1", 1)]
[InlineData("medium", 2)]
[InlineData("yes", 2)]
[InlineData("2", 2)]
[InlineData("high", 3)]
[InlineData("3", 3)]
public void The_cab_probe_level_is_read_with_the_aliases_the_simulator_takes(string value, int expected)
{
Assert.Equal(expected, Read($"gfx.cabprobe {value}\n").CabProbe);
}
[Fact]
public void The_cab_probe_numbers_are_kept_within_the_simulators_ranges()
{
var s = Read("gfx.cabprobe.interval 500\ngfx.cabprobe.bounce 9\n");
Assert.Equal((120, 4.0), (s.CabProbeInterval, s.CabProbeBounce));
s = Read("gfx.cabprobe.interval 0\ngfx.cabprobe.bounce -1\n");
Assert.Equal((1, 0.0), (s.CabProbeInterval, s.CabProbeBounce));
}
[Fact]
public void The_ao_lighting_counts_with_gtao_only()
{
Assert.True(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao gtao\n")));
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao ssao\n")));
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao no\n")));
}
[Theory]
[InlineData("gfx.ssr no\ngfx.contactshadows no\n", true)]
[InlineData("gfx.ssr low\ngfx.contactshadows no\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows low\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.depthprepass.scene yes\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao.lighting no\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao ssao\n", false)]
public void The_ao_lighting_adds_the_depth_pass_only_when_nothing_else_draws_it(string text, bool expected)
{
Assert.Equal(expected, GraphicsRules.AoLightingAddsDepthPrepass(Read(text)));
}
[Theory]
[InlineData("gfx.cabprobe medium\n", true, true)]
[InlineData("gfx.cabprobe no\n", false, false)]
[InlineData("gfx.cabprobe low\ngfx.lights.clustered no\n", true, false)]
[InlineData("gfx.cabprobe high\ngfx.lights.cab no\n", true, false)]
public void The_cab_probe_lights_the_cab_only_with_its_lamp_as_a_light(string text, bool used, bool lights)
{
var s = Read(text);
Assert.Equal(used, GraphicsRules.CabProbeUsed(s));
Assert.Equal(lights, GraphicsRules.CabProbeLights(s));
}
[Theory]
[InlineData(0, false, 0, 8, false)]
[InlineData(1, false, 0, 8, false)]
[InlineData(2, false, 1, 8, true)]
[InlineData(3, true, 2, 4, true)]
[InlineData(4, true, 3, 3, true)]
[InlineData(5, true, 3, 2, true)]
public void A_level_sets_the_ao_lighting_and_the_cab_probe(int place, bool aoLighting, int probe, int interval, bool reflections)
{
var level = GraphicsPreset.All[place];
var s = new SimulatorSettings { CabProbeBounce = 2.5 };
level.ApplyTo(s);
Assert.Equal((aoLighting, probe, interval, reflections), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeReflections));
Assert.Equal(2.5, s.CabProbeBounce);
Assert.Same(level, GraphicsPreset.Matching(s));
}
[Fact]
public void An_import_keeps_the_lamp_switch_of_the_users_own_file()
{
var installation = WithIni("gfx.lights.cab no\n");
installation.Files.WithFile("/backup/eu07.ini", "gfx.lights.cab yes\ngfx.cabprobe high\n");
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
Assert.False(installation.SettingsStore.Settings.CabLampLight);
Assert.Equal(3, installation.SettingsStore.Settings.CabProbe);
}
}

View File

@@ -6,12 +6,12 @@ namespace StarterNG.Tests;
public class HaslerTapeTests
{
private const string Header =
internal const string Header =
"Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " +
"BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " +
"Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n";
private static string Line(double t, double v, double brake, double current, string command = "none",
internal static string Line(double t, double v, double brake, double current, string command = "none",
int security = 0) =>
string.Create(CultureInfo.InvariantCulture,
$"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") +
@@ -68,6 +68,197 @@ public class HaslerTapeTests
Assert.Equal(5, tape.DistanceM, 6);
}
[Fact]
public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end()
{
// the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures
string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n");
static string WithSpeed(string line, double kmh) =>
line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n"));
// the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter
string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n",
" 0 1 0.0000 0.0000 0.0000 0.0000\r\n");
var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header()
{
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance()
{
// the player in another vehicle for ten minutes, then back in this one
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0)
+ Line(602, 36, 0, 0) + Line(603, 0, 0, 0));
Assert.Equal(603, tape.Duration, 6);
Assert.Equal(600, tape.GapTime, 6);
Assert.Equal(2, tape.RunningTime, 6);
Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping
Assert.Equal(10 + 10 + 5, tape.DistanceM, 6);
Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6);
}
[Fact]
public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap()
{
// a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after
var text = new System.Text.StringBuilder(Header);
double t = 0;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
t += 1.017 - 0.05;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
var tape = HaslerTape.Parse(text.ToString());
Assert.Equal(0, tape.GapTime, 6);
Assert.Equal(tape.Duration, tape.RunningTime, 6);
Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6);
}
[Fact]
public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole()
{
string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400)
+ Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0);
var whole = HaslerTape.Parse(text);
for (int cut = 1; cut < text.Length; cut += 7)
{
var reader = new HaslerTape.Reader();
reader.Feed(text[..cut]);
reader.Feed(text[cut..]);
Assert.Equal(whole.Samples, reader.Tape(final: true).Samples);
}
}
[Fact]
public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed()
{
var reader = new HaslerTape.Reader();
string line = Line(1, 36, 0, 0);
reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]);
Assert.Single(reader.Tape(final: false).Samples);
Assert.Single(reader.Tape(final: false).Samples);
reader.Feed(line[20..]);
Assert.Equal(2, reader.Tape(final: false).Samples.Count);
}
[Fact]
public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Single(tapes.Load(file, follow: false)!.Samples);
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0));
Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count);
// begun anew, and already longer than was read: its time goes back
files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0));
var tape = tapes.Load(file, follow: true)!;
Assert.Equal(4, tape.Samples.Count);
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
// begun anew, and shorter
files.WithFile(path, Header + Line(0, 18, 0, 0));
Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6);
}
[Fact]
public void A_log_begun_anew_over_the_end_that_was_read_is_read_whole_once_its_time_goes_back()
{
// the command is free text, here long enough that the end kept of the read part holds no time
string command = new('x', 400);
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(3, 36, 0, 0, command));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Equal(3, Assert.Single(tapes.Load(file, follow: false)!.Samples).Time, 6);
// begun anew: where the read part ended it reads as it did, but the lines added go back to the start
files.WithFile(path, Header + Line(0, 36, 0, 0, command) + Line(1, 36, 0, 0, command) + Line(2, 36, 0, 0, command));
var tape = tapes.Load(file, follow: true)!;
Assert.Equal([0.0, 1.0, 2.0], tape.Samples.Select(s => s.Time));
}
[Fact]
public void A_tape_that_cannot_be_read_is_none_and_told_and_is_read_whole_once_it_can()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
var installation = new TestInstallation(files);
var tapes = installation.Tapes;
var file = Assert.Single(tapes.List());
tapes.Load(file, follow: false);
files.FailReading(path);
Assert.Null(tapes.Load(file, follow: true));
Assert.Contains("EU07-424.dat", installation.Log.Text);
files.AllowReading(path).WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0));
Assert.All(tapes.Load(file, follow: true)!.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
}
[Fact]
public void A_file_read_only_forward_is_read_whole_each_time()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)).OpenedForwardOnly(path);
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Single(tapes.Load(file, follow: true)!.Samples);
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0));
Assert.Equal(2, tapes.Load(file, follow: true)!.Samples.Count);
}
[Fact]
public void Empty_lines_in_a_log_are_passed_over()
{
var tape = HaslerTape.Parse(Header + "\r\n" + Line(0, 36, 0, 0) + " \r\n" + Line(1, 36, 0, 0));
Assert.Equal(2, tape.Samples.Count);
}
[Fact]
public void Forgetting_another_file_keeps_the_followed_tape_and_its_own_lets_it_go()
{
string Lines(int firstSpeed, int count) =>
Header + Line(0, firstSpeed, 0, 0) + string.Concat(Enumerable.Range(1, count).Select(t => Line(t, 36, 0, 0)));
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Lines(36, 20));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
tapes.Load(file, follow: false);
// the first line changed, as long as it was and far from the end: a tape still followed doesn't read it again
files.WithFile(path, Lines(72, 21));
tapes.Forget(TestInstallation.At("physicslog", "EU07-111.dat"));
Assert.Equal(36, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
tapes.Forget(file.Path);
Assert.Equal(72, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
}
[Fact]
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
{

View File

@@ -0,0 +1,96 @@
using Avalonia.Controls;
using Avalonia.LogicalTree;
using StarterNG.Application;
using StarterNG.Domain.Tapes;
using StarterNG.Tests.Fakes;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>The tapes' window over the tapes of an installation of its own, read as it is opened.</summary>
[Collection(AvaloniaControls.Name)]
public class HaslerTapeWindowTests
{
private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc);
static HaslerTapeWindowTests() => HeadlessDrawing.Ensure();
private static AppServices Services(InMemoryFileSystem files)
{
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
return AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
// The window reads the tapes off the UI thread and shows them on it: what it shows is waited for.
private static void Until(Func<bool> shown) =>
Assert.True(SpinWait.SpinUntil(() =>
{
Controls.Settle();
return shown();
}, TimeSpan.FromSeconds(5)));
private static Button Button(Window window, string key) =>
window.GetLogicalDescendants().OfType<Button>().Single(b => b.Content as string == App.Loc[key]);
[Fact]
public void With_nothing_recorded_it_offers_to_record_and_turns_on_the_black_box_and_the_trains_tapes()
{
var services = Services(new InMemoryFileSystem());
var window = new HaslerTapeWindow();
bool told = false;
window.LogEnabled += () => told = true;
window.Show();
try
{
var strip = (Control)Button(window, "HaslerRecordingEnable").Parent!;
Until(() => strip.IsVisible);
Button(window, "HaslerRecordingEnable").RaiseEvent(Controls.Click());
Assert.True(services.Settings.BlackBox);
Assert.True(services.Settings.PhysicsLogTrains);
Assert.False(services.Settings.PhysicsLog);
Assert.True(told);
Assert.False(strip.IsVisible);
// the simulator's own log is on as it comes: nothing more to offer
Assert.False(((Control)Button(window, "HaslerLogEnable").Parent!).IsVisible);
}
finally
{
window.Close();
}
}
[Fact]
public void A_tape_of_the_last_launch_is_summed_up_with_its_scenario_and_train()
{
string path = TestInstallation.At("physicslog", "EP07-424.dat");
var files = new InMemoryFileSystem()
.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 36, 0, 0) + HaslerTapeTests.Line(60, 36, 0, 0));
var services = Services(files);
services.Tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "EP07-424", new[] { "EP07-424" },
"Tor doświadczalny", "EIE1531");
var window = new HaslerTapeWindow();
window.Show();
try
{
string scenario = string.Format(App.Loc["HaslerScenario"], "Tor doświadczalny");
var texts = window.GetLogicalDescendants().OfType<TextBlock>();
Until(() => texts.Any(t => t.Text?.Contains(scenario) == true));
string summary = texts.First(t => t.Text?.Contains(scenario) == true).Text!;
Assert.StartsWith("EP07-424", summary);
Assert.Contains(string.Format(App.Loc["HaslerTrain"], "EIE1531"), summary);
}
finally
{
window.Close();
}
// closed, the tape it read is no longer followed: begun anew and longer, it is read whole
files.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 72, 0, 0) + HaslerTapeTests.Line(1, 72, 0, 0)
+ HaslerTapeTests.Line(2, 72, 0, 0));
var tape = services.Tapes.Load(services.Tapes.List().Single(), follow: true)!;
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
}
}

View File

@@ -0,0 +1,87 @@
using Avalonia.Controls;
using Avalonia.LogicalTree;
using StarterNG.Application;
using StarterNG.Tests.Fakes;
using StarterNG.Views;
namespace StarterNG.Tests;
/// <summary>The starter's questions over its window, answered with the mouse or not at all.</summary>
[Collection(AvaloniaControls.Name)]
public class MessageBoxTests
{
// The buttons are labelled in the starter's language.
static MessageBoxTests()
{
HeadlessDrawing.Ensure();
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
private static (Window Owner, Window Dialog, Task<bool?> Answer) Choose()
{
var owner = new Window();
owner.Show();
var answer = MessageBox.Choose(owner, "Zapisać zmiany przed startem?", "Niezapisane zmiany", "Zapisz", "Nie zapisuj");
Controls.Settle();
return (owner, Assert.Single(owner.OwnedWindows), answer);
}
// The answer is given once the dialog's closing has gone through the dispatcher.
private static bool? Answered(Task<bool?> answer)
{
Assert.True(SpinWait.SpinUntil(() =>
{
Controls.Settle();
return answer.IsCompleted;
}, TimeSpan.FromSeconds(5)));
return answer.Result;
}
private static Button[] Buttons(Window dialog) => dialog.GetLogicalDescendants().OfType<Button>().ToArray();
[Theory]
[InlineData(0, true)]
[InlineData(1, false)]
[InlineData(2, null)]
public void A_choice_gives_the_answer_clicked_and_the_way_back_gives_none(int clicked, bool? expected)
{
var (owner, dialog, answer) = Choose();
try
{
Assert.Equal("Niezapisane zmiany", dialog.Title);
Assert.Contains(dialog.GetLogicalDescendants().OfType<TextBlock>(), t => t.Text == "Zapisać zmiany przed startem?");
var buttons = Buttons(dialog);
Assert.Equal(["Zapisz", "Nie zapisuj", App.Loc["Cancel"]], buttons.Select(b => b.Content as string));
Assert.False(answer.IsCompleted);
buttons[clicked].RaiseEvent(Controls.Click());
Assert.Equal(expected, Answered(answer));
Assert.Empty(owner.OwnedWindows);
}
finally
{
owner.Close();
}
}
[Fact]
public void Closing_the_window_of_a_choice_picks_neither_answer()
{
var (owner, dialog, answer) = Choose();
try
{
dialog.Close();
Assert.Null(Answered(answer));
}
finally
{
owner.Close();
}
}
}

View File

@@ -0,0 +1,139 @@
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class MonitorsTests
{
[Fact]
public void A_monitor_is_named_as_the_simulator_names_it()
{
Assert.Equal("Generic_PnP_Monitor:1920,0", Monitors.IdOf("Generic PnP Monitor", 1920, 0));
Assert.Equal("HDMI-1:-1280,-200", Monitors.IdOf("HDMI-1", -1280, -200));
}
[Fact]
public void Xrandr_lists_the_connected_outputs_with_their_place()
{
const string report =
"Screen 0: minimum 320 x 200, current 4480 x 1440, maximum 16384 x 16384\n" +
"eDP-1 connected primary 1920x1080+0+360 (normal left inverted right x axis y axis) 344mm x 194mm\n" +
" 1920x1080 60.00*+\n" +
"HDMI-1 connected 2560x1440+1920+0 (normal left inverted right x axis y axis) 597mm x 336mm\n" +
"DP-1 disconnected (normal left inverted right x axis y axis)\n" +
"DP-2 connected (normal left inverted right x axis y axis)\n";
var monitors = Monitors.Parse(report);
Assert.Equal(2, monitors.Count);
Assert.Equal(new DisplayMonitor("eDP-1:0,360", "eDP-1", 1920, 1080, true, 60), monitors[0]);
Assert.Equal(new DisplayMonitor("HDMI-1:1920,0", "HDMI-1", 2560, 1440, false), monitors[1]);
}
[Fact]
public void Xrandr_gives_each_monitor_the_rate_its_mode_runs_at()
{
const string report =
"DP-1 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm\n" +
" 2560x1440 59.95 + 165.08* 143.97\n" +
" 1920x1080 60.00 50.00\n" +
"HDMI-1 connected 1920x1080+2560+0 (normal left inverted right x axis y axis) 527mm x 296mm\n" +
" 1920x1080 60.00*+ 50.00\n" +
"DP-2 disconnected (normal left inverted right x axis y axis)\n" +
" 1280x1024 75.02*\n";
var monitors = Monitors.Parse(report);
Assert.Equal(new[] { 165, 60 }, monitors.Select(m => m.RefreshRate));
}
[Fact]
public void The_monitor_is_written_only_when_one_is_chosen()
{
var s = new StarterNG.Domain.Settings.SimulatorSettings();
var c = StarterNG.Classes.ConfigFile.Parse("");
new StarterNG.Infrastructure.Settings.SettingsSerializer().Write(s, c);
Assert.False(c.Has("fullscreenmonitor"));
s.FullscreenMonitor = "HDMI-1:1920,0";
new StarterNG.Infrastructure.Settings.SettingsSerializer().Write(s, c);
Assert.Equal("HDMI-1:1920,0", c.GetRaw("fullscreenmonitor"));
}
[Fact]
public void The_size_is_of_the_monitor_named_or_of_the_primary_one()
{
var monitors = new[]
{
new DisplayMonitor("eDP-1:0,360", "eDP-1", 1920, 1080, true),
new DisplayMonitor("HDMI-1:1920,0", "HDMI-1", 2560, 1440, false)
};
Assert.Equal((2560, 1440), Monitors.SizeOf(monitors, "HDMI-1:1920,0"));
Assert.Equal((1920, 1080), Monitors.SizeOf(monitors, ""));
// Not connected: the simulator goes to the primary one.
Assert.Equal((1920, 1080), Monitors.SizeOf(monitors, "DP-3:4480,0"));
Assert.Null(Monitors.SizeOf(Array.Empty<DisplayMonitor>(), "HDMI-1:1920,0"));
}
// ── A name outside ASCII: the simulator compares the file's bytes with GLFW's UTF-8 name ──
private static readonly string UserIni = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
private static StarterNG.Tests.Fakes.TestInstallation WithIni(byte[] ini)
{
var files = new StarterNG.Tests.Fakes.InMemoryFileSystem();
files.WriteAllBytes(UserIni, ini);
var installation = new StarterNG.Tests.Fakes.TestInstallation(files);
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
return installation;
}
private static bool Holds(byte[] file, byte[] part) => file.AsSpan().IndexOf(part) >= 0;
[Theory]
[InlineData("Obecný_monitor_PnP:1920,0")]
[InlineData("Écran_à_Ábc:0,0")]
[InlineData("Монитор_Рабочий:-1920,0")]
[InlineData("显示器:0,0")]
public void A_monitors_name_goes_into_the_file_as_the_utf8_the_simulator_compares(string id)
{
var cp1250 = StarterNG.Infrastructure.Adapters.LegacyText.CodePage1250;
var installation = WithIni(cp1250.GetBytes("lang pl\n// zażółć\nfullscreen yes\n"));
installation.SettingsStore.Settings.FullscreenMonitor = id;
installation.SettingsStore.Save();
byte[] saved = installation.Files.ReadAllBytes(UserIni);
Assert.True(Holds(saved, System.Text.Encoding.UTF8.GetBytes("fullscreenmonitor " + id)));
// The rest of the file stays in the simulator's code page.
Assert.True(Holds(saved, cp1250.GetBytes("// zażółć")));
Assert.Equal(id, WithIni(saved).SettingsStore.Settings.FullscreenMonitor);
}
[Fact]
public void A_monitors_name_written_in_the_code_page_is_read_and_goes_as_utf8_on_a_save()
{
const string id = "Obecný_monitor_PnP:1920,0";
var cp1250 = StarterNG.Infrastructure.Adapters.LegacyText.CodePage1250;
var installation = WithIni(cp1250.GetBytes($"fullscreen yes\nfullscreenmonitor {id}\n"));
Assert.Equal(id, installation.SettingsStore.Settings.FullscreenMonitor);
installation.SettingsStore.Save();
byte[] saved = installation.Files.ReadAllBytes(UserIni);
Assert.True(Holds(saved, System.Text.Encoding.UTF8.GetBytes("fullscreenmonitor " + id)));
Assert.False(Holds(saved, cp1250.GetBytes("fullscreenmonitor " + id)));
}
[Fact]
public void An_ascii_name_of_a_monitor_stays_as_the_file_has_it()
{
var installation = WithIni(System.Text.Encoding.ASCII.GetBytes("fullscreenmonitor HDMI-1:1920,0\n"));
installation.SettingsStore.Save();
Assert.True(Holds(installation.Files.ReadAllBytes(UserIni),
System.Text.Encoding.ASCII.GetBytes("fullscreenmonitor HDMI-1:1920,0")));
}
}

View File

@@ -0,0 +1,132 @@
using StarterNG.Classes;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
// The old starter's magazyn.ini taken in at a start, over the fake disk.
public class OldStarterWarehouseTests
{
private const string PresetsPath = "/home/user/.config/MaSzyna/starter/userpresets.json";
// As the old starter writes it: CRLF, code page 1250, the scenery's path for a name.
private const string Magazyn =
"[TRAINSET0=baltyk/baltyk_km/mpj15120]\r\n" +
"00=node -1 0 EN57AKM-1682RA dynamic pkp\\en57akm_2013_v1 EN57AKM-1682ra akm_2013_ra_male_okna 0 headdriver 255 0 enddynamic\r\n" +
"01=node -1 0 EN57AKM-1682S dynamic pkp\\en57akm_2013_v1 EN57AKM-1682s akm_2013_s 0 nobody 255 0 enddynamic\r\n" +
"02=node -1 0 EN57AKM-1682RB dynamic pkp\\en57akm_2013_v1 EN57AKM-1682rb akm_2013_rb_male_okna 0 nobody 0 0 enddynamic\r\n";
private static (PresetFile Presets, InMemoryFileSystem Files) Rig()
{
var files = new InMemoryFileSystem();
return (new PresetFile(files, TestLog.Over(files), PresetsPath), files);
}
private static List<TrainsetPreset> Consist(string name, string vehicle) =>
OldStarterWarehouse.Read($"[TRAINSET0={name}]\r\n00=node -1 0 {vehicle} dynamic pkp\\x {vehicle} x 0 headdriver 3 0 enddynamic\r\n");
[Fact]
public void A_consist_of_the_old_starter_reads_as_a_trainset_with_its_vehicles()
{
var consist = Assert.Single(OldStarterWarehouse.Read(Magazyn));
Assert.Equal("baltyk/baltyk_km/mpj15120", consist.Name);
Assert.StartsWith("trainset baltyk/baltyk_km/mpj15120 none 0 0\n", consist.Entry);
Assert.EndsWith("endtrainset\n", consist.Entry);
var vehicles = ConsistText.VehiclesFrom(consist.Entry);
Assert.NotNull(vehicles);
Assert.Equal(new[] { "EN57AKM-1682RA", "EN57AKM-1682S", "EN57AKM-1682RB" }, vehicles!.Select(v => v.Name));
}
[Fact]
public void A_consist_new_in_the_old_starter_joins_the_warehouse()
{
var (presets, _) = Rig();
presets.Save("mine", "trainset mine");
int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn));
Assert.Equal(1, added);
Assert.Equal(new[] { "baltyk/baltyk_km/mpj15120", "mine" }, presets.Presets().Select(p => p.Name));
}
[Fact]
public void A_consist_removed_here_does_not_come_back_at_the_next_start()
{
var (presets, _) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.TakeFromOldStarter(found);
presets.Delete("baltyk/baltyk_km/mpj15120");
int added = presets.TakeFromOldStarter(found);
Assert.Equal(0, added);
Assert.Empty(presets.Presets());
}
[Fact]
public void Nothing_new_leaves_the_file_unwritten()
{
var (presets, files) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.TakeFromOldStarter(found);
string before = files.ReadAllText(PresetsPath);
files.WithFile(PresetsPath, before + " ");
presets.TakeFromOldStarter(found);
Assert.Equal(before + " ", files.ReadAllText(PresetsPath));
}
[Fact]
public void A_consist_imported_by_hand_before_is_not_taken_twice()
{
var (presets, _) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.Save(found[0].Name, found[0].Entry);
int added = presets.TakeFromOldStarter(found);
Assert.Equal(0, added);
Assert.Single(presets.Presets());
}
[Fact]
public void A_consist_of_the_same_name_made_here_stays_and_the_old_one_comes_in_beside_it()
{
var (presets, _) = Rig();
presets.Save("osobowy", "trainset osobowy none 0 0\nendtrainset\n");
presets.TakeFromOldStarter(Consist("osobowy", "SM42"));
var all = presets.Presets();
Assert.Equal(new[] { "osobowy", "osobowy" + PresetFile.OldStarterSuffix }, all.Select(p => p.Name));
Assert.Equal("trainset osobowy none 0 0\nendtrainset\n", all[0].Entry);
Assert.Contains("SM42", all[1].Entry);
}
[Fact]
public void A_consist_changed_in_the_old_starter_and_untouched_here_is_replaced()
{
var (presets, _) = Rig();
presets.TakeFromOldStarter(Consist("osobowy", "SM42"));
presets.TakeFromOldStarter(Consist("osobowy", "SU45"));
var only = Assert.Single(presets.Presets());
Assert.Equal("osobowy", only.Name);
Assert.Contains("SU45", only.Entry);
}
[Fact]
public void A_warehouse_file_that_cannot_be_read_is_left_as_it_is()
{
var (presets, files) = Rig();
files.WithFile(PresetsPath, "{ cut");
int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn));
Assert.Equal(0, added);
Assert.Equal("{ cut", files.ReadAllText(PresetsPath));
Assert.False(files.FileExists(PresetsPath + ".unreadable"));
}
}

View File

@@ -0,0 +1,80 @@
using StarterNG.Application;
namespace StarterNG.Tests;
public class OneAtATimeTests
{
private static async Task Until(Func<bool> condition)
{
var giveUp = DateTime.UtcNow.AddSeconds(5);
while (!condition())
{
Assert.True(DateTime.UtcNow < giveUp, "waited too long");
await Task.Delay(10);
}
}
[Fact]
public async Task Asked_once_it_runs_once()
{
int runs = 0;
var once = new OneAtATime(() => { runs++; return Task.CompletedTask; });
await once.RunAsync();
Assert.Equal(1, runs);
Assert.False(once.IsRunning);
}
[Fact]
public async Task Asked_while_running_it_runs_once_more_after_not_alongside()
{
int runs = 0, together = 0, most = 0;
var gates = new Queue<TaskCompletionSource>();
var once = new OneAtATime(async () =>
{
runs++;
most = Math.Max(most, ++together);
var gate = new TaskCompletionSource();
gates.Enqueue(gate);
await gate.Task;
together--;
});
var first = once.RunAsync();
// Three requests during the first run make one more run, not three.
await once.RunAsync();
await once.RunAsync();
await once.RunAsync();
Assert.Equal(1, runs);
gates.Dequeue().SetResult();
await Until(() => Volatile.Read(ref runs) == 2);
await Until(() => gates.Count == 1);
gates.Dequeue().SetResult();
await first;
Assert.Equal(2, runs);
Assert.Equal(1, most);
Assert.False(once.IsRunning);
}
[Fact]
public async Task A_failed_run_does_not_keep_it_busy()
{
bool fail = true;
int runs = 0;
var once = new OneAtATime(() =>
{
runs++;
return fail ? Task.FromException(new IOException("locked")) : Task.CompletedTask;
});
await Assert.ThrowsAsync<IOException>(once.RunAsync);
fail = false;
await once.RunAsync();
Assert.Equal(2, runs);
Assert.False(once.IsRunning);
}
}

View File

@@ -0,0 +1,17 @@
using StarterNG.Domain.Settings;
namespace StarterNG.Tests;
public class RenderersTests
{
[Theory]
[InlineData("default", RendererKind.Modern)]
[InlineData("full", RendererKind.Modern)]
[InlineData("vulkan", RendererKind.Modern)]
[InlineData("legacy", RendererKind.Legacy)]
[InlineData("simple", RendererKind.Legacy)]
[InlineData("simpleshader", RendererKind.Legacy)]
[InlineData("OFF", RendererKind.Legacy)]
public void A_renderer_word_draws_with_the_renderer_master_gives_it(string word, RendererKind kind) =>
Assert.Equal(kind, Renderers.KindOf(word));
}

View File

@@ -53,6 +53,26 @@ public class SceneryFileWatchTests
Assert.Equal("Katowice Główne", change.Fresh!.Name);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void An_sbt_made_or_removed_makes_the_scenery_read_anew(bool there)
{
string sbt = TestInstallation.At("scenery", "kato.sbt");
var files = Folder();
if (there)
files.WithFile(sbt, "EU07SBT2");
var (installation, watch, _) = Rig(files);
if (there)
files.DeleteFile(sbt);
else
files.WithFile(sbt, "EU07SBT2");
var change = Assert.Single(watch.Look(installation.Library.Sceneries));
Assert.Equal(!there, change.Fresh!.HasCompanionTimetable);
}
[Fact]
public void An_include_that_changed_or_came_makes_the_scenery_read_anew()
{

View File

@@ -270,7 +270,7 @@ public class ScenerySyntaxTests
trainset td/rozklad tdo_n1734 0.0 0.1
//$o Skład gotowy na żeberku.
endtrainset
include koniec.scm
include koniec.scm end
""";
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
@@ -331,13 +331,61 @@ public class ScenerySyntaxTests
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
}
[Fact]
public void A_vehicle_without_its_fiz_is_reported_as_one_the_simulator_leaves_out()
{
// As on Bałtyk Cargo: the wagons of a folder gone empty drop out of the consist.
const string scn = """
trainset none tor1 0 0.1
node -1 0 sm42 dynamic PKP\SM42_V1 6D-468 6D -1 headdriver 3 0 enddynamic
node -1 0 eaos-33 dynamic PKP\412W_V1 5340976-0 412wc 0 nobody 3 60 wegiel3 enddynamic
node -1 0 eaos-34 dynamic PKP\412W_V1 5351442-9 412W 0 nobody 0 60 mial1 enddynamic
endtrainset
node -1 0 auto dynamic car car car tor1 0 headdriver 0 0 enddynamic
""";
var asked = new List<(string, string)>();
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, loadsVehicle: (folder, mmd) =>
{
asked.Add((folder, mmd));
return !folder.Equals(@"PKP\412W_V1", StringComparison.Ordinal);
});
Assert.Equal(new[]
{
(SceneryFaultKind.VehicleMissing, "x.scn", 3, (string?)"eaos-33", (string?)@"PKP\412W_V1/412wc.fiz"),
(SceneryFaultKind.VehicleMissing, "x.scn", 4, "eaos-34", @"PKP\412W_V1/412W.fiz")
}, scenery.Faults.Select(Seen));
Assert.Contains(("car", "car"), asked);
// Still listed whole: the starter writes them as they are, for when they are back.
Assert.Equal(3, Assert.Single(scenery.Trainsets).Vehicles.Count);
}
[Fact]
public void A_vehicle_folder_there_but_empty_is_no_vehicle()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/x.scn",
"trainset none tor1 0 0\n" +
"node -1 0 a1 dynamic PKP\\430W_V2 skin 430W 0 nobody 3 0 enddynamic\n" +
"node -1 0 a2 dynamic PKP\\412W_V1 skin 412W 0 nobody 0 0 enddynamic\n" +
"endtrainset\n")
.WithLegacyFile("game/dynamic/pkp/430w_v2/430w.fiz", "")
.WithLegacyFile("game/dynamic/pkp/412w_v1/412w.mmd", "");
var faults = TestScenery.Repository(files).Load("game/scenery/x.scn")!.Faults;
Assert.Equal((SceneryFaultKind.VehicleMissing, "x.scn", 3, "a2", @"PKP\412W_V1/412W.fiz"), Seen(Assert.Single(faults)));
}
[Fact]
public void An_include_named_in_another_case_is_found_as_the_simulator_finds_it()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/x.scn", "FirstInit\ninclude Tomaszewo/Auta.SCM end\n")
.WithLegacyFile("game/scenery/tomaszewo/auta.scm",
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n");
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n")
.WithLegacyFile("game/dynamic/car/car.fiz", "");
var repository = TestScenery.Repository(files);
var scenery = repository.Load("game/scenery/x.scn")!;
@@ -378,4 +426,35 @@ public class ScenerySyntaxTests
Assert.Equal(sbt, scenery.HasCompanionTimetable);
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
}
[Fact]
public void An_include_with_no_end_is_a_fault_even_as_the_last_line()
{
const string scn = "FirstInit\ntrainset a t 0 0\nendtrainset\ninclude dekoracje.scm //Sklady dekoracyjne\n";
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn).Faults.Select(f => (f.Kind, f.Line)).ToList();
Assert.Equal(new[] { (SceneryFaultKind.IncludeNotClosed, 4) }, faults);
}
[Fact]
public void The_consists_of_a_last_include_with_no_end_are_listed_as_the_simulator_loads_them()
{
const string decorations = "trainset d1 t1 0 0\nnode -1 0 a dynamic d s m 0 nobody 3 0 enddynamic\nendtrainset\n";
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm //Sklady dekoracyjne\n",
name => (name, decorations));
Assert.Contains(SceneryIncludes.BeginMarker + "dekoracje.scm", text);
Assert.Contains("trainset d1 t1 0 0", text);
}
[Fact]
public void An_include_with_no_end_before_more_of_the_file_is_left_alone()
{
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm\ntrainset a t 0 0\nendtrainset\n",
name => (name, "trainset d1 t1 0 0\nendtrainset\n"));
Assert.DoesNotContain(SceneryIncludes.BeginMarker, text);
}
}

View File

@@ -158,14 +158,12 @@ public class ScreenReaderNamesTests
var slider = new Slider();
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
row.Description = "Gra zajmie cały ekran.";
row.IdleNote = "Ten symulator nie zna tego ustawienia.";
Assert.Equal("Gra zajmie cały ekran., Ten symulator nie zna tego ustawienia.", AutomationProperties.GetHelpText(check));
Assert.Equal("Gra zajmie cały ekran.", AutomationProperties.GetHelpText(check));
Assert.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
Assert.Null(AutomationProperties.GetName(check));
row.Description = null;
row.IdleNote = null;
Assert.Null(AutomationProperties.GetHelpText(check));
}

View File

@@ -1,154 +0,0 @@
using StarterNG.Domain.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class SettingReachTests
{
private static SimulatorTarget Linux(string renderer = "full", bool server = false) =>
new(WindowsBuild: false, renderer, server);
[Theory]
[InlineData("feedbackmode")]
[InlineData("feedbackport")]
[InlineData("showsystemconsole")]
[InlineData("gfx.angleplatform")]
public void Windows_only_keys_idle_on_a_linux_build(string key)
{
Assert.Equal(IdleReason.WindowsBuildOnly, SettingReach.Why(key, Linux()));
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux() with { WindowsBuild = true }));
}
[Theory]
[InlineData("full", IdleReason.LegacyRendererOnly)]
[InlineData("experimental", IdleReason.LegacyRendererOnly)]
[InlineData("legacy", IdleReason.None)]
[InlineData("simpleshader", IdleReason.None)]
[InlineData("simple", IdleReason.None)]
public void Legacy_renderer_keys_follow_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("smoothtraction", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("usevbo", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.shadows.cab.range", Linux(renderer)));
}
[Fact]
public void Pausing_in_the_background_needs_a_network_server()
{
Assert.Equal(IdleReason.NeedsNetworkServer, SettingReach.Why("inactivepause", Linux()));
Assert.Equal(IdleReason.None, SettingReach.Why("inactivepause", Linux(server: true)));
}
[Fact]
public void The_starters_own_keys_never_idle()
{
Assert.Equal(IdleReason.None, SettingReach.Why("starter.autoclose", Linux()));
}
[Theory]
[InlineData("width, height")]
[InlineData("fullscreen")]
public void The_monitors_own_mode_overrides_size_and_full_screen(string key)
{
Assert.Equal(IdleReason.MonitorModeInstead,
SettingReach.Why(key, Linux() with { FullscreenWindowed = true }));
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux()));
}
[Fact]
public void An_ordinary_key_works_everywhere()
{
Assert.Equal(IdleReason.None, SettingReach.Why("fieldofview", Linux()));
}
[Theory]
[InlineData("full", IdleReason.None)]
[InlineData("legacy", IdleReason.ModernRendererOnly)]
[InlineData("experimental", IdleReason.ModernRendererOnly)]
public void Effects_of_the_full_renderer_follow_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("gfx.postfx.motionblur.enabled", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("sleeperdistance", Linux(renderer)));
}
[Theory]
[InlineData("vulkan", IdleReason.None)]
[InlineData("vulkan14", IdleReason.None)]
[InlineData("full", IdleReason.VulkanOnly)]
[InlineData("gl46", IdleReason.VulkanOnly)]
[InlineData("legacy", IdleReason.VulkanOnly)]
public void What_only_vulkan_reads_follows_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("gfx.dlss.preset", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.framegeneration", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.raytracing", Linux(renderer)));
// Both renderers of the new simulator read this one.
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.postfx.ao", Linux(renderer)));
}
[Theory]
[InlineData("vulkan")]
[InlineData("vulkan14")]
[InlineData("opengl")]
[InlineData("gl46")]
public void The_new_simulators_renderers_read_what_the_full_one_does(string renderer)
{
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
Assert.Equal(IdleReason.None, SettingReach.Why("multisampling", Linux(renderer)));
}
[Theory]
[InlineData("full", IdleReason.None)]
[InlineData("legacy", IdleReason.None)]
[InlineData("experimental", IdleReason.OpenGlRenderersOnly)]
public void The_experimental_renderer_passes_over_what_only_opengl_reads(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("multisampling", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("anisotropicfiltering", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.smoke", Linux(renderer)));
// ...but reads the rest of the reflections and shadows.
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.reflections.fidelity", Linux(renderer)));
Assert.Equal(IdleReason.None, SettingReach.Why("shadowtune", Linux(renderer)));
}
[Theory]
[InlineData(null, 0, false)]
[InlineData(0.0, 0, false)]
[InlineData(60.0, 0, true)]
[InlineData(null, 50, true)] // fpsaverage, the older regulator
public void The_draw_range_factor_needs_a_regulator(double? targetFps, double fpsAverage, bool regulated)
{
var target = Linux() with { TargetFps = targetFps, FpsAverage = fpsAverage };
Assert.Equal(regulated ? IdleReason.None : IdleReason.NeedsFrameRateTarget,
SettingReach.Why("gfx.drawrange.factor.max", target));
}
// ── The rest of the target ───────────────────────────────────────────────
[Fact]
public void A_windows_build_is_told_from_its_header()
{
var files = new InMemoryFileSystem()
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
.WithFile(TestInstallation.At("eu07.exe"), "MZ binary");
var installation = new TestInstallation(files);
Assert.False(installation.Executables.IsWindowsBuild("eu07"));
Assert.True(installation.Executables.IsWindowsBuild("eu07.exe"));
}
[Fact]
public void A_network_server_in_the_ini_is_noticed()
{
string ini = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(ini, "network.server tcp 0.0.0.0:7424\n"));
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
Assert.True(installation.SettingsStore.Settings.NetworkServer);
}
}

View File

@@ -0,0 +1,39 @@
using StarterNG.Application;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>The settings page on a start with no eu07.ini of the player's own yet.</summary>
[Collection(AvaloniaControls.Name)]
public class SettingsFirstStartTests
{
[Fact]
public void A_first_start_has_nothing_to_save_before_the_simulator_starts()
{
var files = new InMemoryFileSystem();
files.WriteAllText(TestInstallation.At("eu07.ini"), "width 1920\nheight 1080\nendconfig\n");
var installation = new TestInstallation(files);
installation.Environment.AsWindows();
var services = AppServices.Initialize(installation.Paths, installation.Files, installation.Clock,
installation.Environment);
services.SettingsStore.Load();
services.SettingsStore.StartAtHighWithoutOwnSettings();
HeadlessDrawing.Ensure();
// The page reads the graphics cards away from the window and comes back to it, as in the application.
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(new Avalonia.Threading.AvaloniaSynchronizationContext());
Avalonia.Controls.Window? window = null;
try
{
var page = new StarterNG.Views.Settings();
window = Controls.Show(page, 1600, 1000, themed: true);
Assert.False(page.HasUnsavedChanges);
}
finally
{
window?.Close();
SynchronizationContext.SetSynchronizationContext(context);
}
}
}

View File

@@ -492,10 +492,8 @@ public class SettingsStoreTests
[InlineData("mousescale 1.5 0.5", false, true, "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 0.5", true, false, "mousescale -1.5 0.5")]
[InlineData("mousescale -1.5 -0.5", false, false, "mousescale 1.5 0.5")]
[InlineData("mousescale 2.5 0.123456", false, true, "mousescale 2.5 -0.123456")]
// Further than the slider goes.
[InlineData("mousescale 12 0.5", true, false, "mousescale -12 0.5")]
public void A_mouse_scale_keeps_its_numbers_when_an_axis_is_inverted(
[InlineData("mousescale 3.2 0.5", true, true, "mousescale -3.2 -0.5")]
public void An_inverted_axis_is_the_sign_of_its_number(
string line, bool invertX, bool invertY, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
@@ -508,10 +506,69 @@ public class SettingsStoreTests
Assert.Equal(written, LineFor(installation, "mousescale"));
}
[Fact]
public void A_mouse_scale_nobody_changed_stays_as_the_file_has_it()
[Theory]
[InlineData("mousescale 1.0 0.5")]
[InlineData("mousescale 1 0.5")]
[InlineData("mousescale 1.5 0.5")]
[InlineData("mousescale -2.3 0.5")]
[InlineData("mousescale 3.2 -0.5")]
public void A_mouse_scale_of_the_old_starter_stays_as_the_file_has_it(string line)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 1.5 0.5\n"));
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Equal(line, LineFor(installation, "mousescale"));
}
[Theory]
// The old starter's four speeds (src/uSettings.pas): low, standard, high, very high.
[InlineData(1, "mousescale 1.0 0.5")]
[InlineData(2, "mousescale 1.5 0.5")]
[InlineData(3, "mousescale 2.3 0.5")]
[InlineData(4, "mousescale 3.2 0.5")]
public void The_sensitivity_is_written_as_the_old_starter_wrote_it(int level, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 12 0.5\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.CursorSensitivity = level;
installation.SettingsStore.Save();
Assert.Equal(written, LineFor(installation, "mousescale"));
}
[Theory]
// Low below 1.3, high above 1.9, very high above 2.7, standard between - whatever the sign.
[InlineData("0", 1)]
[InlineData("0.2", 1)]
[InlineData("1.29", 1)]
[InlineData("1.3", 2)]
[InlineData("1.5", 2)]
[InlineData("1.9", 2)]
[InlineData("2", 3)]
[InlineData("-2.3", 3)]
[InlineData("2.7", 3)]
[InlineData("3", 4)]
[InlineData("-3.2", 4)]
[InlineData("12", 4)]
// Not a number the old starter could read: its list stayed at standard.
[InlineData("Infinity", 2)]
[InlineData("fast", 2)]
public void The_sensitivity_is_read_as_the_old_starter_read_it(string x, int level)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"mousescale {x} 0.5\n"));
installation.SettingsStore.Load();
Assert.Equal(level, installation.SettingsStore.Settings.CursorSensitivity);
}
[Fact]
public void Without_a_mouse_scale_the_old_starters_standard_is_written()
{
var installation = WithHome();
installation.SettingsStore.Load();
installation.SettingsStore.Save();
@@ -519,28 +576,35 @@ public class SettingsStoreTests
Assert.Equal("mousescale 1.5 0.5", LineFor(installation, "mousescale"));
}
[Fact]
public void Moving_the_sensitivity_replaces_the_scale_it_stood_for()
[Theory]
// The second number is always 0.5, as the old starter wrote it; its sign is the inversion.
[InlineData("mousescale 1.5 0.2", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 0.23", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 -0.23", "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 -2", "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 0", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 -0", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 NaN", "mousescale 1.5 0.5")]
// A decimal comma: the simulator reads "0,2" as 0.
[InlineData("mousescale 1.5 0,2", "mousescale 1.5 0.5")]
// The first is one of that starter's four speeds, the one of the level the file's number has.
[InlineData("mousescale 0.5 0.5", "mousescale 1.0 0.5")]
[InlineData("mousescale 0 0.5", "mousescale 1.0 0.5")]
[InlineData("mousescale 2 0.5", "mousescale 2.3 0.5")]
[InlineData("mousescale -3 0.5", "mousescale -3.2 0.5")]
[InlineData("mousescale 12 0.2", "mousescale 3.2 0.5")]
[InlineData("mousescale Infinity -0.5", "mousescale 1.5 -0.5")]
// One number: the simulator takes the next word of the file ("mousecontrol") for Y, and reads it as 0.
[InlineData("mousescale 1.5", "mousescale 1.5 0.5")]
[InlineData("mousescale 0.5\t// (3.2 0.5) komentarz", "mousescale 1.0 0.5\t// (3.2 0.5) komentarz")]
public void A_mouse_scale_the_old_starter_would_not_write_goes_on_a_save(string line, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 1.5 0.5\n"));
installation.SettingsStore.Load();
Assert.Equal(2, installation.SettingsStore.Settings.CursorSensitivity);
installation.SettingsStore.Settings.CursorSensitivity = 3;
installation.SettingsStore.Save();
Assert.Equal("mousescale 3 0.5", LineFor(installation, "mousescale"));
}
[Fact]
public void The_default_mouse_scale_is_written_as_before()
{
var installation = WithHome();
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Equal("mousescale 2 0.2", LineFor(installation, "mousescale"));
Assert.Equal(written, LineFor(installation, "mousescale"));
}
// ── A file that could not be read ────────────────────────────────────────
@@ -885,12 +949,8 @@ public class SettingsStoreTests
[InlineData("default")]
[InlineData("simpleshader")]
[InlineData("off")]
[InlineData("opengl")]
[InlineData("gl46")]
[InlineData("vulkan14")]
[InlineData("legacy")]
[InlineData("simple")]
[InlineData("experimental")]
public void A_renderer_word_the_simulator_reads_as_another_stays_until_changed(string word)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
@@ -901,16 +961,33 @@ public class SettingsStoreTests
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
}
// Words master does not know start the full renderer with a line in its log, and the
// experimental renderer is not in a player's build: a save puts "default" in their place.
[Theory]
[InlineData(0, "full")]
[InlineData("full")]
[InlineData("opengl")]
[InlineData("gl46")]
[InlineData("vulkan14")]
[InlineData("experimental")]
[InlineData("null")]
public void A_renderer_word_master_does_not_run_is_saved_as_default(string word)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Contains("gfxrenderer default\n", SavedLines(installation));
}
[Theory]
[InlineData(0, "default")]
[InlineData(1, "legacy")]
[InlineData(2, "simple")]
[InlineData(3, "experimental")]
[InlineData(4, "vulkan")]
public void A_chosen_renderer_is_saved_as_the_simulator_reads_it(int engine, string saved)
{
// application.cpp knows full (or default), experimental and simple; every
// other word - "simpleshader" and "off" from older starters - is legacy.
// application.cpp on master knows default, legacy and simple; "simpleshader" and "off"
// from older starters are legacy, and any other word gets the full renderer.
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine;
@@ -926,8 +1003,10 @@ public class SettingsStoreTests
[InlineData("full", 0)]
[InlineData("gl46", 0)]
[InlineData("opengl", 0)]
[InlineData("vulkan", 4)]
[InlineData("VULKAN14", 4)]
[InlineData("vulkan", 0)]
[InlineData("VULKAN14", 0)]
[InlineData("whatever", 0)]
[InlineData("experimental", 0)]
[InlineData("simpleshader", 1)]
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine)
{
@@ -935,7 +1014,7 @@ public class SettingsStoreTests
}
[Fact]
public void The_buffer_is_written_for_old_and_new_simulators()
public void The_buffer_is_written_as_the_framebuffer_master_reads()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1000\nheight 500\n"));
installation.SettingsStore.Load();
@@ -944,19 +1023,20 @@ public class SettingsStoreTests
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.Contains("gfx.buffer.percent 50\n", saved);
Assert.DoesNotContain("gfx.buffer.percent", saved);
Assert.Contains("gfx.framebuffer.width 500\n", saved);
Assert.Contains("gfx.framebuffer.height 250\n", saved);
}
[Theory]
[InlineData("gfx.buffer.percent 0.5\n", 50)]
[InlineData("gfx.buffer.percent 75\n", 75)]
[InlineData("gfx.buffer.percent 10\n", 25)]
[InlineData("gfx.buffer.percent 300\n", 200)]
[InlineData("width 1000\ngfx.framebuffer.width 500\n", 50)]
[InlineData("width 1000\ngfx.framebuffer.width 100\n", 25)]
[InlineData("width 1000\ngfx.framebuffer.width 3000\n", 100)]
[InlineData("gfx.framebuffer.width 500\n", 100)]
[InlineData("starter.bufferscale 60\n", 60)]
[InlineData("starter.bufferscale 60\ngfx.buffer.percent 80\n", 80)]
public void The_buffer_is_read_from_the_key_the_new_simulator_goes_by(string ini, int percent)
[InlineData("starter.bufferscale 60\nwidth 1000\ngfx.framebuffer.width 800\n", 60)]
[InlineData("gfx.buffer.percent 0.5\n", 100)]
public void The_buffer_is_read_from_the_starters_key_or_the_framebuffer(string ini, int percent)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
@@ -965,36 +1045,6 @@ public class SettingsStoreTests
Assert.Equal(percent, installation.SettingsStore.Settings.BufferScalePercent);
}
[Fact]
public void The_two_anti_aliasing_keys_untouched_keep_their_order()
{
// Moving them would change which of the two the simulator goes by.
const string ini = "gfx.antialiasing taa\nwidth 800\nmultisampling 2\n";
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.True(saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal) < saved.IndexOf("multisampling 2", StringComparison.Ordinal), saved);
}
[Fact]
public void A_chosen_anti_aliasing_is_saved_below_multisampling_for_the_later_line_to_count()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfx.antialiasing msaax4\nwidth 800\nmultisampling 2\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.AntiAliasing = AntiAliasingMode.Taa;
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.True(saved.IndexOf("multisampling ", StringComparison.Ordinal) < saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal), saved);
var again = WithHome(installation.Files);
again.SettingsStore.Load();
Assert.Equal(AntiAliasingMode.Taa, again.SettingsStore.Settings.AntiAliasing);
}
[Fact]
public void A_field_of_view_down_to_ten_degrees_survives_a_save()
{
@@ -1196,6 +1246,28 @@ public class SettingsStoreTests
Assert.Equal(60, store.Settings.FieldOfView);
}
// The move to the standard mode puts back the keys of the rows it hides: the row of the
// render scale has the frame buffer's two, and the percent it is worked out from is the starter's own.
[Theory]
[InlineData("width 1920\nheight 1080\nstarter.bufferscale 50\ngfx.framebuffer.width 960\ngfx.framebuffer.height 540\n")]
[InlineData("width 1920\nheight 1080\ngfx.framebuffer.width 960\ngfx.framebuffer.height 540\n")]
public void The_frame_buffer_put_back_takes_the_render_scale_with_it(string ini)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
var store = installation.SettingsStore;
store.Load();
Assert.Equal(50, store.Settings.BufferScalePercent);
var reset = store.WithDefaults(store.Settings, new[] { "gfx.framebuffer.width", "gfx.framebuffer.height" });
Assert.Equal(100, reset.BufferScalePercent);
Assert.Equal(1920, reset.Width);
var written = store.Render(reset);
Assert.Equal("100", written["starter.bufferscale"]);
Assert.Equal("1920", written["gfx.framebuffer.width"]);
Assert.Equal("1080", written["gfx.framebuffer.height"]);
}
// ── What the screen shows otherwise ──────────────────────────────────────
[Fact]
@@ -1257,6 +1329,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 +1407,240 @@ 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);
}
// An older file says "standard no": taken in, it would move the player again on the next
// start, and its "advanced yes" would open the advanced mode past the warning.
private const string OlderModeLines = "starter.settings.standard no\nstarter.settings.advanced yes\nfieldofview 50\n";
[Fact]
public void An_imported_ini_leaves_the_mode_as_this_installation_has_it()
{
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
var files = new InMemoryFileSystem()
.WithFile(UserIni, "starter.settings.standard yes\nstarter.settings.advanced no\n")
.WithFile(backup, OlderModeLines);
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.ImportFrom(backup));
store.Save();
Assert.Equal(50, store.Settings.FieldOfView);
Assert.True(store.Settings.MovedToStandard);
Assert.False(store.Settings.AdvancedSettings);
string written = files.ReadAllText(UserIni, System.Text.Encoding.UTF8);
Assert.Contains("starter.settings.standard yes", written);
Assert.Contains("starter.settings.advanced no", written);
}
[Fact]
public void A_profile_leaves_the_mode_as_this_installation_has_it()
{
var files = new InMemoryFileSystem()
.WithFile(UserIni, "starter.settings.standard yes\nstarter.settings.advanced no\n")
.WithFile(Profile, OlderModeLines);
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.TryLoadProfile(Profile));
store.Save();
Assert.Equal(50, store.Settings.FieldOfView);
Assert.True(store.Settings.MovedToStandard);
Assert.False(store.Settings.AdvancedSettings);
string written = files.ReadAllText(UserIni, System.Text.Encoding.UTF8);
Assert.Contains("starter.settings.standard yes", written);
Assert.Contains("starter.settings.advanced no", written);
}
[Theory]
[InlineData("starter.gpu")]
[InlineData("gfx.usegles")]
public void The_move_to_the_standard_mode_keeps_what_lets_a_machine_run_the_simulator(string key) =>
Assert.Contains(key, StarterNG.Application.SettingsStore.KeptOnMoveToStandard);
[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,54 @@
using StarterNG.Domain.Settings;
using StarterNG.Views;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class SliderStepsTests
{
[Fact]
public void The_old_starters_steps_are_offered_and_a_value_outside_them_stays()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.ReflectionUpdates) { Value = 1 / 300.0 };
// The simulator's own once in five minutes, shown before the old starter's 1 to 60.
Assert.Equal(1 / 300.0, steps.Value);
Assert.Equal(SliderRanges.ReflectionUpdates.Length, slider.Maximum);
slider.Value = slider.Maximum;
Assert.Equal(60, steps.Value);
}
[Fact]
public void A_frame_limit_above_the_list_stays_as_the_file_has_it()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.FrameRateLimits) { Value = 300 };
Assert.Equal(300, steps.Value);
Assert.Equal(SliderRanges.FrameRateLimits.Length, slider.Maximum);
}
[Fact]
public void Clamping_puts_a_value_past_either_end_at_that_end()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.FrameRateLimits) { Clamps = true, Value = 300 };
Assert.Equal(240, steps.Value);
Assert.Equal(SliderRanges.FrameRateLimits.Length - 1, slider.Maximum);
}
[Fact]
public void Clamping_leaves_a_value_between_two_steps_where_it_is()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.CabShadowRanges) { Clamps = true, Value = 15 };
Assert.Equal(15, steps.Value);
steps.Value = -5;
Assert.Equal(0, steps.Value);
}
}

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

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>

View File

@@ -1,5 +1,6 @@
using StarterNG.Classes;
using StarterNG.Domain;
using StarterNG.Domain.Settings;
using StarterNG.Views;
namespace StarterNG.Tests;
@@ -58,6 +59,63 @@ public class TrainsetDisplayTests
Assert.False(TrainsetDisplay.ListedIn(picked, showAi: false, drivableOnly: true, current: picked));
}
private static SimulatorSettings Mode(bool advanced) =>
new() { AdvancedSettings = advanced, ShowAiVehicles = true, DrivableOnly = false };
[Fact]
public void The_standard_mode_lists_every_consist_but_starts_only_in_one_a_player_drives()
{
var standard = Mode(advanced: false);
var decor = new Trainset("trainset a tor 0 0 //$decor\nnode -1 0 v1 dynamic d s m 0 headdriver 3 0 enddynamic\nendtrainset");
Assert.True(decor.Decor);
foreach (var consist in new[] { Consist(), Consist(description: "-ai"), Consist(driver: "nobody"), decor })
Assert.True(TrainsetDisplay.ListedIn(consist, standard, current: null));
Assert.True(TrainsetDisplay.StartableIn(Consist(), standard));
Assert.True(TrainsetDisplay.StartableIn(Consist(driver: "nobody"), standard));
Assert.False(TrainsetDisplay.StartableIn(Consist(description: "-ai"), standard));
Assert.False(TrainsetDisplay.StartableIn(decor, standard));
Assert.True(TrainsetDisplay.StartableIn(decor, Mode(advanced: true)));
}
[Fact]
public void The_filters_work_in_the_advanced_mode()
{
var settings = Mode(advanced: true);
settings.ShowAiVehicles = false;
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), settings, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(), settings, current: null));
settings.DrivableOnly = true;
Assert.False(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), settings, current: null));
}
[Fact]
public void The_standard_mode_has_no_filters_and_leaves_out_empty_consists()
{
var standard = new SimulatorSettings { AdvancedSettings = false, ShowAiVehicles = false, DrivableOnly = true };
var empty = new Trainset("trainset a tor 0 0\nendtrainset");
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), standard, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), standard, current: null));
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: null));
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: empty));
}
[Fact]
public void The_advanced_mode_lists_by_its_own_filters()
{
var advanced = Mode(advanced: true);
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), advanced, current: null));
advanced.ShowAiVehicles = false;
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
}
[Theory]
[InlineData(eDriverType.Headdriver, 0)]
[InlineData(eDriverType.Reardriver, 1)]

View File

@@ -6,6 +6,8 @@ namespace StarterNG.Tests;
// PresetStore keeps the disk of the first test that reaches it, a fake one as every
// composition root in the tests is built on fakes. So each test has a name to itself.
// Puts in services of its own: not while the controls read theirs.
[Collection(AvaloniaControls.Name)]
public class WarehouseEditTests
{
private const string Text =
@@ -96,6 +98,23 @@ public class WarehouseEditTests
Assert.Null(Stored("edit-changed"));
}
[Fact]
public void A_write_tells_the_list_the_name_and_the_entry_and_no_write_tells_nothing()
{
var told = new List<(string Name, string Entry)>();
_edit.Saved += (name, entry) => told.Add((name, entry));
var trainset = _edit.Open(Preset("edit-told"));
_edit.Save();
Assert.Empty(told);
trainset.Vehicles.Add(trainset.Vehicles[0].Clone());
_edit.Save();
Assert.Equal([("edit-told", ConsistText.Serialize(trainset))], told);
PresetStore.Delete("edit-told");
}
[Fact]
public void Nothing_is_written_with_nothing_open()
{

View File

@@ -160,6 +160,11 @@ public partial class App : Avalonia.Application
});
});
// Ahead of the sceneries, so the list knows which still have their .sbt.
try { AppServices.Current.BinaryTerrain.CleanUpOnce(); }
catch (Exception ex) { Diagnostics.Log("sbt cleanup", ex); }
// Before any window lists the warehouse; it catches what it meets itself.
PresetStore.TakeFromOldStarter();
AppServices.Current.Library.Load(progress);
}).ContinueWith(load =>
{

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Settings;
@@ -43,6 +44,7 @@ public sealed class AppServices
paths.FromRoot("starter"),
paths.FromRoot("lang")));
Sceneries = new SceneryRepository(files, paths, log, new SceneryParser(clock, random));
BinaryTerrain = new BinaryTerrainFiles(files, paths, log, settingsPaths.SbtCleanupPath());
SceneryImages = new SceneryImageLocator(files);
MiniTextures = new MiniTextureIndex(files, paths);
@@ -63,13 +65,15 @@ public sealed class AppServices
SceneryFiles = new SceneryFileWatch(files, Sceneries, Library, State);
Executables = new ExecutableLocator(files, paths, environment, log);
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(dlssPlatform: !environment.IsMacOS), Executables);
// Read when a borderless screen with a smaller buffer is first written, and once.
var monitors = new Lazy<IReadOnlyList<DisplayMonitor>>(() => Monitors.List(environment));
SettingsStore = new SettingsStore(files, clock, log, settingsPaths,
new SettingsSerializer(id => Monitors.SizeOf(monitors.Value, id)), Executables);
MissingVehicleLog = new MissingVehicleLog(SettingsStore.Settings, missingAssets, Library, log);
Favorites = new FavoriteSceneries(files, log, settingsPaths.FavoritesPath());
Tapes = new HaslerTapes(files, paths, log, clock, Timetables, () => State.SimulatorRunning);
Gpus = new LinuxGpus(files, environment);
GraphicsCards = new GraphicsCards(files, environment, Gpus);
Displays = new Displays(files, environment);
StartSimulation = new StartSimulation(State, SettingsStore, Library.Vehicles, Executables,
files, paths, Processes, random, log, Gpus, environment,
new WineConfigLink(files, environment, settingsPaths, log), Tapes);
@@ -111,6 +115,8 @@ public sealed class AppServices
public SceneryFileWatch SceneryFiles { get; }
public BinaryTerrainFiles BinaryTerrain { get; }
public SceneryImageLocator SceneryImages { get; }
public IMiniTextureIndex MiniTextures { get; }
@@ -141,8 +147,6 @@ public sealed class AppServices
public GraphicsCards GraphicsCards { get; }
public Displays Displays { get; }
public SettingsPaths SettingsPaths { get; }
public MissingVehicleLog MissingVehicleLog { 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

@@ -0,0 +1,45 @@
using System;
using System.Threading.Tasks;
namespace StarterNG.Application;
/// <summary>
/// Runs a piece of work one at a time. Asked again while it runs, it does not start a
/// second one alongside, nor forget the request: it runs once more when the first ends,
/// however many times it was asked meanwhile. For the UI thread, which calls it alone.
/// </summary>
public sealed class OneAtATime
{
private readonly Func<Task> _work;
private bool _running;
private bool _again;
public OneAtATime(Func<Task> work) => _work = work;
public bool IsRunning => _running;
public async Task RunAsync()
{
if (_running)
{
_again = true;
return;
}
_running = true;
try
{
do
{
_again = false;
await _work();
}
while (_again);
}
finally
{
_running = false;
_again = false;
}
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
@@ -75,6 +76,9 @@ public sealed class SettingsStore
public string SavePath => _savePath;
/// <summary>The last save found eu07.ini changed by something else and kept those changes: what is held was read again.</summary>
public bool LastSaveMerged { get; private set; }
public void RegisterCapture(ISettingsCapture capture) => _capture = capture;
public void Load()
@@ -92,9 +96,30 @@ public sealed class SettingsStore
return;
GraphicsPreset.High.ApplyTo(Settings);
// Nothing of an older starter to bring over: the settings start in the standard mode.
Settings.MovedToStandard = true;
Save();
}
/// <summary>
/// A copy of eu07.ini beside it, the file name and <paramref name="suffix"/>, before
/// something changes many keys at once; one already there is left as it is.
/// </summary>
public void KeepCopy(string suffix)
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
string copy = path + suffix;
try
{
if (_files.FileExists(path) && !_files.FileExists(copy))
_files.CopyFile(path, copy, overwrite: false);
}
catch (Exception e)
{
_log.Log($"{copy} could not be made: {e.Message}");
}
}
public void LoadFrom(string path)
{
try
@@ -113,9 +138,37 @@ 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();
}
/// <summary>
/// What lets some machines run the simulator at all: the card it is put on (offloading
/// to the discrete one fails with some drivers) and OpenGL ES where desktop OpenGL does
/// not work. The move to the standard mode, done without asking, leaves them as they are.
/// </summary>
public static readonly IReadOnlySet<string> KeptOnMoveToStandard =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "starter.gpu", "gfx.usegles" };
/// <summary>
/// The mode is this installation's, like its simulator and its card: another file, a
/// backup or a profile of an older starter, says nothing of it. Without this, its
/// "starter.settings.standard no" would move the player again on the next start, and its
/// "starter.settings.advanced yes" would open the advanced mode past the warning.
/// The returned action puts the mode back as it was when this was called.
/// </summary>
private Action KeepMode()
{
bool advanced = Settings.AdvancedSettings, moved = Settings.MovedToStandard;
return () =>
{
Settings.AdvancedSettings = advanced;
Settings.MovedToStandard = moved;
};
}
/// <summary>
/// Reads a profile into the settings; true when it read cleanly. A read that failed
/// would leave defaults to be saved over the real settings, so those are read again.
@@ -124,9 +177,13 @@ public sealed class SettingsStore
{
if (_files.FileExists(path))
{
var mode = KeepMode();
LoadFrom(path);
if (!LoadFailed)
{
mode();
return true;
}
}
if (LoadFailed)
@@ -157,8 +214,30 @@ public sealed class SettingsStore
return;
}
// Edited by other hands since it was read or written here: their file is what the changes
// go onto, so a key the player left alone keeps what was put there meanwhile.
bool merged = false;
if (string.Equals(path, _savePath, StringComparison.Ordinal) && IsConfigNewerOnDisk())
{
try
{
_config = ConfigFile.Parse(_files.ReadAllText(path, _encoding));
merged = true;
}
catch (Exception ex)
{
_log.Log($"re-reading {path} before saving", ex);
}
}
ApplyChanges(_config, Changes(Settings));
if (merged)
{
// What is held follows the file: the player's changes and the others' together.
_serializer.Read(Settings, _config);
}
_synced = Render(Settings);
LastSaveMerged = merged;
try
{
@@ -185,16 +264,8 @@ public sealed class SettingsStore
else
config.Set(change.Key, change.After);
}
// Each sets the mode as the simulator reads it, so the new one has to come later to count.
// Untouched, the two keep their order: moving them would change which one decides.
if (changes.Any(change => change.Key is "gfx.antialiasing" or "multisampling"))
config.MoveAfter("gfx.antialiasing", "multisampling");
}
/// <summary>Whether the simulator can have DLSS on this platform at all.</summary>
public bool DlssPlatform => _serializer.DlssPlatform;
/// <summary>
/// Takes the settings of another eu07.ini (a backup, a file from another machine)
/// into the current ones, keeping what belongs to this installation: the chosen
@@ -220,9 +291,7 @@ public sealed class SettingsStore
var gpu = s.Gpu;
string lastScenery = s.LastScenery;
bool maximized = s.WindowMaximized;
// Only read for the dependencies and never written, so they stay as this user's file has them.
bool cabLampLight = s.CabLampLight;
bool depthPrepassScene = s.DepthPrepassScene;
var mode = KeepMode();
_serializer.Read(s, imported);
@@ -231,8 +300,9 @@ public sealed class SettingsStore
s.Gpu = gpu;
s.LastScenery = lastScenery;
s.WindowMaximized = maximized;
s.CabLampLight = cabLampLight;
s.DepthPrepassScene = depthPrepassScene;
mode();
// an ini of before the tapes of the trains goes the same way as a profile
SettingsSerializer.MoveToTrainTapes(s);
return true;
}
@@ -240,7 +310,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 +320,7 @@ public sealed class SettingsStore
}
var copy = ConfigFile.Parse(_config.ToText());
ApplyChanges(copy, Changes(Settings));
ApplyChanges(copy, Changes(settings ?? Settings));
try
{
@@ -278,6 +349,90 @@ public sealed class SettingsStore
return keys;
}
/// <summary>
/// The keys the starter knows that the file gives a value it cannot read, with that value:
/// the setting shows its default, while the file keeps its own until the setting is changed.
/// A value read another way (tak, 1.0, a clamped number) is no unknown one.
/// </summary>
public IReadOnlyDictionary<string, string> UnreadableValues()
{
var unreadable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var defaults = Render(WithFile(new ConfigFile()));
var read = Render(WithFile(_config));
var overCap = SettingsSerializer.OverCapKeys(_config);
foreach (var (key, fallback) in defaults)
{
// Read, only brought down to the cap.
if (NotReadAlone.Contains(key) || overCap.Contains(key))
continue;
if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw)
continue;
if (read.TryGetValue(key, out string? shown) && shown == fallback && !SameValue(raw, shown))
unreadable[key] = raw;
}
foreach (var key in SimulatorKeys.All)
{
if (_config.IsPastEnd(key.Key) || _config.GetRaw(key.Key) is not { Length: > 0 } raw)
continue;
string first = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)[0];
bool readable = key.Kind switch
{
SimulatorKeyKind.Toggle => Bool(first) is not null,
SimulatorKeyKind.Number => double.TryParse(first, NumberStyles.Float, CultureInfo.InvariantCulture, out _),
_ => true
};
if (!readable)
unreadable[key.Key] = raw;
}
return unreadable;
}
// Written from other keys, or rewritten on purpose whatever they say: what they hold is no setting of their own.
private static readonly HashSet<string> NotReadAlone = new(StringComparer.OrdinalIgnoreCase)
{
"mousescale", "gfxrenderer", "gfx.shadowmap.enabled", "gfx.framebuffer.width", "gfx.framebuffer.height"
};
private SimulatorSettings WithFile(ConfigFile config)
{
var s = new SimulatorSettings();
_serializer.Read(s, config);
return s;
}
// Two numbers written apart that the file and the screen mean alike: 45 and 45.0, 0.1 and 1e-1.
private static bool SameNumber(double x, double y) =>
Math.Abs(x - y) <= 1e-9 * Math.Max(1, Math.Max(Math.Abs(x), Math.Abs(y)));
// The same value in other words: yes and tak, 45 and 45.0.
private static bool SameValue(string raw, string shown)
{
var a = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var b = shown.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (string.Equals(a[i], b[i], StringComparison.OrdinalIgnoreCase))
continue;
if (double.TryParse(a[i], NumberStyles.Float, CultureInfo.InvariantCulture, out double x) &&
double.TryParse(b[i], NumberStyles.Float, CultureInfo.InvariantCulture, out double y) && SameNumber(x, y))
continue;
if (Bool(a[i]) is { } p && p == Bool(b[i]))
continue;
return false;
}
return true;
}
private static bool? Bool(string word) => word.ToLowerInvariant() switch
{
"yes" or "true" or "1" or "tak" => true,
"no" or "false" or "0" or "nie" => false,
_ => null
};
/// <summary>
/// What saving <paramref name="settings"/> would change in the file: the keys
/// changed since it was read, those it lacks, and the ones no simulator reads.
@@ -290,6 +445,8 @@ public sealed class SettingsStore
var shown = _capture?.ShownUnlikeSettings ?? new Dictionary<string, ShownValue>();
var changes = new List<IniChange>();
var listed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// Above the starter's caps the file is brought down, though nothing on screen moved.
var overCap = SettingsSerializer.OverCapKeys(_config);
foreach (string key in SettingsSerializer.ObsoleteKeys)
Add(key, null);
@@ -316,12 +473,29 @@ public sealed class SettingsStore
return Uart.FeaturesStand(_config.GetRaw(key), value);
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
return _config.GetRaw(key) == value;
if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) &&
!SimulatorSettings.KeptRendererWord(_config.GetRaw(key)))
return false;
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
return false;
if (overCap.Contains(key))
return false;
// The simulator goes by these to the letter: a buffer of a window's size stretched
// over the monitor, a monitor's name it does not find. The file's own is no choice to keep.
if (AsWritten(key) && _config.GetRaw(key) != value)
return false;
string? synced = _synced.GetValueOrDefault(key);
if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced)
return true;
return _config.Has(key) && synced == value;
}
bool AsWritten(string key) =>
string.Equals(key, "fullscreenmonitor", StringComparison.OrdinalIgnoreCase) ||
(settings.FullscreenWindowed &&
SettingsSerializer.FramebufferKeys.Contains(key, StringComparer.OrdinalIgnoreCase));
void Add(string key, string? value)
{
// To the simulator a key past endconfig is not set yet, whatever it says.
@@ -364,6 +538,7 @@ public sealed class SettingsStore
/// <summary>A copy of <paramref name="settings"/> with <paramref name="keys"/> as <paramref name="source"/> has them.</summary>
public SimulatorSettings WithKeysOf(SimulatorSettings settings, SimulatorSettings source, IReadOnlyCollection<string> keys)
{
keys = SettingsSerializer.WithCompanions(keys);
var taken = Render(source);
var config = new ConfigFile();

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

@@ -58,5 +58,9 @@ public sealed class WarehouseEdit
PresetStore.Save(Name, entry);
_saved = entry;
Saved?.Invoke(Name, entry);
}
/// <summary>The consist was written under its name, with this entry - for the list showing it.</summary>
public event Action<string, string>? Saved;
}

View File

@@ -19,6 +19,9 @@ public sealed class ConfigFile
// Its first line, or -1 when the file runs to its end.
private int _end = -1;
// While lines are indexed: the one at hand starts inside a block comment.
private bool _inBlock;
public static ConfigFile Parse(string text)
{
var cfg = new ConfigFile();
@@ -37,7 +40,10 @@ public sealed class ConfigFile
private void IndexLine(int line)
{
if (!TryParseKey(_lines[line], out string key))
// The simulator skips what /* */ encloses, over as many lines as it runs.
bool startsInBlock = _inBlock;
_inBlock = EndsInBlock(_lines[line], startsInBlock);
if (startsInBlock || !TryParseKey(_lines[line], out string key))
return;
if (_end < 0 && key.Equals(EndKey, StringComparison.OrdinalIgnoreCase))
@@ -52,6 +58,7 @@ public sealed class ConfigFile
{
_index.Clear();
_end = -1;
_inBlock = false;
for (int line = 0; line < _lines.Count; line++)
IndexLine(line);
}
@@ -252,17 +259,53 @@ public sealed class ConfigFile
}
}
// Where a comment starts as the simulator's parser sees one: // or /* anywhere, even glued
// to a value, but not within quotes, which it keeps whole.
private static int FindCommentStart(string body)
{
for (int i = 0; i + 1 < body.Length; i++)
bool quoted = false;
for (int i = 0; i < body.Length; i++)
{
if (body[i] == '/' && body[i + 1] == '/' &&
(i == 0 || char.IsWhiteSpace(body[i - 1])))
if (body[i] == '"')
quoted = !quoted;
else if (!quoted && i + 1 < body.Length && body[i] == '/' && body[i + 1] is '/' or '*')
return i;
}
return -1;
}
// Whether a block comment is still open at the end of the line.
private static bool EndsInBlock(string raw, bool inBlock)
{
bool quoted = false;
for (int i = 0; i < raw.Length; i++)
{
if (inBlock)
{
if (raw[i] == '*' && i + 1 < raw.Length && raw[i + 1] == '/')
{
inBlock = false;
i++;
}
continue;
}
if (raw[i] == '"')
quoted = !quoted;
else if (!quoted && raw[i] == '/' && i + 1 < raw.Length)
{
if (raw[i + 1] == '/')
return false;
if (raw[i + 1] == '*')
{
inBlock = true;
i++;
}
}
}
return inBlock;
}
private static int IndexOfWhitespace(string s)
{
for (int i = 0; i < s.Length; i++)

View File

@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -28,6 +30,9 @@ public sealed class TrainsetPreset
public sealed class PresetCollection
{
public List<TrainsetPreset> Presets { get; set; } = new();
/// <summary>The old starter's consists taken in at a start, by <see cref="PresetFile.Fingerprint"/>.</summary>
public List<string> OldStarterSeen { get; set; } = new();
}
public static class PresetStore
@@ -81,33 +86,9 @@ public static class PresetStore
int added = 0;
try
{
string text = File.ReadAllText(path, LegacyText.CodePage1250);
var section = Regex.Matches(text,
@"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in section)
foreach (var consist in OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path))))
{
string name = m.Groups[1].Value.Trim();
if (name.Length == 0) name = $"import_{added + 1}";
var nodes = new List<string>();
foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$"))
{
string body = line.Groups[1].Value.Trim();
if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase))
body += " enddynamic";
nodes.Add(body);
}
if (nodes.Count == 0) continue;
var sb = new StringBuilder();
sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n");
foreach (string n in nodes)
sb.Append(n).Append('\n');
sb.Append("endtrainset\n");
Save(name, sb.ToString());
Save(consist.Name, consist.Entry);
added++;
}
}
@@ -118,6 +99,26 @@ public static class PresetStore
return added;
}
/// <summary>
/// At the start: what the old starter put in its warehouse since the last start
/// joins this one, as that starter showed its magazyn.ini each time it was opened.
/// </summary>
public static void TakeFromOldStarter()
{
string? path = FindMagazynPath();
if (path is null)
return;
try
{
Disk.TakeFromOldStarter(OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path))));
}
catch (Exception ex)
{
Infrastructure.Diagnostics.Log($"Import {path}", ex);
}
}
private static string? FindMagazynPath()
{
string cwd = Directory.GetCurrentDirectory();
@@ -139,6 +140,46 @@ public static class PresetStore
var m = Regex.Match(p.Entry ?? "", @"^\s*trainset\s+\S+\s+(\S+)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
return m.Success ? m.Groups[1].Value : "";
}
}
/// <summary>
/// The old starter's magazyn.ini: a [TRAINSETn=name] line for each consist, then
/// its vehicles as numbered "node … enddynamic" lines.
/// </summary>
public static class OldStarterWarehouse
{
public static List<TrainsetPreset> Read(string text)
{
var consists = new List<TrainsetPreset>();
var sections = Regex.Matches(text,
@"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in sections)
{
string name = m.Groups[1].Value.Trim();
if (name.Length == 0) name = $"import_{consists.Count + 1}";
var nodes = new List<string>();
foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$"))
{
string body = line.Groups[1].Value.Trim();
if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase))
body += " enddynamic";
nodes.Add(body);
}
if (nodes.Count == 0) continue;
var sb = new StringBuilder();
sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n");
foreach (string n in nodes)
sb.Append(n).Append('\n');
sb.Append("endtrainset\n");
consists.Add(new TrainsetPreset { Name = name, Entry = sb.ToString() });
}
return consists;
}
private static string Sanitize(string name) =>
string.IsNullOrWhiteSpace(name) ? "preset" : name.Replace(' ', '_');
@@ -193,6 +234,55 @@ public sealed class PresetFile
Persist(col, read);
}
/// <summary>Where a consist of the old starter goes when one of its name with other vehicles is here.</summary>
public const string OldStarterSuffix = " (magazyn.ini)";
/// <summary>
/// Takes in the old starter's consists not taken at an earlier start, so one
/// removed here stays removed while the old starter keeps it as it was. One
/// whose name is here with other vehicles comes in beside it, unless what is
/// here is that consist as an earlier start brought it, untouched since.
/// </summary>
/// <returns>How many came in.</returns>
public int TakeFromOldStarter(IReadOnlyList<TrainsetPreset> found)
{
// A file that cannot be read is not replaced by an import nobody asked for.
if (found.Count == 0 || !TryRead(out var col))
return 0;
var seenBefore = new HashSet<string>(col.OldStarterSeen, StringComparer.Ordinal);
var seen = new HashSet<string>(seenBefore, StringComparer.Ordinal);
int added = 0;
foreach (var consist in found)
{
if (!seen.Add(Fingerprint(consist)))
continue;
var here = col.Presets.Find(p => string.Equals(p.Name, consist.Name, StringComparison.OrdinalIgnoreCase));
if (here is not null && here.Entry == consist.Entry)
continue;
string name = here is null || seenBefore.Contains(Fingerprint(here))
? consist.Name
: consist.Name + OldStarterSuffix;
col.Presets.RemoveAll(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
col.Presets.Add(new TrainsetPreset { Name = name, Entry = consist.Entry });
added++;
}
if (seen.Count == seenBefore.Count)
return 0;
col.OldStarterSeen = seen.Order(StringComparer.Ordinal).ToList();
col.Presets.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
Persist(col, read: true);
return added;
}
/// <summary>A consist by its name and vehicles, short enough to keep each one ever taken in.</summary>
public static string Fingerprint(TrainsetPreset preset) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(preset.Name + "\n" + preset.Entry)));
/// <summary>The file's presets; false, with none, when there is a file but they cannot be had from it.</summary>
private bool TryRead(out PresetCollection col)
{

View File

@@ -19,11 +19,27 @@ public class SettingRow : ContentControl
AvaloniaProperty.Register<SettingRow, string?>(nameof(ValueText));
/// <summary>
/// Why the simulator to be started would pass this setting over; the row dims
/// and says so. The input stays usable - the file may serve another build.
/// A setting for those who know what it does: the standard mode leaves it out, as
/// one a player can break the game with or has no need of.
/// </summary>
public static readonly StyledProperty<string?> IdleNoteProperty =
AvaloniaProperty.Register<SettingRow, string?>(nameof(IdleNote));
public static readonly StyledProperty<bool> AdvancedProperty =
AvaloniaProperty.Register<SettingRow, bool>(nameof(Advanced));
public bool Advanced
{
get => GetValue(AdvancedProperty);
set => SetValue(AdvancedProperty, value);
}
/// <summary>The value eu07.ini gives the setting that the starter cannot read, said under it; null when there is none.</summary>
public static readonly StyledProperty<string?> UnknownValueProperty =
AvaloniaProperty.Register<SettingRow, string?>(nameof(UnknownValue));
public string? UnknownValue
{
get => GetValue(UnknownValueProperty);
set => SetValue(UnknownValueProperty, value);
}
public string? Label
{
@@ -49,12 +65,6 @@ public class SettingRow : ContentControl
set => SetValue(ValueTextProperty, value);
}
public string? IdleNote
{
get => GetValue(IdleNoteProperty);
set => SetValue(IdleNoteProperty, value);
}
public SettingRow()
{
UpdatePseudoClasses();
@@ -68,22 +78,19 @@ public class SettingRow : ContentControl
change.Property == DescriptionProperty ||
change.Property == ConfigKeyProperty ||
change.Property == ValueTextProperty ||
change.Property == IdleNoteProperty ||
change.Property == UnknownValueProperty ||
change.Property == ContentProperty)
UpdatePseudoClasses();
if (change.Property == IdleNoteProperty)
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
if (change.Property == LabelProperty || change.Property == ContentProperty)
ScreenReaderNames.NameInputs(Content, Label);
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
ScreenReaderNames.TellValue(Content, ValueText);
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
if (change.Property == DescriptionProperty || change.Property == UnknownValueProperty ||
change.Property == ContentProperty)
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
}
// Again once in the window: a panel given as content may be filled after it was set.
@@ -92,7 +99,7 @@ public class SettingRow : ContentControl
base.OnLoaded(e);
ScreenReaderNames.NameInputs(Content, Label);
ScreenReaderNames.TellValue(Content, ValueText);
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
}
private void UpdatePseudoClasses()
@@ -102,6 +109,6 @@ public class SettingRow : ContentControl
PseudoClasses.Set(":no-key", string.IsNullOrEmpty(ConfigKey));
PseudoClasses.Set(":no-value", string.IsNullOrEmpty(ValueText));
PseudoClasses.Set(":no-content", Content is null);
PseudoClasses.Set(":idle", !string.IsNullOrEmpty(IdleNote));
PseudoClasses.Set(":unknown", !string.IsNullOrEmpty(UnknownValue));
}
}

View File

@@ -7,6 +7,16 @@ namespace StarterNG.Controls;
public class SettingsSection : HeaderedContentControl
{
/// <summary>Every row of the section is for the advanced mode only.</summary>
public static readonly StyledProperty<bool> AdvancedProperty =
AvaloniaProperty.Register<SettingsSection, bool>(nameof(Advanced));
public bool Advanced
{
get => GetValue(AdvancedProperty);
set => SetValue(AdvancedProperty, value);
}
public static readonly StyledProperty<object?> ToggleProperty =
AvaloniaProperty.Register<SettingsSection, object?>(nameof(Toggle));

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using StarterNG.Classes;
namespace StarterNG.Domain;
/// <summary>A stretch of a consist made of vehicles alike, shown as one picture with a count.</summary>
public sealed record ConsistRun(Dynamic First, int Count);
public static class ConsistRuns
{
/// <summary>
/// The consist's vehicles in order, those next to each other that look alike taken together.
/// </summary>
/// <param name="keyOf">
/// What makes two vehicles alike, given the vehicle and its place in the consist.
/// No key keeps the vehicle on its own.
/// </param>
public static List<ConsistRun> Of(IReadOnlyList<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf)
{
var runs = new List<ConsistRun>();
string? prevKey = null;
for (int i = 0; i < vehicles.Count; i++)
{
string? key = keyOf(vehicles[i], i);
if (key is not null && prevKey is not null && runs.Count > 0 &&
string.Equals(key, prevKey, StringComparison.OrdinalIgnoreCase))
{
var last = runs[^1];
runs[^1] = last with { Count = last.Count + 1 };
}
else
{
runs.Add(new ConsistRun(vehicles[i], 1));
}
prevKey = key;
}
return runs;
}
}

View File

@@ -64,6 +64,13 @@ public enum SceneryFaultKind
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
IncludeNotClosed,
/// <summary>
/// A vehicle whose <c>.fiz</c> is not in its folder under dynamic: the simulator
/// leaves it out, and its trainset runs short. <see cref="SceneryFault.Token"/>
/// names the file.
/// </summary>
VehicleMissing,
/// <summary>A trainset the starter could not read, for a reason none of the above names.</summary>
TrainsetUnreadable,

View File

@@ -15,9 +15,10 @@ namespace StarterNG.Domain.Sceneries;
/// include, so they are not loaded twice.
/// </summary>
/// <remarks>
/// Only the plain <c>include path end</c> form: an include with parameters needs
/// them put in, and one whose <c>end</c> is not on its line is read by the
/// simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
/// Only the plain <c>include path end</c> form, or <c>include path</c> as the last
/// thing in the file, where the simulator runs out of words before it would
/// look for an <c>end</c>: an include with parameters needs them put in, and one
/// whose <c>end</c> is not on its line is read by the simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
/// whether it is loaded is the player's to choose. Each inlined file is wrapped in
/// marker comments, which is how a trainset is told to belong to it.
/// </remarks>
@@ -29,7 +30,8 @@ public static class SceneryIncludes
private static readonly Regex FirstInit = new(@"\bFirstInit\b", RegexOptions.IgnoreCase);
private static readonly Regex Include = new(
@"^[ \t]*include[ \t]+(\S+)[ \t]+end\b[^\r\n]*", RegexOptions.Multiline | RegexOptions.IgnoreCase);
@"^[ \t]*include[ \t]+(\S+?)(?:[ \t]+end\b[^\r\n]*|[ \t]*(?://[^\r\n]*)?\s*\z)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
private static readonly Regex HasTrainset = new(@"^[ \t]*trainset\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);

View File

@@ -33,13 +33,18 @@ public static class ScenerySyntax
/// 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, bool>? opensInclude = null)
/// <param name="loadsVehicle">
/// Whether the simulator finds a vehicle's definition, by its folder under dynamic
/// and its .mmd's name, as the scenery writes them; null leaves vehicles unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null,
Func<string, string, bool>? loadsVehicle = 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, opensInclude, asSimulator: true);
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true, loadsVehicle);
simulator.Run();
var author = new Reading(tokens, lines, null, asSimulator: false);
author.Run();
@@ -110,7 +115,8 @@ public static class ScenerySyntax
}
private sealed class Reading(
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator,
Func<string, string, bool>? loadsVehicle = null)
{
public readonly List<(int Start, int End, string Name)> Trainsets = new();
public readonly List<(int, int)> Loose = new();
@@ -253,6 +259,9 @@ public static class ScenerySyntax
return tokens.Count - 1;
}
if (complete)
Definition(at, name);
var (fault, trackless) = CheckFields(at, complete, inTrainset, name);
if (fault is null && !closed)
fault = SceneryFaultKind.VehicleNotClosed;
@@ -267,6 +276,16 @@ public static class ScenerySyntax
return end;
}
// Without its .fiz the simulator makes nothing of the vehicle, and reads on to the next.
private void Definition(int at, string name)
{
string folder = tokens[at + 5].Text;
string mmd = tokens[at + 7].Text;
if (loadsVehicle is null || !Plain(folder) || !Plain(mmd) || loadsVehicle(folder, mmd))
return;
Fault(SceneryFaultKind.VehicleMissing, tokens[at].Index, name, $"{folder}/{mmd}.fiz");
}
// As the author meant it: there to be listed, whatever is wrong with it.
private int ListVehicle(int at, bool complete, bool closed, int meant)
{
@@ -378,7 +397,8 @@ public static class ScenerySyntax
while (end < tokens.Count && tokens[end].Text != "end")
end++;
int last = Math.Min(end, tokens.Count - 1);
if (Lost(at + 1, last) is not null)
// No "end" at all is a mistake too, even where the file runs out before it costs anything.
if (end >= tokens.Count || Lost(at + 1, last) is not null)
Fault(SceneryFaultKind.IncludeNotClosed, token.Index, token: name, swallowed: (at + 1, last));
return last;
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace StarterNG.Domain.Settings;
@@ -40,176 +39,42 @@ public sealed record GraphicsExtras(
}
/// <summary>
/// What only Ultra sets, switches and limits with no scale to climb. Not every best is the
/// top of a scale: shadows are longest with the limit at its bottom, the regulator and the
/// release of textures would only take away, off.
/// Left to the player, picture unchanged: separate windows for the screens
/// (python.displaywindows, python.vsync), texture streaming, the frame pacing.
/// What only Ultra sets, with no scale to climb: the longest shadows, at the bottom of their
/// limit, and the screens drawn. What only the advanced mode shows no level sets.
/// </summary>
/// <param name="ShadowAngleLimit">gfx.shadow.angle.min: how low the sun counts for shadows, so how long they
/// get: up to 5× the height of what casts them at 0.2, no longer than it at 1 (opengl33renderer.cpp).</param>
/// <param name="TargetFps">targetfps: above 0 the simulator moves the distance factor by itself.</param>
/// <param name="ScreenWindowFps">python.fpslimit: read only by the screens' separate windows
/// (pythonscreenviewer.cpp), it does nothing without them.</param>
/// <param name="TextureRelease">gfx.textures.releasedistance: above 0 textures of far vehicles leave the card.</param>
/// <param name="CompressTextures">compresstex: on saves card memory at a cost to the picture.</param>
/// <param name="SkipDecor">starter.ignoreirrelevant: on leaves decorative consists out of the scenario.</param>
public sealed record GraphicsTop(
double ShadowAngleLimit,
double TargetFps,
double ScreenWindowFps,
double TextureRelease,
bool Screens,
bool ScreenMipmaps,
bool CompressTextures,
bool SkipDecor,
bool Sky,
bool Cab,
bool AirCouplers,
bool SmoothTraction)
/// <param name="Screens">python.enabled.</param>
public sealed record GraphicsTop(double ShadowAngleLimit, bool Screens)
{
public const string TargetFpsKey = "targetfps";
public const string ScreenWindowFpsKey = "python.fpslimit";
public const string TextureReleaseKey = "gfx.textures.releasedistance";
public const string SkyKey = "skyenabled";
public const string CabKey = "rendercab";
public const string AirCouplersKey = "newaircouplers";
public const string SmoothTractionKey = "smoothtraction";
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
public static readonly IReadOnlyList<string> RowKeys = new[]
{
TargetFpsKey, ScreenWindowFpsKey, TextureReleaseKey, SkyKey, CabKey, AirCouplersKey, SmoothTractionKey
};
/// <summary>The eu07.ini keys these values live in.</summary>
public static readonly IReadOnlyList<string> Keys = RowKeys.Concat(new[]
{
"gfx.shadow.angle.min", "python.enabled", "python.mipmaps", "compresstex", "starter.ignoreirrelevant"
}).ToList();
public static readonly IReadOnlyList<string> Keys = new[] { "gfx.shadow.angle.min", "python.enabled" };
/// <summary>What they are with nothing set, as <see cref="GraphicsExtras.None"/>.</summary>
public static readonly GraphicsTop None =
new(0.2, 0, 100, 0, true, true, true, false, true, true, true, true);
public static readonly GraphicsTop None = new(0.2, true);
public static GraphicsTop Of(SimulatorSettings s) =>
new(s.ShadowAngleLimit, GraphicsPreset.NumberOf(s, TargetFpsKey),
GraphicsPreset.NumberOf(s, ScreenWindowFpsKey), GraphicsPreset.NumberOf(s, TextureReleaseKey),
s.PythonScreens, s.ScreenMipmaps, s.CompressTextures, s.IgnoreIrrelevantTrains,
GraphicsPreset.ToggleOf(s, SkyKey), GraphicsPreset.ToggleOf(s, CabKey),
GraphicsPreset.ToggleOf(s, AirCouplersKey), GraphicsPreset.ToggleOf(s, SmoothTractionKey));
public static GraphicsTop Of(SimulatorSettings s) => new(s.ShadowAngleLimit, s.PythonScreens);
public void ApplyTo(SimulatorSettings s)
{
void Number(string key, double value) => s.Extra[key] = value.ToString(CultureInfo.InvariantCulture);
void Toggle(string key, bool value) => s.Extra[key] = SimulatorKey.FormatToggle(value);
s.ShadowAngleLimit = ShadowAngleLimit;
Number(TargetFpsKey, TargetFps);
Number(ScreenWindowFpsKey, ScreenWindowFps);
Number(TextureReleaseKey, TextureRelease);
s.PythonScreens = Screens;
s.ScreenMipmaps = ScreenMipmaps;
s.CompressTextures = CompressTextures;
s.IgnoreIrrelevantTrains = SkipDecor;
Toggle(SkyKey, Sky);
Toggle(CabKey, Cab);
Toggle(AirCouplersKey, AirCouplers);
Toggle(SmoothTractionKey, SmoothTraction);
}
}
/// <summary>
/// What only the simulators with the OpenGL 4.6 and Vulkan 1.4 renderers read, the others pass it
/// over. High is what they do with nothing set. Left to the player: frame generation, Reflex, the
/// choice of the card, automatic exposure, the fitted cascades and the bounced light of the cab.
/// </summary>
/// <param name="CabProbeInterval">gfx.cabprobe.interval, in frames: the lower the dearer.</param>
/// <param name="RayTracing">gfx.raytracing: the Vulkan renderer's alone, off on OpenGL.</param>
public sealed record GraphicsNewRenderer(
int LampShadows,
int ContactShadows,
int Occlusion,
int OcclusionSlices,
int OcclusionSteps,
bool OcclusionLighting,
int CabProbe,
int CabProbeInterval,
bool CabProbeReflections,
int ScreenReflections,
bool RayTracing,
bool VolumetricFog,
int FogQuality,
int Clouds,
bool CloudShadows,
bool Grass,
int GrassDistance,
double GrassDensity,
int Precipitation,
bool Bloom)
{
/// <summary>The eu07.ini keys these values live in; the fade of the grass follows its distance.</summary>
public static readonly IReadOnlyList<string> Keys = new[]
{
"gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality", "gfx.postfx.ao.lighting",
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections", "gfx.ssr", "gfx.raytracing",
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows",
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
"gfx.precipitation.particles", "gfx.postfx.bloom"
};
public static GraphicsNewRenderer Of(SimulatorSettings s) =>
new(s.LightShadows, s.ContactShadows, s.AmbientOcclusion, s.AoSlices, s.AoSteps, s.AoLighting,
s.CabProbe, s.CabProbeInterval, s.CabProbeReflections, s.Ssr, s.RayTracing,
s.VolumetricFog, s.FogQuality, s.Clouds, s.CloudShadows,
s.Grass, s.GrassDistance, s.GrassDensity, s.PrecipitationParticles, s.Bloom);
/// <summary>This level as it lands on <paramref name="s"/>: ray tracing on Vulkan only.</summary>
public GraphicsNewRenderer For(SimulatorSettings s) =>
GraphicsRules.RayTracingAllowed(s) ? this : this with { RayTracing = false };
public void ApplyTo(SimulatorSettings s)
{
s.LightShadows = LampShadows;
s.ContactShadows = ContactShadows;
s.AmbientOcclusion = Occlusion;
s.AoSlices = OcclusionSlices;
s.AoSteps = OcclusionSteps;
s.AoLighting = OcclusionLighting;
s.CabProbe = CabProbe;
s.CabProbeInterval = CabProbeInterval;
s.CabProbeReflections = CabProbeReflections;
s.Ssr = ScreenReflections;
s.RayTracing = RayTracing && GraphicsRules.RayTracingAllowed(s);
s.VolumetricFog = VolumetricFog;
s.FogQuality = FogQuality;
s.Clouds = Clouds;
s.CloudShadows = CloudShadows;
s.Grass = Grass;
s.GrassDistance = GrassDistance;
s.GrassDensity = GrassDensity;
s.PrecipitationParticles = Precipitation;
s.Bloom = Bloom;
}
}
/// <summary>
/// A level of detail set in one go: what weighs on the graphics card. Every scale climbs in
/// even steps from <see cref="Minimal"/> to <see cref="Ultra"/>, as far as it has steps for six
/// levels. The screen (resolution, field of view), the frame pacing and the effects that are a
/// matter of taste - motion blur, chromatic aberration - stay as they are, except at the
/// two ends of the scale, which have <see cref="Extras"/>.
/// levels. A level sets only what the standard mode shows, and only to what its sliders offer
/// (<see cref="SliderRanges"/>, the old starter's ranges): never past the old starter. The screen
/// (resolution, buffer, field of view), the frame pacing and the effects that are a matter of
/// taste - motion blur, chromatic aberration - stay as they are, except at the two ends of the
/// scale, which have <see cref="Extras"/>.
/// </summary>
/// <param name="NameKey">Its name's translation key.</param>
/// <param name="CabShadowsRange">gfx.shadows.cab.range, in metres, read only by the legacy renderer.</param>
/// <param name="AntiAliasing">Multisampling, as older simulators read it too. DLSS, once on, stays: no level does better.</param>
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second.</param>
/// <param name="DrawRange">basedrawrange, in metres. Below 2000 it changes nothing on screen: the renderer
/// keeps at least that for signals and lights (opengl33renderer.cpp).</param>
/// <param name="DistanceFactor">heightbase: the only thing that draws less than those 2 km, and draws
/// shapes, wires and sections nearer. A regulating targetfps moves it from there.</param>
/// <param name="BufferScale">starter.bufferscale, in percent. Above the screen over High: on a 4K one
/// Ultra is a picture of 8K, multisampled on top.</param>
/// <param name="AntiAliasing">multisampling.</param>
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second, one of the old starter's steps.</param>
/// <param name="DrawRangeFactor">gfx.drawrange.factor.max: how far the regulator may stretch the draw range.</param>
public sealed record GraphicsPreset(
string NameKey,
@@ -228,122 +93,73 @@ public sealed record GraphicsPreset(
double ReflectionsRate,
bool ExtraEffects,
int SplineFidelity,
double DrawRange,
double DistanceFactor,
int BufferScale,
double SleeperDistance,
double DrawRangeFactor,
double ReflectedInstances,
double ReflectedVehicles,
int CabShadowsRange,
GraphicsNewRenderer NewRenderer,
GraphicsExtras? Extras = null,
GraphicsTop? Top = null)
{
public const string DrawRangeKey = "basedrawrange";
public const string DistanceFactorKey = "heightbase";
public const string SleeperKey = "sleeperdistance";
public const string ReflectedInstancesKey = "gfx.reflections.range_instances";
public const string ReflectedVehiclesKey = "gfx.reflections.range_vehicles";
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
public static readonly IReadOnlyList<string> RowKeys = new[]
{
DrawRangeKey, DistanceFactorKey, SleeperKey, ReflectedInstancesKey, ReflectedVehiclesKey
};
/// <summary>The eu07.ini keys a level sets.</summary>
public static readonly IReadOnlyList<string> Keys = new[]
{
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "gfx.antialiasing", "dynamiclights",
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "dynamiclights",
"gfx.smoke.fidelity", "shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff",
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.extraeffects",
"splinefidelity", DrawRangeKey, DistanceFactorKey, "starter.bufferscale", "gfx.buffer.percent", SleeperKey,
"gfx.drawrange.factor.max", ReflectedInstancesKey, ReflectedVehiclesKey, "gfx.shadows.cab.range"
}.Concat(GraphicsNewRenderer.Keys).ToList();
"splinefidelity", "gfx.drawrange.factor.max", "gfx.shadows.cab.range"
};
/// <summary>The last resort: no shadows, no reflections, no effects, no smoke, a softer picture.</summary>
/// <summary>The last resort: no shadows, no reflections, no effects, no smoke.</summary>
public static readonly GraphicsPreset Minimal = new(
"PresetMinimal", TextureSize: 512, CabTextureSize: 512, Anisotropy: 1, AntiAliasing: AntiAliasingMode.Off,
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 512, ShadowRange: 75, ShadowRank: 1,
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1 / 300.0, ExtraEffects: false,
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.6, BufferScale: 70,
SleeperDistance: 100, DrawRangeFactor: 1, ReflectedInstances: 250, ReflectedVehicles: 50, CabShadowsRange: 0,
NewRenderer: new GraphicsNewRenderer(LampShadows: 0, ContactShadows: 0, Occlusion: 0, OcclusionSlices: 2, OcclusionSteps: 3,
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 0,
RayTracing: false, VolumetricFog: false, FogQuality: 1, Clouds: 0, CloudShadows: false, Grass: false,
GrassDistance: 30, GrassDensity: 0.25, Precipitation: 16384, Bloom: false),
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 1024, ShadowRange: 75, ShadowRank: 1,
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: false,
SplineFidelity: 1, DrawRangeFactor: 1, CabShadowsRange: 0,
Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800));
public static readonly GraphicsPreset Low = new(
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 2, AntiAliasing: AntiAliasingMode.Off,
DynamicLights: 3, SmokeFidelity: 1, Shadows: true, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 2,
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1 / 60.0, ExtraEffects: true,
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.7, BufferScale: 80,
SleeperDistance: 150, DrawRangeFactor: 1.5, ReflectedInstances: 400, ReflectedVehicles: 100, CabShadowsRange: 0,
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 2, OcclusionSteps: 3,
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 1,
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: false, Grass: true,
GrassDistance: 40, GrassDensity: 0.5, Precipitation: 32768, Bloom: true));
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: true,
SplineFidelity: 2, DrawRangeFactor: 1, CabShadowsRange: 0);
public static readonly GraphicsPreset Medium = new(
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 4, AntiAliasing: AntiAliasingMode.Msaa2,
DynamicLights: 5, SmokeFidelity: 2, Shadows: true, ShadowMap: 1024, ShadowRange: 175, ShadowRank: 2,
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1 / 30.0, ExtraEffects: true,
SplineFidelity: 2, DrawRange: 2250, DistanceFactor: 0.85, BufferScale: 90,
SleeperDistance: 200, DrawRangeFactor: 2, ReflectedInstances: 550, ReflectedVehicles: 150, CabShadowsRange: 20,
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 3, OcclusionSteps: 4,
OcclusionLighting: false, CabProbe: 1, CabProbeInterval: 8, CabProbeReflections: true, ScreenReflections: 1,
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: true, Grass: true,
GrassDistance: 50, GrassDensity: 0.75, Precipitation: 32768, Bloom: true));
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1, ExtraEffects: true,
SplineFidelity: 2, DrawRangeFactor: 2, CabShadowsRange: 20);
/// <summary>
/// Where a player with no settings of their own starts. The simulator's own values (Globals.h),
/// but for smoke, track curves, reflections and cab shadows: theirs are the bottom of a scale
/// with levels to go under this one.
/// with levels to go under this one, or below what the old starter offered.
/// </summary>
public static readonly GraphicsPreset High = new(
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa4,
DynamicLights: 7, SmokeFidelity: 2, Shadows: true, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 0.1, ExtraEffects: true,
SplineFidelity: 2, DrawRange: 2500, DistanceFactor: 1, BufferScale: 100,
SleeperDistance: 250, DrawRangeFactor: 3, ReflectedInstances: 750, ReflectedVehicles: 250, CabShadowsRange: 40,
NewRenderer: new GraphicsNewRenderer(LampShadows: 2, ContactShadows: 0, Occlusion: 2, OcclusionSlices: 3, OcclusionSteps: 4,
OcclusionLighting: true, CabProbe: 2, CabProbeInterval: 4, CabProbeReflections: true, ScreenReflections: 2,
RayTracing: false, VolumetricFog: true, FogQuality: 2, Clouds: 2, CloudShadows: true, Grass: true,
GrassDistance: 60, GrassDensity: 1, Precipitation: 65536, Bloom: true));
/// <summary>For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.</summary>
public static readonly GraphicsPreset VeryHigh = new(
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 2, ExtraEffects: true,
SplineFidelity: 3, DrawRange: 5000, DistanceFactor: 2, BufferScale: 150,
SleeperDistance: 2000, DrawRangeFactor: 3, ReflectedInstances: 1500, ReflectedVehicles: 1000, CabShadowsRange: 70,
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 2, Occlusion: 2, OcclusionSlices: 4, OcclusionSteps: 6,
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 3, CabProbeReflections: true, ScreenReflections: 3,
RayTracing: false, VolumetricFog: true, FogQuality: 3, Clouds: 3, CloudShadows: true, Grass: true,
GrassDistance: 120, GrassDensity: 1.5, Precipitation: 131072, Bloom: true));
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 3, ExtraEffects: true,
SplineFidelity: 2, DrawRangeFactor: 3, CabShadowsRange: 30);
/// <summary>
/// Every value at the top of what the screen offers. Not the best picture throughout: a map
/// of 8192 stretches the cascades fourfold, so shadows reach 2400 m but are coarser up close
/// than at <see cref="VeryHigh"/>.
/// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.
/// Filtering stays as High's, so the textures tell this level from Ultra.
/// </summary>
public static readonly GraphicsPreset VeryHigh = new(
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 10, ExtraEffects: true,
SplineFidelity: 3, DrawRangeFactor: 3, CabShadowsRange: 50);
/// <summary>
/// The top of every slider, which is the most the old starter gave. Not the best picture
/// throughout: a map of 8192 stretches the cascades fourfold, so shadows reach 1600 m but are
/// coarser up close than at <see cref="VeryHigh"/>.
/// </summary>
public static readonly GraphicsPreset Ultra = new(
"PresetUltra", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 600, ShadowRank: 3,
"PresetUltra", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 400, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 60, ExtraEffects: true,
SplineFidelity: 4, DrawRange: 10000, DistanceFactor: 3, BufferScale: 200,
SleeperDistance: 5000, DrawRangeFactor: 3, ReflectedInstances: 3000, ReflectedVehicles: 2000, CabShadowsRange: 100,
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 3, Occlusion: 2, OcclusionSlices: 6, OcclusionSteps: 8,
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 2, CabProbeReflections: true, ScreenReflections: 3,
RayTracing: true, VolumetricFog: true, FogQuality: 4, Clouds: 4, CloudShadows: true, Grass: true,
GrassDistance: 300, GrassDensity: 2, Precipitation: 262144, Bloom: true),
SplineFidelity: 4, DrawRangeFactor: 3, CabShadowsRange: 100,
Extras: new GraphicsExtras(MotionBlur: true, ChromaticAberration: true, Smoke: true, PythonUpdateMs: 200),
Top: new GraphicsTop(ShadowAngleLimit: 0.2, TargetFps: 0, ScreenWindowFps: 200, TextureRelease: 0,
Screens: true, ScreenMipmaps: true, CompressTextures: false, SkipDecor: false,
Sky: true, Cab: true, AirCouplers: true, SmoothTraction: true));
Top: new GraphicsTop(ShadowAngleLimit: 0.2, Screens: true));
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra };
@@ -352,8 +168,7 @@ public sealed record GraphicsPreset(
s.MaxTextureSize = TextureSize;
s.MaxCabTextureSize = CabTextureSize;
s.TextureFiltering = Anisotropy;
if (!GraphicsRules.IsDlss(s.AntiAliasing))
s.AntiAliasing = AntiAliasing;
s.AntiAliasing = AntiAliasing;
s.CabShadowsRange = CabShadowsRange;
s.DynamicLights = DynamicLights;
s.SmokeFidelity = SmokeFidelity;
@@ -366,14 +181,7 @@ public sealed record GraphicsPreset(
s.ReflectionsFramerate = ReflectionsRate;
s.ExtraEffects = ExtraEffects;
s.SplineFidelity = SplineFidelity;
s.Extra[DrawRangeKey] = DrawRange.ToString(CultureInfo.InvariantCulture);
s.Extra[DistanceFactorKey] = DistanceFactor.ToString(CultureInfo.InvariantCulture);
s.BufferScalePercent = BufferScale;
s.Extra[SleeperKey] = SleeperDistance.ToString(CultureInfo.InvariantCulture);
s.DrawRangeFactor = DrawRangeFactor;
s.Extra[ReflectedInstancesKey] = ReflectedInstances.ToString(CultureInfo.InvariantCulture);
s.Extra[ReflectedVehiclesKey] = ReflectedVehicles.ToString(CultureInfo.InvariantCulture);
NewRenderer.ApplyTo(s);
Extras?.ApplyTo(s);
Top?.ApplyTo(s);
}
@@ -381,20 +189,14 @@ public sealed record GraphicsPreset(
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
public bool Matches(SimulatorSettings s) =>
s.MaxTextureSize == TextureSize && s.MaxCabTextureSize == CabTextureSize &&
Near(s.TextureFiltering, Anisotropy) && (GraphicsRules.IsDlss(s.AntiAliasing) || s.AntiAliasing == AntiAliasing) &&
Near(s.TextureFiltering, Anisotropy) && s.AntiAliasing == AntiAliasing &&
s.DynamicLights == DynamicLights && s.SmokeFidelity == SmokeFidelity &&
s.RenderShadows == Shadows && s.ShadowMapResolution == ShadowMap &&
s.ShadowProjectionRange == ShadowRange && s.ShadowRankCutoff == ShadowRank &&
s.EnvMap == EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
Near(s.ReflectionsFramerate, ReflectionsRate) && s.ExtraEffects == ExtraEffects &&
s.SplineFidelity == SplineFidelity && Near(NumberOf(s, DrawRangeKey), DrawRange) &&
Near(NumberOf(s, DistanceFactorKey), DistanceFactor) &&
s.BufferScalePercent == BufferScale &&
Near(NumberOf(s, SleeperKey), SleeperDistance) && Near(s.DrawRangeFactor, DrawRangeFactor) &&
Near(NumberOf(s, ReflectedInstancesKey), ReflectedInstances) &&
Near(NumberOf(s, ReflectedVehiclesKey), ReflectedVehicles) &&
s.SplineFidelity == SplineFidelity && Near(s.DrawRangeFactor, DrawRangeFactor) &&
s.CabShadowsRange == CabShadowsRange &&
GraphicsNewRenderer.Of(s) == NewRenderer.For(s) &&
(Extras is null || GraphicsExtras.Of(s) == Extras) &&
(Top is null || GraphicsTop.Of(s) == Top);
@@ -407,31 +209,23 @@ public sealed record GraphicsPreset(
return key.ParseNumber(key.RawIn(s));
}
internal static bool ToggleOf(SimulatorSettings s, string name) =>
SimulatorKey.ParseToggle(SimulatorKeys.Named(name).RawIn(s));
// As the file rounds it: 1/300 comes back as 0.003333.
// As the file rounds it.
private static bool Near(double value, double target) =>
Math.Abs(value - target) <= Math.Abs(target) * 2e-4 + 1e-9;
}
/// <summary>
/// A part of the picture with a level of its own, as its section on the screen has it. The rest
/// of a level - the buffer, the anti-aliasing, the post-processing switches, the frame pacing, the sky and the cab - goes only with the whole.
/// of a level - the anti-aliasing, the post-processing switches, the dynamic lights and the smoke - goes only with the whole.
/// </summary>
/// <param name="Keys">The eu07.ini keys it sets.</param>
public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
{
public static readonly GraphicsGroup DrawRange = new(new[]
{
GraphicsPreset.DrawRangeKey, GraphicsPreset.DistanceFactorKey, "splinefidelity",
GraphicsPreset.SleeperKey, "gfx.drawrange.factor.max"
});
public static readonly GraphicsGroup DrawRange = new(new[] { "splinefidelity", "gfx.drawrange.factor.max" });
public static readonly GraphicsGroup Textures = new(new[]
{
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering",
"compresstex", GraphicsTop.TextureReleaseKey
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering"
});
public static readonly GraphicsGroup Shadows = new(new[]
@@ -439,39 +233,20 @@ public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
"shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff", "gfx.shadow.angle.min", "gfx.shadows.cab.range"
});
public static readonly GraphicsGroup Lights = new(new[]
{
"dynamiclights", "gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality",
"gfx.postfx.ao.lighting", "gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections"
});
public static readonly GraphicsGroup Reflections = new(new[]
{
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate",
GraphicsPreset.ReflectedInstancesKey, GraphicsPreset.ReflectedVehiclesKey, "gfx.ssr", "gfx.raytracing"
});
public static readonly GraphicsGroup Atmosphere = new(new[]
{
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows"
});
public static readonly GraphicsGroup Nature = new(new[]
{
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
"gfx.smoke", "gfx.smoke.fidelity", "gfx.precipitation.particles"
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate"
});
public static readonly IReadOnlyList<GraphicsGroup> All = new[]
{
DrawRange, Textures, Shadows, Lights, Reflections, Atmosphere, Nature
DrawRange, Textures, Shadows, Reflections
};
}
/// <summary>What applying a level touched.</summary>
/// <param name="RowKeys">The keys of <see cref="SimulatorKeys"/> rows to show its values in, in that order.</param>
/// <param name="ChosenKeys">The eu07.ini keys it chose as a whole.</param>
public sealed record PresetApplied(IReadOnlyList<string> RowKeys, IReadOnlyList<string> ChosenKeys);
public sealed record PresetApplied(IReadOnlyList<string> ChosenKeys);
/// <summary>
/// Remembers what was there before an end of the scale, which comes back with any level
@@ -498,15 +273,11 @@ public sealed class GraphicsPresetMemory
comingTop?.ApplyTo(settings);
preset.ApplyTo(settings);
var rows = new List<string>(GraphicsPreset.RowKeys);
var chosen = new List<string>(GraphicsPreset.Keys);
if (preset.Extras is not null || coming is not null)
chosen.AddRange(GraphicsExtras.Keys);
if (preset.Top is not null || comingTop is not null)
{
chosen.AddRange(GraphicsTop.Keys);
rows.AddRange(GraphicsTop.RowKeys);
}
return new PresetApplied(rows, chosen);
return new PresetApplied(chosen);
}
}

View File

@@ -1,115 +1,32 @@
namespace StarterNG.Domain.Settings;
/// <summary>
/// What the simulator does with combinations of graphics settings, mirrored here so
/// the starter only offers what takes effect and writes eu07.ini the way the
/// simulator will run it (utilities/Globals.cpp, rendering/vulkan14, rendering/opengl46).
/// What the simulator does with graphics values, mirrored here so the starter writes
/// eu07.ini the way the simulator will run it (utilities/Globals.cpp), and how far the
/// starter lets them go: no further than the old starter did (MaSzyna-EU07/Starter).
/// </summary>
public static class GraphicsRules
{
public static bool IsDlss(AntiAliasingMode mode) => mode is AntiAliasingMode.Dlss or AntiAliasingMode.Dlaa;
/// <summary>maxcabtexturesize: the old starter's list ended at 4096.</summary>
public const int MaxCabTextureSize = 4096;
public static bool IsTemporal(AntiAliasingMode mode) => mode == AntiAliasingMode.Taa || IsDlss(mode);
public static bool IsVulkan(SimulatorSettings s) => s.Backend == GraphicsBackend.Vulkan;
/// <summary>The projection range of shadowtune: the old starter's list ended at 400.</summary>
public const int MaxShadowRange = 400;
/// <summary>
/// DLSS is the Vulkan renderer's only (the OpenGL one takes TAA instead), and the
/// DLSS SDK has no macOS libraries.
/// The frame buffer, in percent of the window. The old starter's choice of buffer
/// (gfx.framebuffer.fidelity) is not read by the simulator, so it always had the window's size.
/// </summary>
public static bool DlssAllowed(SimulatorSettings s, bool dlssPlatform) => dlssPlatform && IsVulkan(s);
public const int MaxBufferScale = 100;
public static bool DlssActive(SimulatorSettings s, bool dlssPlatform) =>
DlssAllowed(s, dlssPlatform) && IsDlss(s.AntiAliasing);
/// <summary>The frame generation goes with gfx.antialiasing dlss or dlaa, nothing else.</summary>
public static bool FrameGenerationAllowed(SimulatorSettings s, bool dlssPlatform) => DlssActive(s, dlssPlatform);
/// <summary>Reflex (VK_NV_low_latency2) is the Vulkan renderer's only.</summary>
public static bool ReflexAllowed(SimulatorSettings s) => IsVulkan(s);
/// <summary>The frame generation turns Reflex on whatever gfx.reflex says.</summary>
public static bool ReflexForced(SimulatorSettings s, bool dlssPlatform) =>
FrameGenerationAllowed(s, dlssPlatform) && s.FrameGeneration > 1;
/// <summary>Ray traced reflections: the Vulkan renderer on a GPU with ray queries.</summary>
public static bool RayTracingAllowed(SimulatorSettings s) => IsVulkan(s);
/// <summary>The render scale is ignored by DLAA, which always draws at the size of the window.</summary>
public static bool BufferScaleUsed(SimulatorSettings s, bool dlssPlatform) =>
!(DlssActive(s, dlssPlatform) && s.AntiAliasing == AntiAliasingMode.Dlaa);
/// <summary>TAA and DLSS run in the post-processing which gfx.skippipeline leaves out.</summary>
public static bool TemporalWithoutPipeline(SimulatorSettings s) => s.SkipPipeline && IsTemporal(s.AntiAliasing);
/// <summary>With the clustered lights the headlights come from the clusters; dynamiclights only caps the old path.</summary>
public static bool DynamicLightsUsed(SimulatorSettings s) => !s.LightsClustered;
/// <summary>The ambient occlusion goes into the lighting only with GTAO.</summary>
public static bool AoLightingUsed(SimulatorSettings s) => s.AmbientOcclusion == 2;
/// <summary>
/// The AO in the lighting needs the depth of the whole scene drawn before its colour. SSR, contact
/// shadows and gfx.depthprepass.scene draw it anyway; without them it is an extra pass (CPU time on OpenGL).
/// </summary>
public static bool AoLightingAddsDepthPrepass(SimulatorSettings s) =>
AoLightingUsed(s) && s.AoLighting && s.Ssr == 0 && s.ContactShadows == 0 && !s.DepthPrepassScene;
public static bool CabProbeUsed(SimulatorSettings s) => s.CabProbe > 0;
/// <summary>
/// The light bounced around the cab comes from the cab lamp as a light, which needs the clustered lights
/// and gfx.lights.cab; without them the probe gives the reflections only.
/// </summary>
public static bool CabProbeLights(SimulatorSettings s) => CabProbeUsed(s) && s.LightsClustered && s.CabLampLight;
/// <summary>
/// Brings the settings to what the simulator would run with: the Vulkan-only
/// features off on OpenGL, DLSS falling back to TAA, values within the ranges
/// the simulator clamps them to.
/// </summary>
public static void Normalize(SimulatorSettings s, bool dlssPlatform)
/// <summary>Brings the values within the ranges the simulator clamps them to, and the starter's caps.</summary>
public static void Normalize(SimulatorSettings s)
{
if (IsDlss(s.AntiAliasing) && !DlssAllowed(s, dlssPlatform))
s.AntiAliasing = AntiAliasingMode.Taa;
s.FrameGeneration = FrameGenerationAllowed(s, dlssPlatform) ? Clamp(s.FrameGeneration, 1, 4) : 1;
s.Reflex = ReflexAllowed(s) ? Clamp(s.Reflex, 0, 2) : 0;
if (!RayTracingAllowed(s))
s.RayTracing = false;
if (!IsKnownDlssPreset(s.DlssPreset))
s.DlssPreset = "default";
s.MaxTextureSize = PowerOfTwo(s.MaxTextureSize, 64, 8192);
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, 8192);
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, MaxCabTextureSize);
s.ShadowMapResolution = PowerOfTwo(s.ShadowMapResolution, 512, 8192);
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, 200);
s.LightShadows = Clamp(s.LightShadows, 0, 3);
s.ContactShadows = Clamp(s.ContactShadows, 0, 3);
s.AmbientOcclusion = Clamp(s.AmbientOcclusion, 0, 2);
s.AoSlices = Clamp(s.AoSlices, 1, 8);
s.AoSteps = Clamp(s.AoSteps, 1, 16);
s.CabProbe = Clamp(s.CabProbe, 0, 3);
s.CabProbeInterval = Clamp(s.CabProbeInterval, 1, 120);
s.CabProbeBounce = s.CabProbeBounce < 0 ? 0 : (s.CabProbeBounce > 4 ? 4 : s.CabProbeBounce);
s.Ssr = Clamp(s.Ssr, 0, 3);
s.RayTracingRange = Clamp(s.RayTracingRange, 10, 5000);
s.FogQuality = Clamp(s.FogQuality, 1, 4);
s.Clouds = Clamp(s.Clouds, 0, 4);
s.GrassDistance = Clamp(s.GrassDistance, 5, 500);
s.GrassDensity = s.GrassDensity < 0 ? 0 : (s.GrassDensity > 4 ? 4 : s.GrassDensity);
s.PrecipitationParticles = Clamp(s.PrecipitationParticles, 0, 1 << 20);
}
public static readonly string[] DlssPresets = { "default", "j", "k", "l", "m" };
public static bool IsKnownDlssPreset(string? preset)
{
foreach (string known in DlssPresets)
if (string.Equals(known, preset, System.StringComparison.OrdinalIgnoreCase))
return true;
return false;
s.ShadowProjectionRange = s.ShadowProjectionRange > MaxShadowRange ? MaxShadowRange : s.ShadowProjectionRange;
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, MaxBufferScale);
}
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);

View File

@@ -0,0 +1,14 @@
namespace StarterNG.Domain.Settings;
/// <summary>The renderers a gfxrenderer word picks, as application.cpp tells them apart.</summary>
public enum RendererKind { Modern, Legacy }
public static class Renderers
{
/// <summary>"legacy", "simple", "simpleshader" and "off" draw with the legacy renderer, any other word with the full one.</summary>
public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch
{
"legacy" or "simple" or "simpleshader" or "off" => RendererKind.Legacy,
_ => RendererKind.Modern
};
}

View File

@@ -1,132 +0,0 @@
using System;
using System.Collections.Generic;
namespace StarterNG.Domain.Settings;
/// <summary>Why the simulator about to be started would pass a key over.</summary>
public enum IdleReason
{
None,
WindowsBuildOnly,
LegacyRendererOnly,
/// <summary>Read by the full OpenGL renderer alone.</summary>
ModernRendererOnly,
/// <summary>Read by the OpenGL renderers, which the experimental one is not.</summary>
OpenGlRenderersOnly,
NeedsNetworkServer,
/// <summary>The draw range is only stretched by the frame rate regulator, which is off.</summary>
NeedsFrameRateTarget,
/// <summary>fullscreenwindowed takes the monitor's own mode instead.</summary>
MonitorModeInstead,
VulkanOnly
}
/// <summary>What about the simulator to be started decides which keys it heeds.</summary>
/// <param name="WindowsBuild">The executable is a Windows build, under Wine or not.</param>
/// <param name="Renderer">The gfxrenderer word, as <see cref="SimulatorSettings.RenderEngines"/> has it.</param>
/// <param name="NetworkServer">eu07.ini starts a network.server.</param>
/// <param name="TargetFps">targetfps as eu07.ini sets it, or null where it does not.</param>
/// <param name="FpsAverage">fpsaverage, the older regulator's target; 0 for none.</param>
/// <param name="FullscreenWindowed">fullscreenwindowed is on.</param>
public sealed record SimulatorTarget(bool WindowsBuild, string Renderer, bool NetworkServer,
double? TargetFps = null, double FpsAverage = 0,
bool FullscreenWindowed = false);
/// <summary>The renderers a gfxrenderer word picks, as application.cpp tells them apart.</summary>
public enum RendererKind { Modern, Legacy, Experimental }
/// <summary>
/// Where an eu07.ini key takes effect, from the simulator's sources: a key it
/// reads but leaves alone on the platform, render path or setup at hand.
/// </summary>
public static class SettingReach
{
// The keyboard lights, LPT and PoKeys behind feedback live in Console.cpp,
// which only the Windows build compiles; the system console and ANGLE are
// Windows-only in application.cpp.
private static readonly HashSet<string> WindowsBuildOnly = new(StringComparer.OrdinalIgnoreCase)
{
"feedbackmode", "feedbackport", "showsystemconsole", "gfx.angleplatform"
};
// Read by openglrenderer.cpp alone; the modern path forces VBOs on.
private static readonly HashSet<string> LegacyRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"smoothtraction", "gfx.shadows.cab.range", "usevbo"
};
// Read by opengl33renderer.cpp and the shaders it builds (glsl_common.cpp) alone.
private static readonly HashSet<string> ModernRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"gfx.postfx.chromaticaberration.enabled", "gfx.postfx.motionblur.enabled",
"gfx.postfx.motionblur.shutter", "gfx.extraeffects", "gfx.envmap.enabled", "gfx.skippipeline",
"rendercab", "sleeperdistance"
};
// Read by both OpenGL renderers but not by the experimental one, which sets its
// own anisotropy, draws no smoke and has no frame rate regulator.
private static readonly HashSet<string> OpenGlRenderersOnly = new(StringComparer.OrdinalIgnoreCase)
{
"anisotropicfiltering", "multisampling", "dynamiclights", "gfx.smoke", "gfx.smoke.fidelity",
"gfx.reflections.framerate", "gfx.reflections.range_vehicles", "gfx.shadow.angle.min",
"scalespeculars", "gfx.drawrange.factor.max"
};
private static readonly HashSet<string> VulkanRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"gfx.dlss.preset", "gfx.framegeneration", "gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.vulkan.device"
};
// application.cpp: fullscreenwindowed takes its size from the monitor and always
// goes full screen. "width, height" is how the settings screen names that row.
private static readonly HashSet<string> OverriddenByMonitorMode = new(StringComparer.OrdinalIgnoreCase)
{
"width, height", "fullscreen"
};
public static IdleReason Why(string key, SimulatorTarget target)
{
// The starter's own keys mean nothing to any simulator, and need not.
if (key.StartsWith("starter.", StringComparison.OrdinalIgnoreCase))
return IdleReason.None;
if (WindowsBuildOnly.Contains(key) && !target.WindowsBuild)
return IdleReason.WindowsBuildOnly;
if (OverriddenByMonitorMode.Contains(key) && target.FullscreenWindowed)
return IdleReason.MonitorModeInstead;
var renderer = KindOf(target.Renderer);
if (LegacyRendererOnly.Contains(key) && renderer != RendererKind.Legacy)
return IdleReason.LegacyRendererOnly;
if (ModernRendererOnly.Contains(key) && renderer != RendererKind.Modern)
return IdleReason.ModernRendererOnly;
if (OpenGlRenderersOnly.Contains(key) && renderer == RendererKind.Experimental)
return IdleReason.OpenGlRenderersOnly;
if (VulkanRendererOnly.Contains(key) && !IsVulkan(target.Renderer))
return IdleReason.VulkanOnly;
// on_focus_change pauses only a simulator that serves the network.
if (string.Equals(key, "inactivepause", StringComparison.OrdinalIgnoreCase) && !target.NetworkServer)
return IdleReason.NeedsNetworkServer;
if (string.Equals(key, "gfx.drawrange.factor.max", StringComparison.OrdinalIgnoreCase) &&
!DrawRangeRegulated(target))
return IdleReason.NeedsFrameRateTarget;
return IdleReason.None;
}
/// <summary>
/// Whether the renderer moves the draw range with the frame rate - the only use
/// of gfx.drawrange.factor.max: targetfps does it, as the older fpsaverage does.
/// </summary>
private static bool DrawRangeRegulated(SimulatorTarget target) =>
target.FpsAverage != 0 || (target.TargetFps ?? 0) != 0;
/// <summary>"full", its other names and the Vulkan renderer are the modern kind, "experimental" its own; every other word the legacy one.</summary>
public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch
{
"full" or "default" or "opengl" or "gl46" or "vulkan" or "vulkan14" => RendererKind.Modern,
"experimental" => RendererKind.Experimental,
_ => RendererKind.Legacy
};
public static bool IsVulkan(string renderer) => renderer.ToLowerInvariant() is "vulkan" or "vulkan14";
}

View File

@@ -63,6 +63,12 @@ public sealed record SimulatorKey(
public static class SimulatorKeys
{
/// <summary>
/// The keys a player sees in the standard mode, which has what the old starter had. It had
/// none of these: they are all for the advanced mode.
/// </summary>
public static readonly IReadOnlySet<string> Standard = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public const string General = "general";
public const string Graphics = "graphics";
public const string Sound = "sound";
@@ -94,13 +100,12 @@ public static class SimulatorKeys
Toggle("loadinglog", false, General, "IniSectionInterface"),
Toggle("captureonstart", true, General, "IniSectionInterface"),
Toggle("mousecontrol", true, General, "IniSectionInterface"),
Text("fullscreenmonitor", General, "IniSectionInterface"),
Text("screenshotsdir", General, "IniSectionInterface"),
Number("basedrawrange", 2500, Graphics, "IniSectionRanges", 500, 10000, 250, " m"),
Number("heightbase", 1, Graphics, "IniSectionRanges", 0.5, 3, 0.05, "×"),
Number("targetfps", 0, Graphics, "IniSectionRanges", 0, 240, 5, " FPS", zeroIsOff: true),
Number("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 5000, 50, " m", zeroIsOff: true),
Number("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 1000, 50, " m", zeroIsOff: true),
Number("gfx.reflections.range_instances", 750, Graphics, "IniSectionRanges", 0, 3000, 50, " m"),
Number("gfx.reflections.range_vehicles", 250, Graphics, "IniSectionRanges", 0, 2000, 50, " m"),
Toggle("gfx.textures.streaming", false, Graphics, "IniSectionRanges"),

View File

@@ -8,11 +8,8 @@ public enum ConsistReadyOverride { Scenery = 0, AlwaysCold = 1, AlwaysReady = 2
public enum ExeProblem { None, NotFound, NotExecutable, WrongPlatform, NotAProgram }
// gfxrenderer: the OpenGL renderer ("full", read by every build) or the Vulkan 1.4 one.
public enum GraphicsBackend { OpenGL = 0, Vulkan = 1 }
// gfx.antialiasing. Dlss and Dlaa are the Vulkan renderer's only; the simulator falls back to TAA elsewhere.
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8, Taa, Dlss, Dlaa }
// multisampling: 0 off, then 2, 4 and 8 samples.
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8 }
public sealed class SimulatorSettings
{
@@ -34,7 +31,8 @@ public sealed class SimulatorSettings
public bool InvertMouseHorizontal;
public bool InvertMouseVertical;
public bool IgnoreGamepad;
/// <summary>input.gamepad no: the recommended setting, so the starter's default, though the simulator's own is yes.</summary>
public bool IgnoreGamepad = true;
public int FeedbackMode = 1;
public int FeedbackPort = 888;
public bool UartEnabled;
@@ -55,8 +53,6 @@ public sealed class SimulatorSettings
public bool LogMissingVehicleFiles;
public int RenderEngine;
public GraphicsBackend Backend => RenderEngine == VulkanEngine ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL;
public string VulkanDevice = "";
public int Width = 1280;
public int Height = 720;
public int BufferScalePercent = 100;
@@ -64,9 +60,6 @@ public sealed class SimulatorSettings
public int MaxCabTextureSize = 4096;
public double TextureFiltering = 8;
public AntiAliasingMode AntiAliasing = AntiAliasingMode.Msaa4;
public string DlssPreset = "default";
public int FrameGeneration = 1;
public int Reflex;
public int DynamicLights = 7;
public double DrawRangeFactor = 3.0;
public bool VSync;
@@ -77,37 +70,8 @@ public sealed class SimulatorSettings
public bool ExtraEffects = true;
public bool EnvMap = true;
public bool RenderShadows = true;
public bool ShadowSdsm;
public int LightShadows = 2;
public int ContactShadows;
public bool LightsClustered = true;
public int AmbientOcclusion = 2;
public int AoSlices = 3;
public int AoSteps = 4;
public bool AoLighting = true;
public int CabProbe = 2;
public int CabProbeInterval = 4;
public double CabProbeBounce = 1.0;
public bool CabProbeReflections = true;
// Read from eu07.ini only, for the dependencies shown: the starter offers no switch for them.
public bool CabLampLight { get; internal set; } = true;
public bool DepthPrepassScene { get; internal set; }
public int Ssr = 2;
public bool RayTracing;
public int RayTracingRange = 500;
public bool VolumetricFog = true;
public int FogQuality = 2;
public int Clouds = 2;
public bool CloudShadows = true;
public bool Grass = true;
public int GrassDistance = 60;
public double GrassDensity = 1.0;
public int PrecipitationParticles = 65536;
public bool Bloom = true;
public bool AutoExposure = true;
// Only the older simulators read these.
// Only the legacy renderer, or only Windows builds, read these.
public bool UseVbo = true;
public bool RenderAngleVulkan;
public bool UseGLES;
@@ -127,12 +91,28 @@ public sealed class SimulatorSettings
public double FpsLimit = 30;
public double ShadowAngleLimit = 0.2;
public bool FullscreenWindowed;
/// <summary>fullscreenmonitor: the monitor a full screen opens on, as "name:x,y"; empty for the primary one.</summary>
public string FullscreenMonitor = "";
public int SplineFidelity = 1;
public bool FullPhysics = true;
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;
@@ -166,6 +146,18 @@ public sealed class SimulatorSettings
public bool LargeThumbnails;
public bool AutoExpandSceneryTree;
/// <summary>
/// Every setting on show, the ones a player can break the game with too. Off, the standard
/// mode keeps the settings, the consists and the scenario to what a driver needs.
/// </summary>
public bool AdvancedSettings;
/// <summary>
/// The settings were brought into the standard mode once, on the first start of this
/// starter: the advanced ones to their defaults, the sliders into their ranges.
/// </summary>
public bool MovedToStandard;
/// <summary>Warn at start when the processor cannot run the official simulator builds.</summary>
public bool CpuNotice = true;
@@ -198,25 +190,26 @@ public sealed class SimulatorSettings
}
/// <summary>
/// The gfxrenderer words the simulator tells apart (application.cpp): every
/// other word - the "simpleshader" and "off" older starters offered among them -
/// gets the legacy renderer. A simulator with the OpenGL 4.6 and Vulkan 1.4
/// renderers runs everything but "vulkan" as the first, and "vulkan" too when
/// it was built without it or the card cannot run it.
/// The gfxrenderer words the starter offers. "default" is the full renderer, the one to use
/// wherever it runs; the other two draw with the legacy one. The experimental renderer is
/// not offered: the simulator a player has is built without it.
/// </summary>
public static readonly string[] RenderEngines = { "full", "legacy", "simple", "experimental", "vulkan" };
public static readonly string[] RenderEngines = { "default", "legacy", "simple" };
/// <summary>Where "vulkan" stands among <see cref="RenderEngines"/>.</summary>
public const int VulkanEngine = 4;
/// <summary>
/// The words of the file that stay as they are while the choice stands: those application.cpp
/// on master knows, but "experimental". Any other word starts the full renderer with a line in
/// the log, so a save puts "default" in its place.
/// </summary>
public static bool KeptRendererWord(string? word) =>
word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off";
/// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary>
public static int RenderEngineOf(string word) => word.Trim().ToLowerInvariant() switch
{
"full" or "default" or "opengl" or "gl46" => 0,
"legacy" or "simpleshader" or "off" => 1,
"simple" => 2,
"experimental" => 3,
"vulkan" or "vulkan14" => 4,
_ => 1
_ => 0
};
/// <summary>
@@ -237,12 +230,32 @@ public sealed class SimulatorSettings
}
/// <summary>
/// The file's own first mousescale number. The slider takes whole steps: this
/// stands for as long as <see cref="CursorSensitivity"/> is the step nearest it.
/// The first mousescale number of each level of <see cref="CursorSensitivity"/>, 1 to 4, as
/// the old starter wrote them (MaSzyna-EU07/Starter, src/uSettings.pas): low, standard, high
/// and very high, negative with <see cref="InvertMouseHorizontal"/>. Whatever else the file
/// has there goes on the next save.
/// </summary>
internal double MouseScaleXMagnitude { get; set; } = 2;
internal static readonly double[] MouseScales = { 1.0, 1.5, 2.3, 3.2 };
internal double MouseScaleYMagnitude { get; set; } = 0.2;
/// <summary>The first mousescale number <paramref name="level"/> stands for.</summary>
internal static double MouseScaleOf(int level) => MouseScales[Math.Clamp(level, 1, MouseScales.Length) - 1];
/// <summary>
/// The level the old starter showed for a first mousescale number: low below 1.3, high
/// above 1.9, very high above 2.7 and standard between, whatever its sign.
/// </summary>
internal static int MouseLevelOf(double scale)
{
double size = Math.Abs(scale);
return size > 2.7 ? 4 : size > 1.9 ? 3 : size < 1.3 ? 1 : 2;
}
/// <summary>
/// The second mousescale number, as the old starter always wrote it: 0.5, or
/// -0.5 with <see cref="InvertMouseVertical"/>. Whatever else the file has there
/// goes on the next save.
/// </summary>
internal const double MouseScaleY = 0.5;
/// <summary>The numbers of shadowtune the simulator skips, kept as the file has them.</summary>
internal string[] ShadowTuneUnused { get; set; } = { "250", "300" };

View File

@@ -0,0 +1,31 @@
namespace StarterNG.Domain.Settings;
/// <summary>
/// What the sliders offer, in either mode: the old starter's ranges (MaSzyna-EU07/Starter,
/// src/uMain.dfm), the tops of which <see cref="GraphicsRules"/> holds to. A value the file
/// has below these is shown as it is, so opening and saving the settings never moves it.
/// </summary>
public static class SliderRanges
{
/// <summary>maxtexturesize: its list began at 512.</summary>
public const int MinTextureSize = 512;
/// <summary>The map size of shadowtune: its list began at 1024.</summary>
public const int MinShadowMap = 1024;
/// <summary>dynamiclights: 1 to 7.</summary>
public const int MinDynamicLights = 1;
/// <summary>gfx.reflections.framerate, in updates a second.</summary>
public static readonly double[] ReflectionUpdates = { 1, 3, 10, 25, 60 };
/// <summary>gfx.drawrange.factor.max: normal, high and very high.</summary>
public static readonly double[] DrawRangeFactors = { 1, 2, 3 };
/// <summary>gfx.shadows.cab.range, in metres: off, then 10 to 100.</summary>
public static readonly double[] CabShadowRanges = { 0, 10, 20, 30, 50, 100 };
/// <summary>fpslimit: none, or up to 240, where the fastest usual monitors run.</summary>
public static readonly double[] FrameRateLimits =
{ 0, 20, 25, 30, 40, 45, 50, 60, 72, 75, 90, 100, 120, 144, 165, 180, 200, 240 };
}

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

@@ -199,23 +199,8 @@ public sealed class TexRandomizer
VehicleTexture? current)
{
var result = new List<VehicleTexture>();
foreach (var t in _db.Textures)
foreach (var t in ByMini(minis))
{
if (t.Wreck) continue;
if (WithoutArchival && t.ResolvedArchived) continue;
if (_db.IsSetFollower(t)) continue;
string candidateMini = t.ResolvedClass;
if (string.IsNullOrEmpty(candidateMini))
candidateMini = _db.ResolveMiniName(t) ?? "";
if (string.IsNullOrEmpty(candidateMini)) continue;
bool miniOk = minis.Any(m =>
string.Equals(m, candidateMini, StringComparison.OrdinalIgnoreCase) ||
string.Equals(m, t.TextureMini, StringComparison.OrdinalIgnoreCase) ||
string.Equals(m, t.MiniRef, StringComparison.OrdinalIgnoreCase));
if (!miniOk) continue;
if (!string.IsNullOrEmpty(owner) &&
!string.Equals(owner, t.Meta?.Operator, StringComparison.OrdinalIgnoreCase))
continue;
@@ -236,6 +221,49 @@ public sealed class TexRandomizer
return result;
}
// The textures that can be drawn, by every mini name they answer to, in the catalogue's
// order. Made once: a scenery's worth of consists looks them up hundreds of times.
private Dictionary<string, List<(int Order, VehicleTexture Texture)>>? _byMini;
/// <summary>The textures that can be drawn under any of <paramref name="minis"/>, each once, in the catalogue's order.</summary>
private IEnumerable<VehicleTexture> ByMini(IReadOnlyList<string> minis)
{
_byMini ??= IndexByMini();
var found = new List<(int Order, VehicleTexture Texture)>();
foreach (string mini in minis)
if (!string.IsNullOrEmpty(mini) && _byMini.TryGetValue(mini, out var textures))
found.AddRange(textures);
return found.Distinct().OrderBy(entry => entry.Order).Select(entry => entry.Texture);
}
private Dictionary<string, List<(int Order, VehicleTexture Texture)>> IndexByMini()
{
var index = new Dictionary<string, List<(int, VehicleTexture)>>(StringComparer.OrdinalIgnoreCase);
int order = 0;
foreach (var t in _db.Textures)
{
order++;
if (t.Wreck) continue;
if (WithoutArchival && t.ResolvedArchived) continue;
if (_db.IsSetFollower(t)) continue;
string candidateMini = t.ResolvedClass;
if (string.IsNullOrEmpty(candidateMini))
candidateMini = _db.ResolveMiniName(t) ?? "";
if (string.IsNullOrEmpty(candidateMini)) continue;
foreach (string? name in new[] { candidateMini, t.TextureMini, t.MiniRef }
.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (string.IsNullOrEmpty(name)) continue;
if (!index.TryGetValue(name, out var list))
index[name] = list = new List<(int, VehicleTexture)>();
list.Add((order, t));
}
}
return index;
}
public static int? ParseRevisionYear(string? revision)
{
if (string.IsNullOrWhiteSpace(revision)) return null;

View File

@@ -8,6 +8,7 @@ using StarterNG.Classes;
using StarterNG.Domain.Sceneries;
using StarterNG.Domain.Vehicles;
using StarterNG.Application;
using StarterNG.Domain.Settings;
namespace StarterNG.Domain;
@@ -30,10 +31,27 @@ public static class TrainsetDisplay
!string.IsNullOrEmpty(trainset.Description) &&
trainset.Description.TrimStart().StartsWith("-", StringComparison.Ordinal);
/// <summary>Whether a list of the scenery's consists shows it, under the two filters those lists have.</summary>
/// <summary>Whether a list of the scenery's consists shows it, under the filters those lists have.</summary>
public static bool ListedIn(Trainset trainset, bool showAi, bool drivableOnly, Trainset? current) =>
(showAi || !IsAi(trainset)) && (!drivableOnly || ListedAsDrivable(trainset, current));
/// <summary>
/// Whether a list of the scenery's consists shows it: in the advanced mode under the filters
/// the settings hold; in the standard mode, which has no filters, every consist with vehicles
/// on it, and one emptied here, so it can be filled again or saved.
/// </summary>
public static bool ListedIn(Trainset trainset, SimulatorSettings settings, Trainset? current) =>
settings.AdvancedSettings
? ListedIn(trainset, settings.ShowAiVehicles, settings.DrivableOnly, current)
: !IsEmpty(trainset) || SceneryTrainsetText.IsModified(trainset);
/// <summary>
/// Whether the simulator may start with the player in it: in the standard mode not in one
/// the simulator drives itself nor in a decoration, which the scenario keeps as they are.
/// </summary>
public static bool StartableIn(Trainset trainset, SimulatorSettings settings) =>
settings.AdvancedSettings || (!IsAi(trainset) && !trainset.Decor);
/// <summary>The consist's row in those lists: what it is made of, or the track of one with nothing on it.</summary>
public static string ListLabel(Trainset trainset) =>
CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? "");

View File

@@ -0,0 +1,55 @@
using System;
using System.IO;
namespace StarterNG.Infrastructure.Adapters;
/// <summary>
/// Tells when anything in a folder or below it is written, made, removed or renamed, as
/// the system reports it. Only a hint that it is time to look: a save comes as several
/// reports, and on a network drive, under Wine or past the system's limit of watches it
/// may come as none, so whoever listens still looks now and then on its own.
/// </summary>
public sealed class FolderChanges : IDisposable
{
private readonly FileSystemWatcher? _watcher;
/// <summary>Something changed, or the reports were lost and anything may have: on a thread of the pool.</summary>
public event Action? Changed;
/// <param name="folder">Watched with everything below it; a missing one is not watched.</param>
public FolderChanges(string folder)
{
try
{
if (!Directory.Exists(folder))
return;
var watcher = new FileSystemWatcher(folder)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
| NotifyFilters.LastWrite | NotifyFilters.Size,
// Unpacking an update changes hundreds of files at once.
InternalBufferSize = 64 * 1024
};
watcher.Changed += (_, _) => Changed?.Invoke();
watcher.Created += (_, _) => Changed?.Invoke();
watcher.Deleted += (_, _) => Changed?.Invoke();
watcher.Renamed += (_, _) => Changed?.Invoke();
// Too many at once for the buffer: which ones is lost, so all are looked at.
watcher.Error += (_, _) => Changed?.Invoke();
watcher.EnableRaisingEvents = true;
_watcher = watcher;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException
or PlatformNotSupportedException)
{
// Out of watches on Linux, or a drive that gives none: the slow look alone stays.
}
}
/// <summary>Whether the system reports changes here at all.</summary>
public bool Watching => _watcher is not null;
public void Dispose() => _watcher?.Dispose();
}

View File

@@ -56,6 +56,34 @@ public static class LegacyText
private static readonly byte[] Utf8Bom = { 0xEF, 0xBB, 0xBF };
/// <summary>
/// <paramref name="text"/> as the characters that, written in code page 1250 with the rest
/// of the file, give its UTF-8 bytes: for a word the simulator compares with a UTF-8 one
/// byte by byte, as fullscreenmonitor with GLFW's name of the monitor. ASCII stays as it is.
/// </summary>
public static string Utf8As1250(string text) =>
IsAscii(text) ? text : CodePage1250.GetString(Encoding.UTF8.GetBytes(text));
/// <summary>
/// The other way: what a word of a code page 1250 file says when its bytes are UTF-8.
/// One whose bytes are not UTF-8 was written in the code page itself and stays as read.
/// </summary>
public static string Utf8From1250(string text)
{
if (IsAscii(text))
return text;
byte[] bytes = CodePage1250.GetBytes(text);
return Utf8.IsValid(bytes) && CodePage1250.GetString(bytes) == text ? Encoding.UTF8.GetString(bytes) : text;
}
private static bool IsAscii(string text)
{
foreach (char c in text)
if (c > 0x7F)
return false;
return true;
}
private static Encoding Resolve()
{
try

View File

@@ -1,188 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>A screen, and the fastest it refreshes.</summary>
/// <param name="Name">The connector on Linux (eDP-1, HDMI-A-1); empty for the primary screen on Windows.</param>
public sealed record Display(string Name, int RefreshRate);
/// <summary>
/// The screens attached, for a frame rate limit to match: on Linux from the EDID
/// each connected connector of /sys/class/drm passes on - the most the panel can
/// do, which the desktop may not be using - and on Windows the primary screen's
/// current mode.
/// </summary>
public sealed class Displays
{
private const string DrmClass = "/sys/class/drm";
private static readonly Regex Connector = new(@"^card\d+-(.+)$", RegexOptions.CultureInvariant);
private readonly IFileSystem _files;
private readonly IEnvironment _environment;
public Displays(IFileSystem files, IEnvironment environment)
{
_files = files;
_environment = environment;
}
/// <summary>Every screen whose refresh rate could be read; empty where none could.</summary>
public IReadOnlyList<Display> List()
{
try
{
if (_environment.IsLinux)
return FromDrm();
if (_environment.IsWindows && OperatingSystem.IsWindows())
return PrimaryOnWindows() is { } rate ? new[] { new Display(string.Empty, rate) } : Array.Empty<Display>();
}
catch (Exception)
{
// A screen we cannot read leaves the limit to the player, as before.
}
return Array.Empty<Display>();
}
private IReadOnlyList<Display> FromDrm()
{
var displays = new List<Display>();
foreach (string directory in _files.GetDirectories(DrmClass))
{
var match = Connector.Match(Path.GetFileName(directory));
if (!match.Success || match.Groups[1].Value.StartsWith("Writeback", StringComparison.Ordinal))
continue;
try
{
string status = Path.Combine(directory, "status");
if (!_files.FileExists(status) || _files.ReadAllText(status).Trim() != "connected")
continue;
int rate = Edid.HighestRefreshRate(_files.ReadAllBytes(Path.Combine(directory, "edid")));
if (rate > 0)
displays.Add(new Display(match.Groups[1].Value, rate));
}
catch (Exception)
{
// One connector we cannot read says nothing of the others.
}
}
return displays;
}
// DEVMODEW: dmSize at 68, dmDisplayFrequency at 184, 220 bytes with no driver data.
private const int DevModeSize = 220;
private const int DevModeSizeOffset = 68;
private const int DisplayFrequencyOffset = 184;
private const int CurrentSettings = -1;
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplaySettingsW(IntPtr deviceName, int modeNum, IntPtr devMode);
private static int? PrimaryOnWindows()
{
IntPtr mode = Marshal.AllocHGlobal(DevModeSize);
try
{
for (int i = 0; i < DevModeSize; i++)
Marshal.WriteByte(mode, i, 0);
Marshal.WriteInt16(mode, DevModeSizeOffset, DevModeSize);
if (EnumDisplaySettingsW(IntPtr.Zero, CurrentSettings, mode) == 0)
return null;
int rate = Marshal.ReadInt32(mode, DisplayFrequencyOffset);
// 0 and 1 stand for the hardware's default rate.
return rate > 1 ? rate : null;
}
finally
{
Marshal.FreeHGlobal(mode);
}
}
}
/// <summary>The timings an EDID lists, as far as a refresh rate goes.</summary>
public static class Edid
{
/// <summary>The fastest refresh rate among the detailed timings, rounded; 0 for none.</summary>
public static int HighestRefreshRate(byte[] edid)
{
if (edid.Length < 128)
return 0;
// The base block's four descriptors.
double best = 0;
for (int at = 54; at + 18 <= 126; at += 18)
best = Math.Max(best, DetailedTiming(edid, at));
for (int block = 128; block + 128 <= edid.Length; block += 128)
{
switch (edid[block])
{
// CTA-861: detailed timings from the offset in its third byte on.
case 0x02 when edid[block + 2] >= 4:
for (int at = block + edid[block + 2]; at + 18 <= block + 127; at += 18)
best = Math.Max(best, DetailedTiming(edid, at));
break;
// DisplayID, where a panel faster than 60 Hz often keeps its only fast mode.
case 0x70:
best = Math.Max(best, DisplayId(edid, block));
break;
}
}
return (int)Math.Round(best);
}
// An 18-byte detailed timing; a pixel clock of zero marks some other descriptor.
private static double DetailedTiming(byte[] e, int at)
{
int clock = e[at] | e[at + 1] << 8;
if (clock == 0)
return 0;
int hActive = e[at + 2] | (e[at + 4] & 0xF0) << 4, hBlank = e[at + 3] | (e[at + 4] & 0x0F) << 8;
int vActive = e[at + 5] | (e[at + 7] & 0xF0) << 4, vBlank = e[at + 6] | (e[at + 7] & 0x0F) << 8;
return Rate(clock * 10_000.0, hActive + hBlank, vActive + vBlank);
}
// Data blocks from the sixth byte on; type I timings (DisplayID 1.3) count the
// pixel clock in 10 kHz, type VII (2.0) in kHz, and both store each size less one.
private static double DisplayId(byte[] e, int block)
{
double best = 0;
int end = Math.Min(block + 5 + e[block + 2], block + 127);
for (int at = block + 5; at + 3 <= end;)
{
int tag = e[at], length = e[at + 2];
if (tag == 0 && length == 0)
break;
int payload = at + 3;
if (tag is 0x03 or 0x22)
{
for (int t = payload; t + 20 <= Math.Min(payload + length, end); t += 20)
{
double clock = (e[t] | e[t + 1] << 8 | e[t + 2] << 16) + 1;
clock *= tag == 0x03 ? 10_000 : 1_000;
int hTotal = (e[t + 4] | e[t + 5] << 8) + 1 + (e[t + 6] | e[t + 7] << 8) + 1;
int vTotal = (e[t + 12] | e[t + 13] << 8) + 1 + (e[t + 14] | e[t + 15] << 8) + 1;
best = Math.Max(best, Rate(clock, hTotal, vTotal));
}
}
at = payload + length;
}
return best;
}
private static double Rate(double pixelClock, int hTotal, int vTotal) =>
hTotal > 0 && vTotal > 0 ? pixelClock / ((double)hTotal * vTotal) : 0;
}

View File

@@ -0,0 +1,96 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using StarterNG.Application;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure;
/// <summary>
/// Looks at a folder's files for a window, one look at a time on the UI thread: when the system
/// reports a change, once the burst a save makes has passed; when the window comes back to the
/// front; when asked; and now and then anyway, for the drives and systems where the reports do
/// not come - often where none come at all. From the window's opening to its closing.
/// </summary>
public sealed class FolderLooks
{
/// <summary>How long the reports have to stop for: a save comes as several of them.</summary>
public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400);
/// <summary>How often it looks anyway where the system reports the changes.</summary>
public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30);
/// <summary>How often it looks where the system reports nothing.</summary>
public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2);
private readonly Func<string> _folder;
private readonly OneAtATime _look;
private readonly TimeProvider _time;
private readonly object _gate = new();
private bool _closed;
private ITimer? _quiet;
private ITimer? _often;
private FolderChanges? _changes;
/// <param name="window">Looked for from its opening to its closing.</param>
/// <param name="folder">The folder, as it is when the window opens.</param>
/// <param name="look">The look itself; it knows when it is no time to look.</param>
/// <param name="time">The clock of the timers, the system's when not given.</param>
public FolderLooks(Window window, Func<string> folder, Func<Task> look, TimeProvider? time = null)
{
_folder = folder;
_look = new OneAtATime(look);
_time = time ?? TimeProvider.System;
window.Opened += (_, _) => Watch();
window.Activated += async (_, _) => await LookAsync();
window.Closed += (_, _) => Close();
}
/// <summary>Whether the system reports the folder's changes; not before the window opens.</summary>
public bool Watching => _changes?.Watching == true;
/// <summary>Looks now, or once more after the look that runs.</summary>
public Task LookAsync() => _look.RunAsync();
private void Watch()
{
var changes = new FolderChanges(_folder());
var often = changes.Watching ? Watched : Unwatched;
lock (_gate)
{
_changes = changes;
_quiet = _time.CreateTimer(_ => LookLater(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_often = _time.CreateTimer(_ => LookLater(), null, often, often);
}
changes.Changed += PutOff;
}
// Each report puts the look off again, so a save of many files is one look after it. The
// reports come on threads of the pool, and may come still as the window closes.
private void PutOff()
{
lock (_gate)
{
if (!_closed)
_quiet?.Change(Quiet, Timeout.InfiniteTimeSpan);
}
}
// The timers tick on threads of the pool; the look belongs on the UI thread.
private void LookLater() => Dispatcher.UIThread.Post(() => _ = LookAsync());
private void Close()
{
FolderChanges? changes;
lock (_gate)
{
_closed = true;
_quiet?.Dispose();
_often?.Dispose();
changes = _changes;
}
changes?.Dispose();
}
}

View File

@@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>A monitor as the simulator names it for fullscreenmonitor.</summary>
/// <param name="Id">"name:x,y" - GLFW's name with spaces as underscores, and the monitor's place on the desktop (application.cpp).</param>
/// <param name="RefreshRate">The current mode's rate in Hz, which a full screen of the simulator keeps; 0 where unknown.</param>
public sealed record DisplayMonitor(string Id, string Name, int Width, int Height, bool Primary, int RefreshRate = 0);
/// <summary>
/// The monitors the simulator can start on, named as GLFW names them: on Windows the
/// monitor's device string under its adapter, on Linux the RandR output that xrandr lists.
/// </summary>
public static class Monitors
{
public static IReadOnlyList<DisplayMonitor> List(IEnvironment environment)
{
try
{
if (environment.IsWindows && OperatingSystem.IsWindows())
return OnWindows();
if (environment.IsLinux)
return FromXrandr();
}
catch (Exception)
{
// Without the list the player still has the primary monitor.
}
return Array.Empty<DisplayMonitor>();
}
/// <summary>
/// The size of the monitor a full screen of the simulator goes to (application.cpp): the one
/// <paramref name="id"/> names, or the primary one when it names none or one not connected.
/// Null where neither is among <paramref name="monitors"/>.
/// </summary>
public static (int Width, int Height)? SizeOf(IReadOnlyList<DisplayMonitor> monitors, string id)
{
DisplayMonitor? primary = null;
foreach (var m in monitors)
{
if (id.Length > 0 && m.Id == id)
return (m.Width, m.Height);
if (m.Primary)
primary ??= m;
}
return primary is null ? null : (primary.Width, primary.Height);
}
/// <summary>The id GLFW gives a monitor: its name with spaces as underscores, then where it starts.</summary>
public static string IdOf(string name, int x, int y) => $"{name.Replace(' ', '_')}:{x},{y}";
// ── Windows: as win32_monitor.c of GLFW walks them ───────────────────────
// DISPLAY_DEVICEW: cb, DeviceName[32], DeviceString[128], StateFlags, DeviceID[128], DeviceKey[128].
private const int DisplayDeviceSize = 840;
private const int DeviceNameOffset = 4;
private const int DeviceStringOffset = 68;
private const int StateFlagsOffset = 324;
private const int Active = 0x1;
private const int PrimaryDevice = 0x4;
// DEVMODEW: dmSize at 68, dmPosition at 76, dmPelsWidth and dmPelsHeight at 172 and 176,
// dmDisplayFrequency at 184.
private const int DevModeSize = 220;
private const int DevModeSizeOffset = 68;
private const int PositionOffset = 76;
private const int WidthOffset = 172;
private const int HeightOffset = 176;
private const int DisplayFrequencyOffset = 184;
private const int CurrentSettings = -1;
private const int RotatedMode = 0x4;
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplayDevicesW(IntPtr device, int index, IntPtr displayDevice, int flags);
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplaySettingsExW(IntPtr deviceName, int modeNum, IntPtr devMode, int flags);
private static IReadOnlyList<DisplayMonitor> OnWindows()
{
var monitors = new List<DisplayMonitor>();
IntPtr adapter = Blank(DisplayDeviceSize, 0, DisplayDeviceSize);
IntPtr display = Blank(DisplayDeviceSize, 0, DisplayDeviceSize);
IntPtr mode = Blank(DevModeSize, DevModeSizeOffset, DevModeSize);
try
{
for (int a = 0; EnumDisplayDevicesW(IntPtr.Zero, a, adapter, 0) != 0; a++)
{
if ((Marshal.ReadInt32(adapter, StateFlagsOffset) & Active) == 0)
continue;
IntPtr adapterName = adapter + DeviceNameOffset;
Clear(mode, DevModeSize, DevModeSizeOffset);
if (EnumDisplaySettingsExW(adapterName, CurrentSettings, mode, RotatedMode) == 0)
continue;
int x = Marshal.ReadInt32(mode, PositionOffset), y = Marshal.ReadInt32(mode, PositionOffset + 4);
int width = Marshal.ReadInt32(mode, WidthOffset), height = Marshal.ReadInt32(mode, HeightOffset);
bool primary = (Marshal.ReadInt32(adapter, StateFlagsOffset) & PrimaryDevice) != 0;
// 0 and 1 stand for the hardware's default rate.
int rate = Marshal.ReadInt32(mode, DisplayFrequencyOffset);
// A monitor under the adapter gives its own name; with none, the adapter's stands.
string name = Marshal.PtrToStringUni(adapter + DeviceStringOffset) ?? string.Empty;
Clear(display, DisplayDeviceSize, 0);
Marshal.WriteInt32(display, 0, DisplayDeviceSize);
for (int d = 0; EnumDisplayDevicesW(adapterName, d, display, 0) != 0; d++)
{
if ((Marshal.ReadInt32(display, StateFlagsOffset) & Active) == 0)
continue;
name = Marshal.PtrToStringUni(display + DeviceStringOffset) ?? name;
break;
}
monitors.Add(new DisplayMonitor(IdOf(name, x, y), name, width, height, primary, rate > 1 ? rate : 0));
Clear(adapter, DisplayDeviceSize, 0);
Marshal.WriteInt32(adapter, 0, DisplayDeviceSize);
}
}
finally
{
Marshal.FreeHGlobal(adapter);
Marshal.FreeHGlobal(display);
Marshal.FreeHGlobal(mode);
}
return monitors;
}
private static IntPtr Blank(int size, int sizeOffset, int sizeValue)
{
IntPtr block = Marshal.AllocHGlobal(size);
Clear(block, size, sizeOffset);
if (sizeOffset == 0)
Marshal.WriteInt32(block, 0, sizeValue);
else
Marshal.WriteInt16(block, sizeOffset, (short)sizeValue);
return block;
}
private static void Clear(IntPtr block, int size, int sizeOffset)
{
for (int i = 0; i < size; i++)
Marshal.WriteByte(block, i, 0);
if (sizeOffset > 0)
Marshal.WriteInt16(block, sizeOffset, (short)size);
}
// ── Linux: the connected RandR outputs, as x11_monitor.c of GLFW names them ──
// A line of xrandr is short; one that takes longer than this to match is no report of monitors.
private static readonly TimeSpan MatchTimeout = TimeSpan.FromSeconds(1);
private static readonly Regex Output = new(
@"^(\S+) connected (primary )?(\d+)x(\d+)\+(\d+)\+(\d+)", RegexOptions.CultureInvariant, MatchTimeout);
// A mode line under an output: the rate in use is the one marked with a star.
private static readonly Regex CurrentRate = new(@"^\s+\S+.*?\s(\d+(?:\.\d+)?)\*", RegexOptions.CultureInvariant, MatchTimeout);
// Where distributions put xrandr: run from there, not from whatever PATH finds first.
private static readonly string[] XrandrPlaces = { "/usr/bin/xrandr", "/usr/local/bin/xrandr", "/bin/xrandr" };
private static IReadOnlyList<DisplayMonitor> FromXrandr()
{
string? xrandr = Array.Find(XrandrPlaces, System.IO.File.Exists);
if (xrandr is null)
return Array.Empty<DisplayMonitor>();
using var process = Process.Start(new ProcessStartInfo(xrandr, "--query")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
});
if (process is null)
return Array.Empty<DisplayMonitor>();
string text = process.StandardOutput.ReadToEnd();
process.WaitForExit(2000);
return Parse(text);
}
/// <summary>The monitors of xrandr's report, each with the rate its mode in use runs at.</summary>
public static IReadOnlyList<DisplayMonitor> Parse(string xrandr)
{
var monitors = new List<DisplayMonitor>();
bool underConnected = false;
foreach (string line in xrandr.Split('\n'))
{
var m = Output.Match(line);
if (m.Success)
{
string name = m.Groups[1].Value;
int width = int.Parse(m.Groups[3].Value), height = int.Parse(m.Groups[4].Value);
int x = int.Parse(m.Groups[5].Value), y = int.Parse(m.Groups[6].Value);
monitors.Add(new DisplayMonitor(IdOf(name, x, y), name, width, height, m.Groups[2].Success));
underConnected = true;
continue;
}
if (line.Length > 0 && !char.IsWhiteSpace(line[0]))
{
// Another output, connected without a place on the desktop or not at all.
underConnected = false;
continue;
}
var rate = CurrentRate.Match(line);
if (underConnected && rate.Success && monitors[^1].RefreshRate == 0)
monitors[^1] = monitors[^1] with
{
RefreshRate = (int)Math.Round(double.Parse(rate.Groups[1].Value, CultureInfo.InvariantCulture))
};
}
return monitors;
}
}

View File

@@ -0,0 +1,474 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
using StarterNG.Domain;
using StarterNG.Domain.Sceneries;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure.Sceneries;
/// <summary>
/// The sceneries' binary terrain files (.sbt): the simulator writes one beside a
/// scenery on its first load and from then on takes the terrain from it, passing
/// the scenery's terrain includes (<c>*_ter.scm</c>) over, and the triangles and
/// lines of its other files with them. It never asks whether the text changed
/// since, so a file made by an older simulator, or before the scenery was updated,
/// keeps showing what was there then.
/// <para>
/// A file goes only when the text of every scenery reading it still holds what it
/// was made of: some sceneries come with the .sbt in place of their terrain
/// includes, and without it they would have no terrain at all.
/// </para>
/// </summary>
public sealed class BinaryTerrainFiles
{
/// <summary>
/// Raised by a release that wants the .sbt files made anew: each installation is
/// cleared once for each value, on the first start of a starter carrying it.
/// Zero clears nothing.
/// </summary>
public const int CleanupGeneration = 1;
private const string Extension = ".sbt";
// The only words that tell what comes after them; "endterrain" is found by the second.
private static readonly SearchValues<string> Keywords =
SearchValues.Create(["include", "terrain"], StringComparison.OrdinalIgnoreCase);
private readonly IFileSystem _files;
private readonly IGamePaths _paths;
private readonly IDiagnosticsLog _log;
private readonly string _recordPath;
/// <param name="recordPath">Where the cleanups done are noted, for each installation.</param>
public BinaryTerrainFiles(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, string recordPath)
{
_files = files;
_paths = paths;
_log = log;
_recordPath = recordPath;
}
/// <summary>The scenery's own .sbt as it is on disk, whatever the case of its letters; null when it has none.</summary>
public string? Of(string sceneryPath)
{
string? file = new CaseInsensitivePaths(_files)
.Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sceneryPath) + Extension);
return file is null ? null : Path.Combine(_paths.Scenery, file);
}
/// <summary>
/// What the simulator would miss to make the scenery's .sbt again - the first
/// file with geometry its text names and the installation lacks, or the terrain
/// directive that brings terrain from elsewhere; null when the text holds it all.
/// Another scenery reading the same .sbt counts too: what that one lacks comes
/// with its name.
/// </summary>
public string? MissingOriginal(string sceneryPath)
{
string name = Path.GetFileName(sceneryPath);
try
{
var texts = new Texts(this);
return texts.Resolve(name) is null
? name
: Unmakeable(Path.GetFileNameWithoutExtension(name) + Extension, texts);
}
catch (Exception ex)
{
_log.Log($"sbt/{name}", ex);
return name;
}
}
/// <summary>
/// What keeps an .sbt of the scenery folder from being made again as it is, for
/// every scenery reading it: the one it is named after, which is where the
/// simulator writes it, the same one with the <c>$</c> a scenery editor puts
/// ahead of the name, which the simulator drops, and any other naming it in a
/// terrain directive. Null when all of them can do without it.
/// </summary>
private string? Unmakeable(string sbt, Texts texts)
{
string stem = Path.GetFileNameWithoutExtension(sbt);
var sceneries = texts.Sceneries();
// The scenery named as the file goes first: what it lacks is told without its name.
var owners = sceneries.Where(scenery => SameName(Stem(scenery), stem)).ToList();
owners.AddRange(sceneries.Where(scenery => !SameName(Stem(scenery), stem)
&& SameName(Stem(scenery).TrimStart('$'), stem)));
if (owners.Count == 0)
return stem + ".scn";
foreach (string owner in owners)
{
var text = texts.Of(owner);
string? missing = text.Missing
?? (text.BinaryTerrain.Count > 0 ? "terrain " + text.BinaryTerrain[0] : null);
if (missing is not null)
return SameName(Stem(owner), stem) ? missing : $"{missing} ({owner})";
}
// A scenery naming the file in a terrain directive takes its geometry from it. With the
// file gone the simulator reads that scenery's own text, which then has to hold it all.
foreach (string other in sceneries.Except(owners))
{
var text = texts.Of(other);
if (text.Missing is { } missing && text.BinaryTerrain.Any(named => Names(named, stem)))
return $"{missing} ({other})";
}
return null;
}
private static string Stem(string file) => Path.GetFileNameWithoutExtension(file);
private static bool SameName(string one, string other) =>
one.Equals(other, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether a terrain directive's word names the .sbt of the scenery folder with this
/// name, the way the simulator reads it: the <c>$</c> ahead dropped, the file looked
/// for under the scenery folder.
/// </summary>
private static bool Names(string word, string stem)
{
string name = word.Replace('\\', '/').TrimStart('$').TrimStart('/');
return !name.Contains('/') && SameName(Stem(name), stem);
}
/// <summary>
/// The scenery files read for one question, each of them once however many
/// sceneries include it: most of an installation's sceneries share their files.
/// </summary>
private sealed class Texts
{
private readonly BinaryTerrainFiles _owner;
private readonly CaseInsensitivePaths _names;
private readonly Dictionary<string, string?> _resolved = new(StringComparer.Ordinal);
private readonly Dictionary<string, FileText> _files;
private readonly Dictionary<string, SceneryText> _texts;
private List<string>? _sceneries;
public Texts(BinaryTerrainFiles owner)
{
_owner = owner;
_names = new CaseInsensitivePaths(owner._files, keepListings: true);
var comparer = owner._files.IgnoresCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
_files = new Dictionary<string, FileText>(comparer);
_texts = new Dictionary<string, SceneryText>(comparer);
}
/// <summary>The file named so under the scenery folder as it is on disk; null when there is none.</summary>
public string? Resolve(string name)
{
if (!_resolved.TryGetValue(name, out string? found))
_resolved[name] = found = _names.Resolve(_owner._paths.Scenery, name);
return found;
}
/// <summary>The sceneries of the installation, by their file names.</summary>
public IReadOnlyList<string> Sceneries() =>
_sceneries ??= _owner._files.GetFiles(_owner._paths.Scenery)
.Where(file => Path.GetExtension(file).Equals(".scn", StringComparison.OrdinalIgnoreCase))
.Select(file => Path.GetFileName(file))
.OrderBy(file => file, StringComparer.Ordinal)
.ToList();
/// <summary>The whole text of a scenery, the files it includes read in turn.</summary>
public SceneryText Of(string scenery)
{
if (_texts.TryGetValue(scenery, out var known))
return known;
string? missing = null;
var binaryTerrain = new List<string>();
try
{
var seen = new HashSet<string>(_files.Comparer);
var pending = new Stack<string>();
pending.Push(scenery);
while (pending.Count > 0)
{
string file = pending.Pop();
if (!seen.Add(file))
continue;
if (!_files.TryGetValue(file, out var text))
_files[file] = text = _owner.Scan(file, this);
missing ??= text.Missing;
binaryTerrain.AddRange(text.BinaryTerrain);
foreach (string include in text.Includes)
pending.Push(include);
}
}
catch (Exception ex)
{
// Not read to its end, nothing tells what it would take to make again.
_owner._log.Log($"sbt/{scenery}", ex);
missing ??= scenery;
}
return _texts[scenery] = new SceneryText(missing, binaryTerrain);
}
}
/// <param name="Missing">The first file with geometry named there that the installation lacks.</param>
/// <param name="Includes">The files it includes that are to be read in turn.</param>
/// <param name="BinaryTerrain">The .sbt files its terrain directives name.</param>
private sealed record FileText(string? Missing, IReadOnlyList<string> Includes, IReadOnlyList<string> BinaryTerrain);
/// <param name="Missing">The first file with geometry its text names that the installation lacks.</param>
/// <param name="BinaryTerrain">The .sbt files its terrain directives name.</param>
private sealed record SceneryText(string? Missing, IReadOnlyList<string> BinaryTerrain);
// A terrain file larger than this is geometry and is left unopened - they are the largest
// files of all. A smaller one may be a list of the files that hold it.
private const long LargestTerrainFileRead = 1024 * 1024;
/// <summary>
/// Reads one file of the scenery for the files it names. With an .sbt there the
/// simulator passes over every triangle and line of the text, in any file, so
/// each scenery file included has to be there for the .sbt to be made again:
/// the terrain ones (<c>*_ter.scm</c>) and any other .scm or .scn. The node
/// templates (.inc) do not count: a scenery naming one that is not there is
/// common, and none comes with an .sbt in its place.
/// </summary>
private FileText Scan(string file, Texts texts)
{
string text = LegacyText.Decode(_files.ReadAllBytes(Path.Combine(_paths.Scenery, file)));
string code = SceneryCode.Mask(text, out _);
string? missing = null;
var includes = new List<string>();
var binaryTerrain = new List<string>();
bool includeNext = false;
bool terrainDirective = false;
int at = 0;
while (true)
{
if (!includeNext && !terrainDirective)
{
// Nothing is asked of the words up to the next one that may be a keyword,
// and a scenery file is mostly numbers.
int hit = code.AsSpan(at).IndexOfAny(Keywords);
if (hit < 0)
break;
for (at += hit; at > 0 && !Separates(code[at - 1]); at--) { }
}
if (!NextWord(code, ref at, out var token))
break;
if (includeNext)
{
includeNext = false;
string name = token.ToString();
bool terrain = SimulatorNames.Lower(name).Contains("_ter.scm");
string? found = texts.Resolve(name);
if (found is null)
{
if (terrain || IsSceneryFile(name))
missing ??= name;
}
else if (!terrain
|| _files.GetFileSize(Path.Combine(_paths.Scenery, found)) <= LargestTerrainFileRead)
includes.Add(found);
}
// An include is one wherever it stands, and a word that only reads as the start of
// a terrain directive - the name of a node, of a texture - must not hide those after it.
else if (token.Equals("include", StringComparison.OrdinalIgnoreCase))
includeNext = true;
else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase))
terrainDirective = true;
else if (token.Equals("endterrain", StringComparison.OrdinalIgnoreCase))
terrainDirective = false;
else if (terrainDirective)
{
var extension = Path.GetExtension(token);
if (extension.Equals(Extension, StringComparison.OrdinalIgnoreCase))
binaryTerrain.Add(token.ToString());
else if (extension.Equals(".txtf", StringComparison.OrdinalIgnoreCase)
|| extension.Equals(".btf", StringComparison.OrdinalIgnoreCase))
missing ??= TerrainFileMissing(token.ToString(), texts);
}
}
return new FileText(missing, includes, binaryTerrain);
}
// The simulator splits its text into words at spaces, tabs, line ends and semicolons.
private static bool Separates(char c) => c == ';' || char.IsWhiteSpace(c);
private static bool NextWord(string code, ref int at, out ReadOnlySpan<char> word)
{
while (at < code.Length && Separates(code[at]))
at++;
int start = at;
while (at < code.Length && !Separates(code[at]))
at++;
word = code.AsSpan(start, at - start);
return at > start;
}
private static bool IsSceneryFile(string name)
{
string extension = Path.GetExtension(name);
return extension.Equals(".scm", StringComparison.OrdinalIgnoreCase)
|| extension.Equals(".scn", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// A terrain file (.txtf) named by a terrain directive has its geometry in itself
/// or in its binary copy (.btf) beside it: with either one there, the scenery's
/// .sbt only keeps that terrain from being used, and the simulator asks for it
/// to go. An .sbt named there is another matter: it holds the geometry of the
/// whole scenery and nothing makes it again, so the scenery's own goes only
/// without one.
/// </summary>
private static string? TerrainFileMissing(string token, Texts texts)
{
string stem = token[..^Path.GetExtension(token).Length];
return texts.Resolve(stem + ".txtf") is null && texts.Resolve(stem + ".btf") is null
? stem + ".txtf"
: null;
}
/// <summary>Removes the scenery's .sbt; false when it has none or it could not go.</summary>
public bool Delete(string sceneryPath)
{
if (Of(sceneryPath) is not { } file)
return false;
try
{
_files.DeleteFile(file);
_log.Log($"{file} removed, the simulator makes it again on the next load of the scenery");
return true;
}
catch (Exception ex)
{
_log.Log($"sbt/{Path.GetFileName(file)}", ex);
return false;
}
}
/// <summary>
/// Clears the .sbt files the simulator can make again, once for each
/// <paramref name="generation"/> on this installation; null when it was done
/// already. A file that could not go leaves the cleanup to the next start.
/// </summary>
public BinaryTerrainCleanup? CleanUpOnce(int generation = CleanupGeneration)
{
if (generation <= 0 || !_files.DirectoryExists(_paths.Scenery))
return null;
var record = ReadRecord();
string installation = Installation();
if (record.TryGetValue(installation, out int done) && done >= generation)
return null;
var deleted = new List<string>();
var kept = new List<(string File, string Reason)>();
var failed = new List<string>();
var texts = new Texts(this);
foreach (string sbt in _files.GetFiles(_paths.Scenery)
.Where(f => Path.GetExtension(f).Equals(Extension, StringComparison.OrdinalIgnoreCase)))
{
string name = Path.GetFileName(sbt);
string? missing;
try
{
missing = Unmakeable(name, texts);
}
catch (Exception ex)
{
_log.Log($"sbt/{name}", ex);
missing = Path.GetFileNameWithoutExtension(name) + ".scn";
}
if (missing is not null)
{
kept.Add((name, missing));
_log.Log($"{name} kept: the scenery cannot be made without it, {missing} is missing");
continue;
}
try
{
_files.DeleteFile(sbt);
deleted.Add(name);
}
catch (Exception ex)
{
failed.Add(name);
_log.Log($"sbt/{name}", ex);
}
}
if (deleted.Count > 0)
_log.Log($"Binary terrain files removed, the simulator makes them again: {string.Join(", ", deleted)}");
if (failed.Count == 0)
{
record[installation] = generation;
WriteRecord(record);
}
return new BinaryTerrainCleanup(deleted, kept, failed);
}
private string Installation() =>
Path.TrimEndingDirectorySeparator(Path.GetFullPath(_paths.Root));
private Dictionary<string, int> ReadRecord()
{
var record = new Dictionary<string, int>(
_files.IgnoresCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
try
{
if (!_files.FileExists(_recordPath))
return record;
foreach (string line in _files.ReadAllLines(_recordPath))
{
int tab = line.IndexOf('\t');
if (tab > 0 && int.TryParse(line[..tab], out int generation))
record[line[(tab + 1)..]] = generation;
}
}
catch (Exception ex)
{
_log.Log("sbt cleanup record", ex);
}
return record;
}
private void WriteRecord(Dictionary<string, int> record)
{
try
{
if (Path.GetDirectoryName(_recordPath) is { Length: > 0 } folder)
_files.CreateDirectory(folder);
_files.WriteAllTextAtomic(_recordPath,
string.Concat(record.Select(entry => $"{entry.Value}\t{entry.Key}\n")));
}
catch (Exception ex)
{
_log.Log("sbt cleanup record", ex);
}
}
}
/// <param name="Deleted">The files removed.</param>
/// <param name="Kept">The files left, as nothing could make them again, each with what is missing.</param>
/// <param name="Failed">The files that could not be removed.</param>
public sealed record BinaryTerrainCleanup(
IReadOnlyList<string> Deleted,
IReadOnlyList<(string File, string Reason)> Kept,
IReadOnlyList<string> Failed);

View File

@@ -24,7 +24,12 @@ public sealed class SceneryParser
/// 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, bool>? opensInclude = null)
/// <param name="loadsVehicle">
/// Whether the simulator finds a vehicle's .fiz, by its folder and .mmd name as
/// written; null leaves vehicles unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null,
Func<string, string, bool>? loadsVehicle = null)
{
string original = content;
@@ -38,7 +43,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), opensInclude);
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude, loadsVehicle);
var faults = syntax.Faults.ToList();
var inlined = SceneryIncludes.Ranges(content);

View File

@@ -79,7 +79,12 @@ 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");
// Watched with the text: made by the simulator on a load, or removed, it changes the scenery too.
string sbtName = Path.GetFileNameWithoutExtension(path) + ".sbt";
string? sbt = ResolveInclude(sbtName);
bool binaryTerrain = sbt is not null;
string sbtPath = Path.Combine(_paths.Scenery, sbt ?? sbtName);
sources[sbtPath] = FileStamp.Of(_files, sbtPath);
bool OpensInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));
@@ -98,7 +103,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, OpensInclude);
var scenery = _parser.Parse(path, text, OpensInclude, LoadsVehicle);
scenery.HasCompanionTimetable = binaryTerrain;
scenery.Sources = sources;
scenery.TextEncoding = ownEncoding;
@@ -119,6 +124,15 @@ public sealed class SceneryRepository : ISceneryRepository
/// </summary>
private bool Opens(string name) => ResolveInclude(name) is not null;
/// <summary>
/// Whether the simulator finds a vehicle's definition - its .fiz, named after its
/// .mmd, in its folder under dynamic - whatever the case of the letters. Without
/// it the simulator leaves the vehicle out; a folder there all the same, empty,
/// makes no difference.
/// </summary>
private bool LoadsVehicle(string folder, string mmd) =>
_names.Resolve(_paths.Dynamic, $"{folder}/{mmd}.fiz") is not null;
/// <summary>
/// An include's file as it is named on disk, from the scenery folder, whatever
/// the case of its letters - as Windows, or Wine, finds it: whose consists the

View File

@@ -302,33 +302,6 @@ public sealed class ExecutableLocator
return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage";
}
/// <summary>Whether the DLSS and frame generation libraries lie next to the simulator: without them it cannot use either.</summary>
public (bool Dlss, bool FrameGeneration) DlssLibraries(string executable)
{
try
{
// Resolve hands back either a path of its own search or the bare name of the pick.
string full = _files.FileExists(executable) ? executable : FullPath(executable);
string? directory = Path.GetDirectoryName(full);
if (string.IsNullOrEmpty(directory) || !_files.DirectoryExists(directory))
return (false, false);
bool windowsBuild = _files.FileExists(full)
? Format(full) == BinaryFormat.PortableExecutable
: _environment.IsWindows;
return windowsBuild
? (Has(directory, "nvngx_dlss.dll"), Has(directory, "nvngx_dlssg.dll"))
: (Has(directory, "libnvidia-ngx-dlss.so*"), Has(directory, "libnvidia-ngx-dlssg.so*"));
}
catch (Exception)
{
return (false, false);
}
}
private bool Has(string directory, string pattern) => _files.GetFiles(directory, pattern).Count > 0;
/// <summary>A path as <see cref="Resolve"/> gives it, which may be relative to the installation, made whole.</summary>
public string FullPath(string path) =>
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);

View File

@@ -53,6 +53,9 @@ public sealed class SettingsPaths
/// <summary>The sceneries starred in the list.</summary>
public string FavoritesPath() => Path.Combine(UserConfigDirectory(), "favorites.txt");
/// <summary>Which cleanup of the .sbt files each installation had.</summary>
public string SbtCleanupPath() => Path.Combine(UserConfigDirectory(), "sbt-cleanup.txt");
public string UserConfigDirectory() =>
Path.GetDirectoryName(UserConfigPath()) ?? _environment.BaseDirectory;
}

View File

@@ -1,24 +1,40 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using StarterNG.Classes;
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure.Settings;
public sealed class SettingsSerializer
{
private readonly bool _dlssPlatform;
private readonly Func<string, (int Width, int Height)?>? _monitorSize;
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
public SettingsSerializer(bool dlssPlatform = true)
/// <param name="monitorSize">
/// The size of the monitor a full screen of the simulator goes to, by what fullscreenmonitor
/// says; null where it is not known.
/// </param>
public SettingsSerializer(Func<string, (int Width, int Height)?>? monitorSize = null) =>
_monitorSize = monitorSize;
/// <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)
{
_dlssPlatform = dlssPlatform;
if (s.PhysicsLogTrainsInIni || !s.BlackBoxInIni || !s.BlackBox)
return;
s.PhysicsLogTrains = true;
s.PhysicsLogTrainsInIni = true;
s.PhysicsLog = false;
}
public bool DlssPlatform => _dlssPlatform;
public void Read(SimulatorSettings s, ConfigFile c)
{
s.LanguageWasSet = c.Has("lang");
@@ -30,20 +46,19 @@ public sealed class SettingsSerializer
s.FpsAverage = c.GetDouble("fpsaverage", 0);
s.PauseOnStart = c.GetBool("pause", false);
// As the old starter read it (src/uSettings.pas): of X its level and its sign, of Y
// only the sign. Both are written as that starter wrote them, one of its four speeds
// and 0.5, whatever the file had. A number that cannot be read leaves the standard level.
var mouse = c.GetTokens("mousescale");
if (mouse.Length >= 1 && double.TryParse(mouse[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double mx))
if (mouse.Length >= 1 && TryParseMouseScale(mouse[0], out double mx))
{
s.InvertMouseHorizontal = mx < 0;
s.MouseScaleXMagnitude = Math.Abs(mx);
s.CursorSensitivity = SensitivityStep(mx);
}
if (mouse.Length >= 2 && double.TryParse(mouse[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double my))
{
s.InvertMouseVertical = my < 0;
s.MouseScaleYMagnitude = Math.Abs(my);
s.CursorSensitivity = SimulatorSettings.MouseLevelOf(mx);
}
if (mouse.Length >= 1)
s.InvertMouseVertical = mouse.Length >= 2 && TryParseMouseScale(mouse[1], out double my) && my < 0;
s.IgnoreGamepad = !c.GetBool("input.gamepad", true);
s.IgnoreGamepad = !c.GetBool("input.gamepad", false);
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
s.FeedbackPort = c.GetInt("feedbackport", 888);
s.UartEnabled = c.Has("uart");
@@ -76,8 +91,7 @@ public sealed class SettingsSerializer
s.VirtualShunting = c.GetBool("ai.trainman", true);
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "full"));
s.VulkanDevice = c.GetString("gfx.vulkan.device", "");
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default"));
s.Width = c.GetInt("width", 1280);
s.Height = c.GetInt("height", 720);
s.BufferScalePercent = ReadBufferScale(c);
@@ -85,9 +99,6 @@ public sealed class SettingsSerializer
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
s.AntiAliasing = ReadAntiAliasing(c);
s.DlssPreset = c.GetString("gfx.dlss.preset", "default").ToLowerInvariant();
s.FrameGeneration = ParseFrameGeneration(FirstToken(c, "gfx.framegeneration"));
s.Reflex = ParseReflex(FirstToken(c, "gfx.reflex"));
s.DynamicLights = Clamp(c.GetInt("dynamiclights", 7), 0, 7);
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
s.VSync = c.GetBool("vsync", false);
@@ -99,34 +110,6 @@ public sealed class SettingsSerializer
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
s.UseVbo = c.GetBool("usevbo", true);
s.RenderShadows = c.GetBool("shadows", true);
s.ShadowSdsm = c.GetBool("gfx.shadow.sdsm", false);
s.LightShadows = ParseLevel(FirstToken(c, "gfx.lights.shadows"), 2, 3);
s.ContactShadows = ParseLevel(FirstToken(c, "gfx.contactshadows"), 0, 3);
s.LightsClustered = c.GetBool("gfx.lights.clustered", true);
s.AmbientOcclusion = ParseAmbientOcclusion(FirstToken(c, "gfx.postfx.ao"));
var aoQuality = c.GetTokens("gfx.postfx.ao.quality");
s.AoSlices = aoQuality.Length >= 1 ? ParseInt(aoQuality[0], 3) : 3;
s.AoSteps = aoQuality.Length >= 2 ? ParseInt(aoQuality[1], 4) : 4;
s.AoLighting = c.GetBool("gfx.postfx.ao.lighting", true);
s.CabProbe = ParseCabProbe(FirstToken(c, "gfx.cabprobe"));
s.CabProbeInterval = c.GetInt("gfx.cabprobe.interval", 4);
s.CabProbeBounce = c.GetDouble("gfx.cabprobe.bounce", 1.0);
s.CabProbeReflections = c.GetBool("gfx.cabprobe.reflections", true);
s.CabLampLight = c.GetBool("gfx.lights.cab", true);
s.DepthPrepassScene = c.GetBool("gfx.depthprepass.scene", false);
s.Ssr = ParseLevel(FirstToken(c, "gfx.ssr"), 2, 3);
s.RayTracing = c.GetBool("gfx.raytracing", false);
s.RayTracingRange = (int)Math.Round(c.GetDouble("gfx.raytracing.range", 500));
s.VolumetricFog = ParseVolumetricFog(FirstToken(c, "gfx.fog"));
s.FogQuality = ParseFogQuality(FirstToken(c, "gfx.fog.quality"));
s.Clouds = ParseLevel(FirstToken(c, "gfx.clouds"), 2, 4);
s.CloudShadows = c.GetBool("gfx.clouds.shadows", true);
s.Grass = c.GetBool("gfx.grass", true);
s.GrassDistance = (int)Math.Round(c.GetDouble("gfx.grass.distance", 60));
s.GrassDensity = c.GetDouble("gfx.grass.density", 1.0);
s.PrecipitationParticles = c.GetInt("gfx.precipitation.particles", 65536);
s.Bloom = c.GetBool("gfx.postfx.bloom", true);
s.AutoExposure = c.GetBool("gfx.postfx.autoexposure", true);
// A negative rate counts as its size; none at all, as never.
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
@@ -150,6 +133,7 @@ public sealed class SettingsSerializer
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
s.FullscreenMonitor = LegacyText.Utf8From1250(c.GetString("fullscreenmonitor", "").Trim());
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4);
@@ -157,6 +141,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;
@@ -193,6 +182,8 @@ public sealed class SettingsSerializer
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
s.AutoExpandSceneryTree = c.GetBool("starter.expandtree", false);
s.AdvancedSettings = c.GetBool("starter.settings.advanced", false);
s.MovedToStandard = c.GetBool("starter.settings.standard", false);
s.CpuNotice = c.GetBool("starter.cpunotice", true);
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
? GpuPreference.System
@@ -217,7 +208,7 @@ public sealed class SettingsSerializer
if (c.Has(key.Key))
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
GraphicsRules.Normalize(s, _dlssPlatform);
GraphicsRules.Normalize(s);
}
/// <summary>
@@ -228,13 +219,20 @@ public sealed class SettingsSerializer
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "gfx.vulkan.device" };
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "fullscreenmonitor" };
/// <summary>Keys no simulator reads any more, taken out of the file on a save.</summary>
public static readonly string[] ObsoleteKeys =
{
"gfx.postfx.tonemapping",
"starter.developertools",
// The OpenGL 4.6 and Vulkan renderers', which the simulator's master does not have.
"gfx.antialiasing", "gfx.buffer.percent", "gfx.vulkan.device", "gfx.dlss.preset", "gfx.framegeneration",
"gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.ssr", "gfx.lights.clustered", "gfx.lights.shadows",
"gfx.contactshadows", "gfx.shadow.sdsm", "gfx.postfx.ao", "gfx.postfx.ao.lighting", "gfx.postfx.ao.quality",
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.bounce", "gfx.cabprobe.reflections", "gfx.fog",
"gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows", "gfx.postfx.bloom", "gfx.postfx.autoexposure",
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density", "gfx.precipitation.particles",
};
/// <summary>
@@ -244,7 +242,7 @@ public sealed class SettingsSerializer
public void Write(SimulatorSettings settings, ConfigFile c)
{
var s = settings.Copy();
GraphicsRules.Normalize(s, _dlssPlatform);
GraphicsRules.Normalize(s);
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
? "en"
@@ -253,14 +251,11 @@ public sealed class SettingsSerializer
c.SetBool("inactivepause", s.PauseWhenInactive);
c.SetBool("pause", s.PauseOnStart);
double magnitude = SensitivityStep(s.MouseScaleXMagnitude) == s.CursorSensitivity
? s.MouseScaleXMagnitude
: s.CursorSensitivity;
double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1);
double my = s.MouseScaleYMagnitude * (s.InvertMouseVertical ? -1 : 1);
double mx = SimulatorSettings.MouseScaleOf(s.CursorSensitivity) * (s.InvertMouseHorizontal ? -1 : 1);
double my = SimulatorSettings.MouseScaleY * (s.InvertMouseVertical ? -1 : 1);
c.Set("mousescale",
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
$"{mx.ToString("0.0", CultureInfo.InvariantCulture)} " +
$"{my.ToString("0.0", CultureInfo.InvariantCulture)}");
c.SetBool("input.gamepad", !s.IgnoreGamepad);
c.SetInt("feedbackmode", s.FeedbackMode);
@@ -292,26 +287,17 @@ public sealed class SettingsSerializer
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
if (!string.IsNullOrWhiteSpace(s.VulkanDevice)) c.Set("gfx.vulkan.device", s.VulkanDevice.Trim());
c.SetInt("width", s.Width);
c.SetInt("height", s.Height);
c.SetInt("starter.bufferscale", s.BufferScalePercent);
int fbw = (int)Math.Round(s.Width * s.BufferScalePercent / 100.0);
int fbh = (int)Math.Round(s.Height * s.BufferScalePercent / 100.0);
// The size for the simulators before gfx.buffer.percent, which pass that one over and the other way round.
c.SetInt("gfx.framebuffer.width", fbw);
c.SetInt("gfx.framebuffer.height", fbh);
c.SetInt("gfx.buffer.percent", s.BufferScalePercent);
// The simulator draws into a buffer of this size and stretches it to the window.
var (bufferWidth, bufferHeight) = FramebufferSize(s);
c.SetInt("gfx.framebuffer.width", bufferWidth);
c.SetInt("gfx.framebuffer.height", bufferHeight);
c.SetInt("maxtexturesize", s.MaxTextureSize);
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
c.SetDouble("anisotropicfiltering", s.TextureFiltering);
// multisampling is what older simulators read; gfx.antialiasing overrides it in the new ones, but only from
// a later line, since each key sets the mode as it is read.
c.SetInt("multisampling", MultisamplingLevel(s.AntiAliasing));
c.Set("gfx.antialiasing", AntiAliasingToken(s.AntiAliasing));
c.Set("gfx.dlss.preset", s.DlssPreset);
c.Set("gfx.framegeneration", s.FrameGeneration > 1 ? $"x{s.FrameGeneration}" : "off");
c.Set("gfx.reflex", s.Reflex switch { 1 => "on", 2 => "boost", _ => "off" });
c.SetInt("dynamiclights", s.DynamicLights);
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
c.SetBool("vsync", s.VSync);
@@ -324,32 +310,6 @@ public sealed class SettingsSerializer
c.SetBool("usevbo", s.UseVbo);
c.SetBool("shadows", s.RenderShadows);
c.SetBool("gfx.shadowmap.enabled", s.RenderShadows);
c.SetBool("gfx.shadow.sdsm", s.ShadowSdsm);
c.Set("gfx.lights.shadows", LevelToken(s.LightShadows));
c.Set("gfx.contactshadows", LevelToken(s.ContactShadows));
c.SetBool("gfx.lights.clustered", s.LightsClustered);
c.Set("gfx.postfx.ao", s.AmbientOcclusion switch { 1 => "ssao", 2 => "gtao", _ => "no" });
c.Set("gfx.postfx.ao.quality", $"{s.AoSlices} {s.AoSteps}");
c.SetBool("gfx.postfx.ao.lighting", s.AoLighting);
c.Set("gfx.cabprobe", LevelToken(s.CabProbe));
c.SetInt("gfx.cabprobe.interval", s.CabProbeInterval);
c.SetDouble("gfx.cabprobe.bounce", s.CabProbeBounce);
c.SetBool("gfx.cabprobe.reflections", s.CabProbeReflections);
c.Set("gfx.ssr", LevelToken(s.Ssr));
c.SetBool("gfx.raytracing", s.RayTracing);
c.SetInt("gfx.raytracing.range", s.RayTracingRange);
c.Set("gfx.fog", s.VolumetricFog ? "yes" : "analytic");
c.Set("gfx.fog.quality", LevelToken(s.FogQuality));
c.Set("gfx.clouds", LevelToken(s.Clouds));
c.SetBool("gfx.clouds.shadows", s.CloudShadows);
c.SetBool("gfx.grass", s.Grass);
c.SetInt("gfx.grass.distance", s.GrassDistance);
// The grass thins out past its distance; the simulator's own default keeps a sixth of it for that.
c.SetInt("gfx.grass.fadedistance", Math.Min(600, s.GrassDistance + Math.Max(10, s.GrassDistance / 6)));
c.SetDouble("gfx.grass.density", s.GrassDensity);
c.SetInt("gfx.precipitation.particles", s.PrecipitationParticles);
c.SetBool("gfx.postfx.bloom", s.Bloom);
c.SetBool("gfx.postfx.autoexposure", s.AutoExposure);
c.Set("gfx.reflections.framerate", s.ReflectionsFramerate.ToString("0.######", CultureInfo.InvariantCulture));
c.Set("shadowtune",
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
@@ -363,6 +323,9 @@ public sealed class SettingsSerializer
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
// The simulator compares the word with GLFW's name of the monitor, which is UTF-8.
if (!string.IsNullOrWhiteSpace(s.FullscreenMonitor))
c.Set("fullscreenmonitor", LegacyText.Utf8As1250(s.FullscreenMonitor.Trim()));
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
c.SetInt("splinefidelity", s.SplineFidelity);
@@ -370,6 +333,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);
@@ -402,6 +372,8 @@ public sealed class SettingsSerializer
c.SetBool("starter.autoclose", s.AutoCloseStarter);
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
c.SetBool("starter.expandtree", s.AutoExpandSceneryTree);
c.SetBool("starter.settings.advanced", s.AdvancedSettings);
c.SetBool("starter.settings.standard", s.MovedToStandard);
c.SetBool("starter.cpunotice", s.CpuNotice);
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
@@ -420,60 +392,79 @@ public sealed class SettingsSerializer
c.Set(key.Key, value.Trim());
}
// What the simulator goes by: up to 4 a part of the window, above it percents.
private static int ReadBufferScale(ConfigFile c)
{
if (!c.Has("gfx.buffer.percent"))
return Clamp(c.GetInt("starter.bufferscale", 100), 25, 200);
/// <summary>The keys of the frame buffer's size.</summary>
public static readonly string[] FramebufferKeys = { "gfx.framebuffer.width", "gfx.framebuffer.height" };
double value = c.GetDouble("gfx.buffer.percent", 100);
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
/// <summary>What the simulator takes for "as large as the window" (opengl33renderer.cpp), its own default.</summary>
public const int FramebufferOfWindow = -1;
/// <summary>
/// The frame buffer of <paramref name="s"/>: its part of the window. Borderless, the window
/// is the monitor whatever width and height say (application.cpp), so the buffer is the
/// window's own, or its part of the monitor's size where that is known.
/// </summary>
private (int Width, int Height) FramebufferSize(SimulatorSettings s)
{
if (!s.FullscreenWindowed)
return (Part(s.Width, s.BufferScalePercent), Part(s.Height, s.BufferScalePercent));
if (s.BufferScalePercent < 100 &&
_monitorSize?.Invoke(s.FullscreenMonitor.Trim()) is { Width: > 0, Height: > 0 } monitor)
return (Part(monitor.Width, s.BufferScalePercent), Part(monitor.Height, s.BufferScalePercent));
return (FramebufferOfWindow, FramebufferOfWindow);
}
private static string FirstToken(ConfigFile c, string key)
private static int Part(int size, int percent) => (int)Math.Round(size * percent / 100.0);
/// <summary>
/// <paramref name="keys"/> with the keys that say the same setting along with them: the
/// starter's own percent goes wherever the frame buffer's size does, or it would stand
/// when the size is put back.
/// </summary>
public static IReadOnlyCollection<string> WithCompanions(IReadOnlyCollection<string> keys)
{
var tokens = c.GetTokens(key);
return tokens.Length > 0 ? tokens[0].ToLowerInvariant() : string.Empty;
if (!keys.Intersect(FramebufferKeys, StringComparer.OrdinalIgnoreCase).Any())
return keys;
var all = new HashSet<string>(keys, StringComparer.OrdinalIgnoreCase) { "starter.bufferscale" };
all.UnionWith(FramebufferKeys);
return all;
}
// The names the simulator takes for Vulkan; every other word is OpenGL to the screen, and stays in the file until changed.
// Whichever of the two keys comes later in the file decides, as each sets the mode when the simulator reads it.
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c)
private static int ReadBufferScale(ConfigFile c) =>
Clamp(BufferScaleIn(c), 25, GraphicsRules.MaxBufferScale);
// The starter's own percent, or the framebuffer the file sets against its window.
private static int BufferScaleIn(ConfigFile c)
{
var fromMultisampling = c.GetInt("multisampling", 2) switch
{
<= 0 => AntiAliasingMode.Off,
1 => AntiAliasingMode.Msaa2,
2 => AntiAliasingMode.Msaa4,
_ => AntiAliasingMode.Msaa8
};
if (!c.Has("gfx.antialiasing") ||
(c.Has("multisampling") && c.LineOf("multisampling") > c.LineOf("gfx.antialiasing")))
return fromMultisampling;
return FirstToken(c, "gfx.antialiasing") switch
{
"off" or "no" or "none" or "0" => AntiAliasingMode.Off,
"msaax2" => AntiAliasingMode.Msaa2,
"msaax4" => AntiAliasingMode.Msaa4,
"msaax8" or "msaax16" => AntiAliasingMode.Msaa8,
"taa" => AntiAliasingMode.Taa,
"dlss" => AntiAliasingMode.Dlss,
"dlaa" => AntiAliasingMode.Dlaa,
_ => fromMultisampling
};
if (c.Has("starter.bufferscale"))
return c.GetInt("starter.bufferscale", 100);
int width = c.GetInt("width", 0);
int framebuffer = c.GetInt("gfx.framebuffer.width", 0);
return width > 0 && framebuffer > 0 ? (int)Math.Round(framebuffer * 100.0 / width) : 100;
}
private static string AntiAliasingToken(AntiAliasingMode mode) => mode switch
/// <summary>
/// The keys of <paramref name="c"/> set above what the starter lets them go to
/// (<see cref="GraphicsRules"/>): the next save brings them down.
/// </summary>
public static IReadOnlySet<string> OverCapKeys(ConfigFile c)
{
AntiAliasingMode.Msaa2 => "msaax2",
AntiAliasingMode.Msaa4 => "msaax4",
AntiAliasingMode.Msaa8 => "msaax8",
AntiAliasingMode.Taa => "taa",
AntiAliasingMode.Dlss => "dlss",
AntiAliasingMode.Dlaa => "dlaa",
_ => "off"
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (c.GetInt("maxcabtexturesize", 0) > GraphicsRules.MaxCabTextureSize)
keys.Add("maxcabtexturesize");
var shadowTune = c.GetTokens("shadowtune");
if (shadowTune.Length >= 3 && ParseDouble(shadowTune[2], 0) > GraphicsRules.MaxShadowRange)
keys.Add("shadowtune");
if (BufferScaleIn(c) > GraphicsRules.MaxBufferScale)
keys.UnionWith(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height" });
return keys;
}
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c) => c.GetInt("multisampling", 2) switch
{
<= 0 => AntiAliasingMode.Off,
1 => AntiAliasingMode.Msaa2,
2 => AntiAliasingMode.Msaa4,
_ => AntiAliasingMode.Msaa8
};
private static int MultisamplingLevel(AntiAliasingMode mode) => mode switch
@@ -484,79 +475,26 @@ public sealed class SettingsSerializer
_ => 0
};
private static int ParseFrameGeneration(string value) => value switch
{
"x2" or "on" or "yes" or "2" => 2,
"x3" or "3" => 3,
"x4" or "4" => 4,
_ => 1
};
private static int ParseReflex(string value) => value switch
{
"on" or "yes" or "1" => 1,
"boost" or "2" => 2,
_ => 0
};
// no/low/medium/high(/ultra) or the number of the level; an absent key keeps the simulator's default.
private static int ParseLevel(string value, int fallback, int max)
{
if (value.Length == 0)
return fallback;
int level = value switch
{
"low" or "1" => 1,
"medium" or "yes" or "true" or "2" => 2,
"high" or "3" => 3,
"ultra" or "4" => 4,
_ => 0
};
return Math.Min(level, max);
}
private static string LevelToken(int level) => level switch
{
1 => "low",
2 => "medium",
3 => "high",
4 => "ultra",
_ => "no"
};
// As the simulator reads it, but a value it does not know keeps its default (medium) rather than turning the probe off.
private static int ParseCabProbe(string value) => value switch
{
"no" or "false" or "off" or "0" => 0,
"low" or "1" => 1,
"high" or "3" => 3,
_ => 2
};
private static int ParseAmbientOcclusion(string value) => value switch
{
"" => 2,
"yes" or "true" or "1" or "gtao" => 2,
"ssao" => 1,
_ => 0
};
private static bool ParseVolumetricFog(string value) =>
value is not ("analytic" or "old" or "no" or "false" or "0");
private static int ParseFogQuality(string value) => value switch
{
"low" or "1" => 1,
"high" or "3" => 3,
"ultra" or "4" => 4,
_ => 2
};
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
private static int SensitivityStep(double mouseScale) =>
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
/// <summary>
/// Whether the file's own mousescale can stay as it is: one of the old starter's four
/// speeds, and 0.5 or -0.5 after it. Otherwise a save writes the one the starter holds,
/// as every save of the old starter did.
/// </summary>
public static bool MouseScaleStands(string? raw)
{
string[] tokens = (raw ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
return tokens.Length >= 2 &&
TryParseMouseScale(tokens[0], out double x) &&
Math.Abs(Math.Abs(x) - SimulatorSettings.MouseScaleOf(SimulatorSettings.MouseLevelOf(x))) < 1e-9 &&
TryParseMouseScale(tokens[1], out double y) &&
Math.Abs(Math.Abs(y) - SimulatorSettings.MouseScaleY) < 1e-9;
}
private static bool TryParseMouseScale(string token, out double scale) =>
double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale) &&
double.IsFinite(scale);
private static double ParseDouble(string s, double fallback) =>
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback;

View File

@@ -18,6 +18,7 @@ using StarterNG.Infrastructure;
using StarterNG.Views;
using StarterNG.Application;
using StarterNG.Application.Abstractions;
using StarterNG.Domain;
using StarterNG.Domain.Settings;
namespace StarterNG;
@@ -40,8 +41,9 @@ public partial class MainWindow : Window
private DateTime _openedUtc = DateTime.UtcNow;
private DateTime _startedUtc = DateTime.MinValue;
private bool _starting;
private bool _lookingAtSceneryFiles;
private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = TimeSpan.FromSeconds(2) };
// Scenery files: looked at when they change, on coming back to the window or from the
// simulator, and now and then anyway.
private readonly FolderLooks _sceneryLooks;
public MainWindow()
{
@@ -102,12 +104,14 @@ public partial class MainWindow : Window
AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel);
AppServices.Current.State.Changed += UpdateStartButton;
Views.Settings.AdvancedModeChanged += UpdateStartButton;
// Settings an older starter left are brought into the standard mode, once.
SettingsView.MoveToStandardOnce();
Opened += (_, _) =>
{
_openedUtc = DateTime.UtcNow;
UpdateStartButton();
_sceneryFilesTimer.Start();
FollowLastRun();
};
Activated += (_, _) =>
@@ -117,20 +121,20 @@ public partial class MainWindow : Window
if (SettingsView.IsVisible)
SettingsView.RefreshExecutables();
};
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
Closed += (_, _) => _sceneryFilesTimer.Stop();
// After the handlers above: back at the window, the settings are checked first.
_sceneryLooks = new FolderLooks(this, () => AppServices.Current.Paths.Scenery, LookAtSceneryFilesAsync);
}
/// <summary>
/// Scenery files changed outside the starter are picked up without a reload. Not
/// with the simulator running: it is left in peace, and what it changes comes in after it.
/// Run through <see cref="_sceneryLooks"/>, one look at a time.
/// </summary>
private async Task LookAtSceneryFilesAsync()
{
if (_lookingAtSceneryFiles || AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
if (AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
return;
_lookingAtSceneryFiles = true;
try
{
var services = AppServices.Current;
@@ -146,10 +150,6 @@ public partial class MainWindow : Window
{
Diagnostics.Log("Following the scenery files", ex);
}
finally
{
_lookingAtSceneryFiles = false;
}
}
/// <summary>
@@ -511,6 +511,15 @@ public partial class MainWindow : Window
return;
}
// The standard mode edits every consist but starts only in one the player drives.
if (!TrainsetDisplay.StartableIn(trainset, AppServices.Current.Settings))
{
startButton.Content = App.Loc[trainset.Decor ? "StartDecor" : "StartAi"];
ToolTip.SetTip(startButton, null);
startButton.IsEnabled = false;
return;
}
bool staffed = HasStartableVehicle(trainset);
startButton.Content = staffed ? App.Loc["Start"] : App.Loc["StartNoStaff"];
ToolTip.SetTip(startButton, staffed ? null : App.Loc["StartNoStaffConfirm"]);
@@ -637,6 +646,9 @@ public partial class MainWindow : Window
// would start a second simulator.
if (_starting || DateTime.UtcNow - _startedUtc < StartCooldown)
return;
// A shortcut starts the same way the button does, and only where the button may.
if (!freeFly && !startButton.IsEnabled)
return;
_starting = true;
try
@@ -652,6 +664,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));
@@ -742,6 +777,8 @@ public partial class MainWindow : Window
FollowLastRun();
RestoreFromSimulator();
ReportIfCrashed(simulator, executable, started);
// What the simulator or its editor wrote while it ran comes in now.
_ = _sceneryLooks.LookAsync();
}), TaskScheduler.Default);
}
@@ -751,7 +788,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

@@ -4,7 +4,7 @@
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>
<IsAotCompatible>true</IsAotCompatible>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<ApplicationManifest>app.manifest</ApplicationManifest>

View File

@@ -81,15 +81,13 @@
TextWrapping="Wrap"
Margin="0,3,0,0" />
<!-- Why the chosen simulator would ignore the setting. Under
the explanation, at full strength while the rest dims. -->
<TextBlock Name="PART_IdleNote"
<!-- A value of eu07.ini the starter cannot read: amber, as the other warnings. -->
<TextBlock Name="PART_Unknown"
Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"
Text="{TemplateBinding IdleNote}"
Text="{TemplateBinding UnknownValue}"
IsVisible="False"
FontSize="12"
FontStyle="Italic"
Foreground="{StaticResource CarbonFg}"
Foreground="#D9A43A"
TextWrapping="Wrap"
Margin="0,3,0,0" />
@@ -103,6 +101,13 @@
<Style Selector="^:no-key /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="IsVisible" Value="False" />
</Style>
<!-- The standard mode: the eu07.ini key means nothing to a player. -->
<Style Selector="^.HideKey /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^:unknown /template/ TextBlock#PART_Unknown">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="^:no-value /template/ TextBlock#PART_Value">
<Setter Property="IsVisible" Value="False" />
</Style>
@@ -113,24 +118,6 @@
<Setter Property="Grid.Column" Value="1" />
<Setter Property="Grid.ColumnSpan" Value="2" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_IdleNote">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Label">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ ContentPresenter#PART_Content">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Value">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Description">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="Opacity" Value="0.45" />
</Style>
<!-- A checkbox is its own label, so let it take the label column too.
Alignment stays Stretch: a bare slider in a labelless row still
wants the full width. -->

View File

@@ -137,7 +137,8 @@
HorizontalContentAlignment="Center"
Click="AddToWarehouseButton_OnClick"
Content="{Binding [AddToWarehouse], Source={x:Static starterNg:App.Loc}}" />
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
<!-- The advanced mode's own: the standard mode lists every consist with vehicles. -->
<StackPanel Name="consistFilters" DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
Margin="2,6,0,0">
<CheckBox Name="depotDrivableOnlyCheck" FontSize="12"
IsCheckedChanged="ConsistFilter_OnChanged"

View File

@@ -69,6 +69,13 @@ public partial class Depot : UserControl
if (Design.IsDesignMode)
return;
// The standard mode lists other consists and leaves the crew alone.
Settings.AdvancedModeChanged += () =>
{
PopulateSceneryConsists();
RebuildConsist();
};
_warehouse = new Warehouse(warehouseList, removeFromWarehouseButton, _hand,
() => AppServices.Current.State.CurrentTrainset, ApplyFromWarehouse);
_warehouse.SelectionChanged += () =>
@@ -77,6 +84,7 @@ public partial class Depot : UserControl
EditWarehouseSelection();
};
_warehouse.Renamed += _warehouseEdit.Renamed;
_warehouseEdit.Saved += _warehouse.RefreshEntry;
_browser = new VehicleBrowser(categoryCombo, classCombo, vehicleListBox, searchBox,
hideArchivalCheck, miniPreview, addVehicleButton, _db, _minis, OpenVehicleBase)
@@ -597,6 +605,7 @@ public partial class Depot : UserControl
depotShowAiCheck.IsChecked = AppServices.Current.Settings.ShowAiVehicles;
depotDrivableOnlyCheck.IsChecked = AppServices.Current.Settings.DrivableOnly;
consistFilters.IsVisible = AppServices.Current.Settings.AdvancedSettings;
_listScenery = AppServices.Current.State.CurrentScenery ?? _sceneries.FirstOrDefault();
sceneryConsistsTab.Header = App.Loc["SceneryConsists"];
@@ -605,12 +614,11 @@ public partial class Depot : UserControl
if (_listScenery != null)
{
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
var settings = AppServices.Current.Settings;
foreach (var trainset in _listScenery.Trainsets)
{
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, AppServices.Current.State.CurrentTrainset))
if (!TrainsetDisplay.ListedIn(trainset, settings, AppServices.Current.State.CurrentTrainset))
continue;
var entry = new ListBoxItem
@@ -754,17 +762,29 @@ public partial class Depot : UserControl
if (scenery.Trainsets.Count == 0) return;
if (await AskTextureRandomizerOpts() is not { } opts) return;
var editing = _consist.EditingTrainset;
// Each consist goes through a consist of its own, off the screen: the strip and the
// list are drawn again once at the end, not for every consist on the way, and one
// randomizer looks the candidates up for all of them.
var work = new Consist(_db, _info);
var rnd = TextureRandomizer(opts);
var changed = new HashSet<Trainset>(ReferenceEqualityComparer.Instance);
foreach (var trainset in scenery.Trainsets)
{
_consist.LoadFrom(trainset);
if (ApplyTextureRandomizer(opts))
WriteBackToScenery();
work.LoadFrom(trainset);
if (work.Count == 0 || rnd.Apply(work, texture => work.MakeDynamic(texture, scenery)) <= 0)
continue;
work.AutoConnectAll();
trainset.Vehicles = work.Flatten();
changed.Add(trainset);
}
if (changed.Count == 0)
return;
if (editing != null)
if (_consist.EditingTrainset is { } editing && changed.Contains(editing))
_consist.LoadFrom(editing);
RebuildConsist();
RefreshConsistListLabels();
if (AppServices.Current.State.CurrentTrainset is { } current && changed.Contains(current))
AppServices.Current.State.NotifyChanged();
}
private async Task<TextureRandomizerDialog.Options?> AskTextureRandomizerOpts() =>
@@ -776,19 +796,21 @@ public partial class Depot : UserControl
{
if (_consist.Count == 0) return false;
var rnd = new TexRandomizer(_db, _rng)
{
WithoutArchival = opts.WithoutArchival,
RevisionTolerance = opts.RevisionTolerance,
RevYear = opts.RevYear
};
if (rnd.Apply(_consist, NewVehicle) <= 0)
if (TextureRandomizer(opts).Apply(_consist, NewVehicle) <= 0)
return false;
_consist.AutoConnectAll();
return true;
}
private TexRandomizer TextureRandomizer(TextureRandomizerDialog.Options opts) =>
new(_db, _rng)
{
WithoutArchival = opts.WithoutArchival,
RevisionTolerance = opts.RevisionTolerance,
RevYear = opts.RevYear
};
private void RandomOrderButton_OnClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) =>
_consist.RandomizeOrder(_rng);

View File

@@ -4,6 +4,7 @@ using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
@@ -536,8 +537,21 @@ public sealed class VehicleBrowser
// mostly by who runs them.
private static Control BrowserLabel(VehicleTexture texture, IReadOnlyList<VehicleTexture>? set)
{
// Clear of the scroll bar, which lies over the right edge of the list.
var row = new DockPanel { Margin = new Thickness(0, 0, 10, 0) };
// Clear of the scroll bar, which lies over the right edge of the list. The name comes
// first: a long operator is cut short to a width of its own, and either ends in "…"
// rather than running into the other.
var row = new Grid { Margin = new Thickness(0, 0, 10, 0), ColumnDefinitions = new ColumnDefinitions("*,Auto") };
var name = new TextBlock { TextTrimming = TextTrimming.CharacterEllipsis };
name.Inlines!.Add(new Run(BrowserName(texture)));
if (set is { Count: > 1 })
{
var count = new Run($" ×{set.Count}");
if (Avalonia.Application.Current?.TryGetResource("CarbonFgDim", null, out var dim) == true && dim is IBrush brush)
count.Foreground = brush;
name.Inlines.Add(count);
}
row.Children.Add(name);
string? op = texture.Meta?.Operator;
if (!string.IsNullOrWhiteSpace(op) && op != "?")
@@ -546,19 +560,14 @@ public sealed class VehicleBrowser
{
Text = op,
Opacity = 0.55,
MaxWidth = 110,
Margin = new Thickness(8, 0, 0, 0),
TextTrimming = TextTrimming.CharacterEllipsis
};
DockPanel.SetDock(operatorText, Dock.Right);
Grid.SetColumn(operatorText, 1);
row.Children.Add(operatorText);
}
var name = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
name.Children.Add(new TextBlock { Text = BrowserName(texture) });
if (set is { Count: > 1 })
name.Children.Add(new TextBlock { Text = $"×{set.Count}", Opacity = 0.55 });
row.Children.Add(name);
return row;
}

View File

@@ -1,4 +1,5 @@
using System;
using StarterNG.Application;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
@@ -116,7 +117,9 @@ public sealed class VehicleCards
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 1, 0, 2)
};
controls.Children.Add(DriverButton(item));
// Who sits in the cab - the player, the simulator, a passenger or nobody - is for the advanced mode.
if (AppServices.Current.Settings.AdvancedSettings)
controls.Children.Add(DriverButton(item));
controls.Children.Add(FlipButton(item));
if (item.Grouped && item.Cars.Count > 1)
@@ -692,10 +695,13 @@ public sealed class VehicleCards
else if (_consist.CanJoin(item, index))
menu.AddItem(App.Loc["TipJoin"], () => _consist.Join(item));
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
if (AppServices.Current.Settings.AdvancedSettings)
{
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
}
// The member the panels show, not always the first car of a unit.
menu.AddItem(App.Loc["WagonNumber"] + "…",

Some files were not shown because too many files have changed in this diff Show More