mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-24 08:59:11 +01:00
Compare commits
45 Commits
fix/scener
...
feat/setti
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d8790301d | ||
| e0d3988d4a | |||
| 57821887e4 | |||
|
|
900161a6c4 | ||
|
|
5ec7a4b539 | ||
|
|
d429d041ff | ||
|
|
f7a58e8431 | ||
|
|
77b0c23cea | ||
|
|
de4eb99ea1 | ||
|
|
34beec588d | ||
|
|
bc4adfe6fa | ||
|
|
c70fd94783 | ||
|
|
5d966be11c | ||
|
|
93f914c868 | ||
|
|
de943cf461 | ||
|
|
e63aa71bf8 | ||
|
|
ecf3067d85 | ||
|
|
4b3ee43e4a | ||
|
|
7e249a7a9a | ||
|
|
97a2c2c75c | ||
|
|
943b855f20 | ||
|
|
797e2e70a7 | ||
| c07ed2fb4d | |||
| cfea240243 | |||
|
|
f0fa2d1768 | ||
|
|
fa8ae760e1 | ||
|
|
195f358e55 | ||
|
|
be7b9c5679 | ||
|
|
faa06fb9d8 | ||
|
|
829a3e7a3d | ||
|
|
5b43e29f9e | ||
|
|
b63ba8fe2e | ||
|
|
76693c1494 | ||
|
|
13990a7036 | ||
|
|
5ab9bce321 | ||
|
|
f1d77addae | ||
|
|
192f9fa499 | ||
|
|
92c0283479 | ||
|
|
b2fd53f7bc | ||
|
|
06513537f0 | ||
|
|
7823bb8d09 | ||
|
|
1398545ff2 | ||
|
|
45105e7b9c | ||
|
|
4429eff4ef | ||
|
|
1ef630b1b6 |
8
.github/workflows/dotnet.yml
vendored
8
.github/workflows/dotnet.yml
vendored
@@ -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
|
||||
|
||||
4
.github/workflows/sonar.yml
vendored
4
.github/workflows/sonar.yml
vendored
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -30,7 +30,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.",
|
||||
["Follow"] = "Follow the train",
|
||||
["Fit"] = "Whole map",
|
||||
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
|
||||
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.",
|
||||
["Unreadable"] = "Can't read {0}: {1}",
|
||||
["Reading"] = "Reading {0}…",
|
||||
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
|
||||
@@ -190,6 +190,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
|
||||
["EventTimetable"] = "Timetable {0}, {1}",
|
||||
["CabSpeed"] = "Speed",
|
||||
["CabWheels"] = "wheels {0:0}",
|
||||
["CabAiTarget"] = "AI {0:0} km/h",
|
||||
["CabAcceleration"] = "Along",
|
||||
["CabLateral"] = "Lateral",
|
||||
@@ -308,7 +309,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
|
||||
["Follow"] = "Śledź pociąg",
|
||||
["Fit"] = "Cała mapa",
|
||||
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",
|
||||
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.",
|
||||
["Unreadable"] = "Nie można odczytać {0}: {1}",
|
||||
["Reading"] = "Czytanie {0}…",
|
||||
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
|
||||
@@ -468,6 +469,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
|
||||
["EventTimetable"] = "Rozkład {0}, {1}",
|
||||
["CabSpeed"] = "Prędkość",
|
||||
["CabWheels"] = "koła {0:0}",
|
||||
["CabAiTarget"] = "AI {0:0} km/h",
|
||||
["CabAcceleration"] = "Wzdłużne",
|
||||
["CabLateral"] = "Boczne",
|
||||
|
||||
@@ -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++)
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -316,6 +316,8 @@ public sealed class EventList : ListBox
|
||||
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
||||
];
|
||||
|
||||
private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight;
|
||||
|
||||
/// <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
|
||||
@@ -325,7 +327,8 @@ public sealed class EventList : ListBox
|
||||
{
|
||||
CabSample? last = null;
|
||||
bool movingOpen = false;
|
||||
foreach (var s in recording.Cab)
|
||||
// the doors' sides as the driver has them, from the cab the driver is in (CabSample.AsTheCabSees)
|
||||
foreach (var s in recording.Cab.Select(sample => sample.AsTheCabSees))
|
||||
{
|
||||
if (last is not { } b || b.Vehicle != s.Vehicle)
|
||||
{
|
||||
@@ -333,8 +336,10 @@ public sealed class EventList : ListBox
|
||||
movingOpen = false;
|
||||
continue;
|
||||
}
|
||||
bool Came(CabDevices device) => !b.Has(device) && s.Has(device);
|
||||
bool Went(CabDevices device) => b.Has(device) && !s.Has(device);
|
||||
// the other end swaps the sides, and tells nothing of the doors; no cab (0) sees them as the front one does
|
||||
bool sameCab = (b.CabEnd < 0) == (s.CabEnd < 0);
|
||||
bool Came(CabDevices device) => !b.Has(device) && s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
||||
bool Went(CabDevices device) => b.Has(device) && !s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
||||
foreach (var (device, key) in Switched)
|
||||
{
|
||||
if (Came(device))
|
||||
|
||||
@@ -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,10 +139,7 @@ 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)
|
||||
{
|
||||
if (track.Points.Count < 2)
|
||||
@@ -151,17 +152,11 @@ public sealed class MapView : Control
|
||||
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));
|
||||
_switchWays.Add((track.Index, track.Branch, track.Points));
|
||||
}
|
||||
else
|
||||
Polyline(g, 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,7 +806,12 @@ public sealed class MapView : Control
|
||||
_centerX = _dragCenter.X + moved.X / _scale;
|
||||
_centerZ = _dragCenter.Z + moved.Y / _scale;
|
||||
}
|
||||
InvalidateVisual();
|
||||
return;
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
|
||||
47
Eu07.BlackBox.Views/MarkGrid.cs
Normal file
47
Eu07.BlackBox.Views/MarkGrid.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
184
Eu07.BlackBox.Views/TrackLayer.cs
Normal file
184
Eu07.BlackBox.Views/TrackLayer.cs
Normal 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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -366,8 +366,12 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit
|
||||
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
||||
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
||||
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
|
||||
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null)
|
||||
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null,
|
||||
float? WheelSpeedKmh = null)
|
||||
{
|
||||
// WheelSpeedKmh: the speed of the wheels as they turn, which the speedometer shows, signed as SpeedKmh; apart
|
||||
// from it while they slip, 0 while they are locked in a skid. None in a recording made before it.
|
||||
|
||||
public bool Has(CabDevices device) => (Devices & device) == device;
|
||||
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
||||
|
||||
@@ -386,6 +390,26 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit
|
||||
/// </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);
|
||||
|
||||
@@ -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++)
|
||||
|
||||
404
StarterNG.Tests/BinaryTerrainFilesTests.cs
Normal file
404
StarterNG.Tests/BinaryTerrainFilesTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
49
StarterNG.Tests/BlackBox/CabDoorsTests.cs
Normal file
49
StarterNG.Tests/BlackBox/CabDoorsTests.cs
Normal 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"));
|
||||
}
|
||||
}
|
||||
67
StarterNG.Tests/BlackBox/MarkGridTests.cs
Normal file
67
StarterNG.Tests/BlackBox/MarkGridTests.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
79
StarterNG.Tests/BlackBox/TrackLayerTests.cs
Normal file
79
StarterNG.Tests/BlackBox/TrackLayerTests.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
55
StarterNG.Tests/ColumnLineTests.cs
Normal file
55
StarterNG.Tests/ColumnLineTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
68
StarterNG.Tests/ConsistRunsTests.cs
Normal file
68
StarterNG.Tests/ConsistRunsTests.cs
Normal 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));
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
158
StarterNG.Tests/ExternalIniTests.cs
Normal file
158
StarterNG.Tests/ExternalIniTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
29
StarterNG.Tests/Fakes/ForwardOnlyStream.cs
Normal file
29
StarterNG.Tests/Fakes/ForwardOnlyStream.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
s.IgnoreIrrelevantTrains = true;
|
||||
level.ApplyTo(s);
|
||||
Assert.True(s.IgnoreIrrelevantTrains, level.NameKey);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
96
StarterNG.Tests/HaslerTapeWindowTests.cs
Normal file
96
StarterNG.Tests/HaslerTapeWindowTests.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
87
StarterNG.Tests/MessageBoxTests.cs
Normal file
87
StarterNG.Tests/MessageBoxTests.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
139
StarterNG.Tests/MonitorsTests.cs
Normal file
139
StarterNG.Tests/MonitorsTests.cs
Normal 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")));
|
||||
}
|
||||
}
|
||||
132
StarterNG.Tests/OldStarterWarehouseTests.cs
Normal file
132
StarterNG.Tests/OldStarterWarehouseTests.cs
Normal 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"));
|
||||
}
|
||||
}
|
||||
17
StarterNG.Tests/RenderersTests.cs
Normal file
17
StarterNG.Tests/RenderersTests.cs
Normal 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));
|
||||
}
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
39
StarterNG.Tests/SettingsFirstStartTests.cs
Normal file
39
StarterNG.Tests/SettingsFirstStartTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
54
StarterNG.Tests/SliderStepsTests.cs
Normal file
54
StarterNG.Tests/SliderStepsTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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 =>
|
||||
{
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 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());
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,10 +177,14 @@ public sealed class SettingsStore
|
||||
{
|
||||
if (_files.FileExists(path))
|
||||
{
|
||||
var mode = KeepMode();
|
||||
LoadFrom(path);
|
||||
if (!LoadFailed)
|
||||
{
|
||||
mode();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (LoadFailed)
|
||||
Load();
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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++)
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
|
||||
42
StarterNG/Domain/ConsistRuns.cs
Normal file
42
StarterNG/Domain/ConsistRuns.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,7 +168,6 @@ public sealed record GraphicsPreset(
|
||||
s.MaxTextureSize = TextureSize;
|
||||
s.MaxCabTextureSize = CabTextureSize;
|
||||
s.TextureFiltering = Anisotropy;
|
||||
if (!GraphicsRules.IsDlss(s.AntiAliasing))
|
||||
s.AntiAliasing = AntiAliasing;
|
||||
s.CabShadowsRange = CabShadowsRange;
|
||||
s.DynamicLights = DynamicLights;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
14
StarterNG/Domain/Settings/Renderers.cs
Normal file
14
StarterNG/Domain/Settings/Renderers.cs
Normal 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
|
||||
};
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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"),
|
||||
|
||||
@@ -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" };
|
||||
|
||||
31
StarterNG/Domain/Settings/SliderRanges.cs
Normal file
31
StarterNG/Domain/Settings/SliderRanges.cs
Normal 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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security));
|
||||
}
|
||||
|
||||
var sample = new TapeSample(time, speed, distance, brake, pipe, current, security);
|
||||
samples.Add(sample);
|
||||
previous = sample;
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 ?? "");
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
222
StarterNG/Infrastructure/Monitors.cs
Normal file
222
StarterNG/Infrastructure/Monitors.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
474
StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs
Normal file
474
StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs
Normal 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);
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,27 +392,74 @@ 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
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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,
|
||||
@@ -448,34 +467,6 @@ public sealed class SettingsSerializer
|
||||
_ => 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
|
||||
};
|
||||
}
|
||||
|
||||
private static string AntiAliasingToken(AntiAliasingMode mode) => mode switch
|
||||
{
|
||||
AntiAliasingMode.Msaa2 => "msaax2",
|
||||
AntiAliasingMode.Msaa4 => "msaax4",
|
||||
AntiAliasingMode.Msaa8 => "msaax8",
|
||||
AntiAliasingMode.Taa => "taa",
|
||||
AntiAliasingMode.Dlss => "dlss",
|
||||
AntiAliasingMode.Dlaa => "dlaa",
|
||||
_ => "off"
|
||||
};
|
||||
|
||||
private static int MultisamplingLevel(AntiAliasingMode mode) => mode switch
|
||||
{
|
||||
AntiAliasingMode.Msaa2 => 1,
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -103,6 +104,9 @@ 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 += (_, _) =>
|
||||
{
|
||||
|
||||
@@ -507,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"]);
|
||||
@@ -633,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
|
||||
@@ -648,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));
|
||||
@@ -749,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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. -->
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using StarterNG.Application;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
@@ -116,6 +117,8 @@ public sealed class VehicleCards
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
Margin = new Thickness(0, 1, 0, 2)
|
||||
};
|
||||
// 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));
|
||||
|
||||
@@ -692,10 +695,13 @@ public sealed class VehicleCards
|
||||
else if (_consist.CanJoin(item, index))
|
||||
menu.AddItem(App.Loc["TipJoin"], () => _consist.Join(item));
|
||||
|
||||
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"] + "…",
|
||||
|
||||
@@ -280,6 +280,8 @@ public sealed class VehicleDetails
|
||||
};
|
||||
driver.MinWidth = 0;
|
||||
driver.HorizontalAlignment = HorizontalAlignment.Stretch;
|
||||
// Shown but not changed in the standard mode: who drives is for the advanced one.
|
||||
driver.IsEnabled = AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
var rows = new StackPanel();
|
||||
rows.Children.Add(Row(App.Loc["CrewLabel"], driver));
|
||||
|
||||
@@ -62,11 +62,7 @@ public sealed class Warehouse
|
||||
var entry = new ListBoxItem
|
||||
{
|
||||
Tag = preset.Name,
|
||||
Content = new TextBlock
|
||||
{
|
||||
Text = preset.Name,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
}
|
||||
Content = EntryContent(preset.Name, preset.Entry)
|
||||
};
|
||||
_list.Items.Add(entry);
|
||||
if (current is not null && string.Equals(current, preset.Name, StringComparison.Ordinal))
|
||||
@@ -81,6 +77,48 @@ public sealed class Warehouse
|
||||
SelectionChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The consist's name, and under it its vehicles as minis - as the scenery's consists
|
||||
/// are listed - so one is told from another without opening it.
|
||||
/// </summary>
|
||||
private static Control EntryContent(string presetName, string entry)
|
||||
{
|
||||
var name = new TextBlock
|
||||
{
|
||||
Text = presetName,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
if (ConsistText.VehiclesFrom(entry) is not { } vehicles)
|
||||
return name;
|
||||
|
||||
var content = new StackPanel
|
||||
{
|
||||
Spacing = 2,
|
||||
Margin = new Thickness(0, 3),
|
||||
Children = { name, TrainsetRow.ScrollingStrip(vehicles) }
|
||||
};
|
||||
// Read by its name, not by every caption under it.
|
||||
Avalonia.Automation.AutomationProperties.SetName(content, presetName);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Redraws one consist's entry after it was edited and saved, so its minis follow the
|
||||
/// edit at once - the rest of the list, its selection and where it is scrolled stay.
|
||||
/// </summary>
|
||||
public void RefreshEntry(string name, string entry)
|
||||
{
|
||||
foreach (var obj in _list.Items)
|
||||
{
|
||||
if (obj is ListBoxItem { Tag: string tag } item &&
|
||||
string.Equals(tag, name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item.Content = EntryContent(tag, entry);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string? SelectedName() => (_list.SelectedItem as ListBoxItem)?.Tag as string;
|
||||
|
||||
public TrainsetPreset? SelectedPreset() => SelectedName() is { } name ? PresetNamed(name) : null;
|
||||
|
||||
@@ -50,6 +50,98 @@ public static class MessageBox
|
||||
return yes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A warning to read before saying yes: the yes button counts down and only then
|
||||
/// takes a click. Enter and Esc both decline, so nothing is agreed to by habit.
|
||||
/// </summary>
|
||||
public static async Task<bool> ShowDelayed(Window owner, string message, string title, string yesText,
|
||||
int seconds)
|
||||
{
|
||||
var win = FixedDialog(title, 520);
|
||||
|
||||
bool yes = false;
|
||||
var yesBtn = DialogButton($"{yesText} ({seconds})", "Accent", 120, () => { yes = true; win.Close(); });
|
||||
var noBtn = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close());
|
||||
yesBtn.IsEnabled = false;
|
||||
noBtn.IsDefault = true;
|
||||
noBtn.IsCancel = true;
|
||||
ReadMessage(win, noBtn, message);
|
||||
|
||||
int left = seconds;
|
||||
var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
// Only time spent with the warning in front of the player counts: the window active and all of it on a screen.
|
||||
if (!win.IsActive || win.WindowState == WindowState.Minimized || !WhollyOnScreen(win))
|
||||
return;
|
||||
left--;
|
||||
if (left > 0)
|
||||
{
|
||||
yesBtn.Content = $"{yesText} ({left})";
|
||||
return;
|
||||
}
|
||||
timer.Stop();
|
||||
yesBtn.Content = yesText;
|
||||
yesBtn.IsEnabled = true;
|
||||
};
|
||||
win.Closed += (_, _) => timer.Stop();
|
||||
|
||||
win.Content = new StackPanel
|
||||
{
|
||||
Margin = new Avalonia.Thickness(16),
|
||||
Spacing = 16,
|
||||
Children =
|
||||
{
|
||||
new SelectableTextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
|
||||
ButtonRow(yesBtn, noBtn)
|
||||
}
|
||||
};
|
||||
|
||||
timer.Start();
|
||||
await win.ShowDialog(owner);
|
||||
return yes;
|
||||
}
|
||||
|
||||
/// <summary>Whether the whole window, frame and all, lies within the working area of one screen.</summary>
|
||||
internal static bool WhollyOnScreen(Window win)
|
||||
{
|
||||
var size = win.FrameSize ?? win.ClientSize;
|
||||
var rect = new Avalonia.PixelRect(win.Position, Avalonia.PixelSize.FromSize(size, win.RenderScaling));
|
||||
foreach (var screen in win.Screens.All)
|
||||
if (screen.WorkingArea.Contains(rect))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A question with two answers and a way back: true for the first, false for the second, null when cancelled
|
||||
/// or the window is closed - closing it never picks one of the answers.
|
||||
/// </summary>
|
||||
public static async Task<bool?> Choose(Window owner, string message, string title, string firstText,
|
||||
string secondText)
|
||||
{
|
||||
var win = FixedDialog(title, 460);
|
||||
|
||||
bool? answer = null;
|
||||
var first = DialogButton(firstText, "Accent", 80, () => { answer = true; win.Close(); });
|
||||
var second = DialogButton(secondText, "Flat", 80, () => { answer = false; win.Close(); });
|
||||
var cancel = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close());
|
||||
|
||||
win.Content = new StackPanel
|
||||
{
|
||||
Margin = new Avalonia.Thickness(16),
|
||||
Spacing = 16,
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
|
||||
ButtonRow(first, second, cancel)
|
||||
}
|
||||
};
|
||||
|
||||
await win.ShowDialog(owner);
|
||||
return answer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A notice with one action besides closing it, and a box to stop it coming
|
||||
/// back, which counts however the window is closed.
|
||||
|
||||
@@ -45,6 +45,8 @@
|
||||
Header="{Binding [ReloadSceneries], Source={x:Static starterNg:App.Loc}}" />
|
||||
<MenuItem Click="OpenSceneryDir_OnClick"
|
||||
Header="{Binding [OpenSceneryFolder], Source={x:Static starterNg:App.Loc}}" />
|
||||
<MenuItem Name="deleteSbtMenuItem" Click="DeleteSbt_OnClick"
|
||||
Header="{Binding [DeleteSbt], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ContextMenu>
|
||||
</TreeView.ContextMenu>
|
||||
</TreeView>
|
||||
|
||||
@@ -45,6 +45,7 @@ public partial class Scenarios : UserControl
|
||||
{
|
||||
InitializeComponent();
|
||||
SyncConsistRowHeight();
|
||||
Settings.AdvancedModeChanged += OnAdvancedModeChanged;
|
||||
|
||||
Sceneries = AppServices.Current.Library.Sceneries;
|
||||
|
||||
@@ -86,6 +87,43 @@ public partial class Scenarios : UserControl
|
||||
state.StartingVehicleName = vehicle;
|
||||
}
|
||||
|
||||
private void OnAdvancedModeChanged()
|
||||
{
|
||||
RefreshVehicleList();
|
||||
RefreshFaultMarks(sceneryList.Items);
|
||||
if (SelectedScenery is { } scenery)
|
||||
PopulateFaults(scenery);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scenery files' mistakes - written wrong, or vehicles the simulator will not
|
||||
/// find - are for those who mend sceneries: shown in the advanced mode only.
|
||||
/// </summary>
|
||||
private static bool ShowsFaults => AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
// The tree's marks put on or taken off where they stand, the selection and what is
|
||||
// unfolded kept.
|
||||
private void RefreshFaultMarks(ItemCollection items)
|
||||
{
|
||||
foreach (var obj in items)
|
||||
{
|
||||
if (obj is not TreeViewItem node)
|
||||
continue;
|
||||
if (node.Tag is int index && index < Sceneries.Count)
|
||||
{
|
||||
string? label = node.Header switch
|
||||
{
|
||||
string text => text,
|
||||
StackPanel { Children: [TextBlock name, ..] } => name.Text,
|
||||
_ => null
|
||||
};
|
||||
if (label is not null)
|
||||
node.Header = SceneryHeader(label, Sceneries[index]);
|
||||
}
|
||||
RefreshFaultMarks(node.Items);
|
||||
}
|
||||
}
|
||||
|
||||
private void BuildSceneryTree()
|
||||
{
|
||||
sceneryList.Items.Clear();
|
||||
@@ -119,7 +157,7 @@ public partial class Scenarios : UserControl
|
||||
/// <summary>The scenery's name, marked when its files hold mistakes.</summary>
|
||||
private object SceneryHeader(string label, Scenery scenery)
|
||||
{
|
||||
if (scenery.Faults.Count == 0)
|
||||
if (!ShowsFaults || scenery.Faults.Count == 0)
|
||||
return label;
|
||||
|
||||
var mark = new Material.Icons.Avalonia.MaterialIcon
|
||||
@@ -165,6 +203,39 @@ public partial class Scenarios : UserControl
|
||||
favoriteMenuItem.Header = App.Loc[scenery is not null && AppServices.Current.Favorites.Contains(scenery)
|
||||
? "FavoriteRemove"
|
||||
: "FavoriteAdd"];
|
||||
deleteSbtMenuItem.IsEnabled = scenery is not null
|
||||
&& !AppServices.Current.State.SimulatorRunning
|
||||
&& AppServices.Current.BinaryTerrain.Of(scenery.Path) is not null;
|
||||
}
|
||||
|
||||
// Only a file the simulator can make again from the scenery's text goes: one
|
||||
// standing in for terrain files the installation lacks takes the terrain with it.
|
||||
private async void DeleteSbt_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (SelectedScenery is not { } scenery || TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
|
||||
var sbt = AppServices.Current.BinaryTerrain;
|
||||
if (sbt.Of(scenery.Path) is not { } file)
|
||||
return;
|
||||
|
||||
string name = Path.GetFileName(file);
|
||||
string title = App.Loc["DeleteSbt"];
|
||||
if (await Task.Run(() => sbt.MissingOriginal(scenery.Path)) is { } missing)
|
||||
{
|
||||
await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtNoOriginal"], name, missing), title,
|
||||
MessageBoxButtons.Ok);
|
||||
return;
|
||||
}
|
||||
|
||||
long megabytes = AppServices.Current.Files.GetFileSize(file) / (1024 * 1024);
|
||||
if (!await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtConfirm"], name, megabytes), title,
|
||||
MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// Gone, the scenery follows by the watch on its files, as it would after any other change.
|
||||
if (!await Task.Run(() => sbt.Delete(scenery.Path)))
|
||||
await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtFailed"], name), title, MessageBoxButtons.Ok);
|
||||
}
|
||||
|
||||
private void ToggleFavorite_OnClick(object? sender, RoutedEventArgs e)
|
||||
@@ -257,20 +328,13 @@ public partial class Scenarios : UserControl
|
||||
}
|
||||
|
||||
/// <summary>A consist's label in a list of them, here and on the depot page.</summary>
|
||||
internal static TextBlock TrainsetListContent(Trainset trainset) =>
|
||||
new Avalonia.Controls.TextBlock
|
||||
{
|
||||
Text = TrainsetDisplay.ListLabel(trainset),
|
||||
TextTrimming = Avalonia.Media.TextTrimming.CharacterEllipsis,
|
||||
TextWrapping = Avalonia.Media.TextWrapping.NoWrap
|
||||
};
|
||||
internal static Control TrainsetListContent(Trainset trainset) => TrainsetRow.Build(trainset);
|
||||
|
||||
private void PopulateVehicleList(Scenery scn)
|
||||
{
|
||||
vehicleList.Items.Clear();
|
||||
|
||||
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
|
||||
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
|
||||
var settings = AppServices.Current.Settings;
|
||||
var current = AppServices.Current.State.CurrentTrainset;
|
||||
ListBoxItem? currentRow = null;
|
||||
|
||||
@@ -278,7 +342,7 @@ public partial class Scenarios : UserControl
|
||||
{
|
||||
var trainset = scn.Trainsets[i];
|
||||
|
||||
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, current)) continue;
|
||||
if (!TrainsetDisplay.ListedIn(trainset, settings, current)) continue;
|
||||
|
||||
var listItem = new ListBoxItem
|
||||
{
|
||||
@@ -441,8 +505,9 @@ public partial class Scenarios : UserControl
|
||||
private void PopulateFaults(Scenery scenery)
|
||||
{
|
||||
var faults = scenery.Faults;
|
||||
faultsTab.IsVisible = faults.Count > 0;
|
||||
if (faults.Count == 0)
|
||||
bool shown = ShowsFaults && faults.Count > 0;
|
||||
faultsTab.IsVisible = shown;
|
||||
if (!shown)
|
||||
{
|
||||
if (infoTabs.SelectedItem == faultsTab)
|
||||
infoTabs.SelectedIndex = 0;
|
||||
@@ -1015,6 +1080,11 @@ public partial class Scenarios : UserControl
|
||||
});
|
||||
|
||||
var db = AppServices.Current.Library.Vehicles;
|
||||
// The start goes by the vehicle's name, so of several named alike only the first is the one marked.
|
||||
string? picked = AppServices.Current.State.StartingVehicleName;
|
||||
var pickedVehicle = string.IsNullOrEmpty(picked)
|
||||
? null
|
||||
: trainset.Vehicles.FirstOrDefault(v => string.Equals(v.Name, picked, StringComparison.OrdinalIgnoreCase));
|
||||
foreach (var train in trainset.Vehicles)
|
||||
{
|
||||
|
||||
@@ -1036,9 +1106,7 @@ public partial class Scenarios : UserControl
|
||||
})
|
||||
: MiniTextures.MissingVisual(train.SkinFile, thumbH);
|
||||
|
||||
bool selected = !string.IsNullOrEmpty(train.Name) &&
|
||||
string.Equals(train.Name, AppServices.Current.State.StartingVehicleName,
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
bool selected = ReferenceEquals(train, pickedVehicle);
|
||||
// The vehicle started in gets a frame over its picture as well as the lines above and below:
|
||||
// two thin lines alone were hard to see. Drawn over the picture, it moves no vehicle aside.
|
||||
if (selected)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
@@ -29,49 +28,11 @@ internal static class SettingTexts
|
||||
AntiAliasingMode.Msaa2 => "MSAA x2",
|
||||
AntiAliasingMode.Msaa4 => "MSAA x4",
|
||||
AntiAliasingMode.Msaa8 => "MSAA x8",
|
||||
AntiAliasingMode.Taa => App.Loc["AaTaa"],
|
||||
AntiAliasingMode.Dlss => App.Loc["AaDlss"],
|
||||
AntiAliasingMode.Dlaa => App.Loc["AaDlaa"],
|
||||
_ => App.Loc["MsaaNone"]
|
||||
};
|
||||
|
||||
private static string Level(int level) => App.Loc[level switch
|
||||
{
|
||||
1 => "LevelLow",
|
||||
2 => "LevelMedium",
|
||||
3 => "LevelHigh",
|
||||
4 => "LevelUltra",
|
||||
_ => "LevelOff"
|
||||
}];
|
||||
|
||||
public static string TwoDecimals(double value) => value.ToString("0.00", CultureInfo.CurrentCulture);
|
||||
|
||||
public static string ShadowMapWord(int pixels) => pixels switch
|
||||
{
|
||||
<= 512 => App.Loc["QualityVeryLow"],
|
||||
<= 1024 => App.Loc["QualityLow"],
|
||||
<= 2048 => App.Loc["QualityModerate"],
|
||||
<= 4096 => App.Loc["QualityHigh"],
|
||||
_ => App.Loc["QualityVeryHigh"]
|
||||
};
|
||||
|
||||
public static string ShadowRangeWord(int metres) => metres switch
|
||||
{
|
||||
<= 100 => App.Loc["RangeLow"],
|
||||
<= 150 => App.Loc["RangeModerate"],
|
||||
<= 250 => App.Loc["RangeHigh"],
|
||||
_ => App.Loc["RangeVeryHigh"]
|
||||
};
|
||||
|
||||
public static string CabShadowRangeWord(int metres) => metres switch
|
||||
{
|
||||
<= 10 => App.Loc["RangeVeryLow"],
|
||||
<= 20 => App.Loc["RangeLow"],
|
||||
<= 30 => App.Loc["RangeStandard"],
|
||||
<= 50 => App.Loc["RangeHigh"],
|
||||
_ => App.Loc["RangeVeryHigh"]
|
||||
};
|
||||
|
||||
/// <summary>A rate below one a second reads better as the time between updates.</summary>
|
||||
public static string ReflectionsInterval(double perSecond)
|
||||
{
|
||||
@@ -82,72 +43,4 @@ internal static class SettingTexts
|
||||
? string.Format(App.Loc["EveryMinutes"], (seconds / 60).ToString("0.#", CultureInfo.CurrentCulture))
|
||||
: string.Format(App.Loc["EverySeconds"], seconds.ToString("0.#", CultureInfo.CurrentCulture));
|
||||
}
|
||||
|
||||
/// <summary>What a level sets, in the words and the units of the rows it sets.</summary>
|
||||
public static string PresetSummary(GraphicsPreset p)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
void Add(string label, string value) => lines.Add(App.Loc[label] + ": " + value);
|
||||
string YesNo(bool on) => App.Loc[on ? "Yes" : "No"];
|
||||
string Whole(double value) => value.ToString("0.#", CultureInfo.CurrentCulture);
|
||||
|
||||
Add("MaxTexResolution", p.TextureSize + " px");
|
||||
Add("MaxTexCabResolution", p.CabTextureSize + " px");
|
||||
Add("TexFilteringQuality", Anisotropy(p.Anisotropy));
|
||||
Add("AntiAliasing", AntiAliasing(p.AntiAliasing));
|
||||
Add("DynamicLights", p.DynamicLights.ToString(CultureInfo.CurrentCulture));
|
||||
Add("SmokeParticlesMultiplier", Fidelity(p.SmokeFidelity));
|
||||
Add("RenderShadows", YesNo(p.Shadows));
|
||||
if (p.Shadows)
|
||||
{
|
||||
Add("ShadowsResolution", p.ShadowMap + " px");
|
||||
Add("ShaderRange", SimulatorSettings.ShadowReach(p.ShadowRange, p.ShadowMap, legacyRenderer: false) + " m");
|
||||
Add("ShadowDisplay", App.Loc[p.ShadowRank switch { 1 => "CSROnlyImportant", 2 => "CSRLimited", _ => "CSRAll" }]);
|
||||
}
|
||||
Add("ReflectionsCubeMap", YesNo(p.EnvMap));
|
||||
if (p.EnvMap)
|
||||
{
|
||||
Add("ReflectionsDetails", App.Loc[p.ReflectionsFidelity switch { 0 => "RDTerrain", 1 => "RDTerrainModels", _ => "RDTerrainModelsVehicles" }]);
|
||||
Add("ReflectionsFramerate", ReflectionsInterval(p.ReflectionsRate));
|
||||
}
|
||||
Add("AdditionalShadersEffects", YesNo(p.ExtraEffects));
|
||||
Add("TrackCurvesQuality", Fidelity(p.SplineFidelity));
|
||||
Add("Ini.basedrawrange", Whole(p.DrawRange) + " m");
|
||||
Add("Ini.heightbase", "×" + p.DistanceFactor.ToString("0.##", CultureInfo.CurrentCulture));
|
||||
Add("BufforResolution", p.BufferScale + "%");
|
||||
Add("Ini." + GraphicsPreset.SleeperKey, Whole(p.SleeperDistance) + " m");
|
||||
Add("RenderRange", "×" + Whole(p.DrawRangeFactor));
|
||||
Add("Ini." + GraphicsPreset.ReflectedInstancesKey, Whole(p.ReflectedInstances) + " m");
|
||||
Add("Ini." + GraphicsPreset.ReflectedVehiclesKey, Whole(p.ReflectedVehicles) + " m");
|
||||
|
||||
var renderer = p.NewRenderer;
|
||||
Add("LightShadows", Level(renderer.LampShadows));
|
||||
Add("ContactShadows", Level(renderer.ContactShadows));
|
||||
Add("AmbientOcclusion", renderer.Occlusion switch { 1 => "SSAO", 2 => "GTAO", _ => App.Loc["LevelOff"] });
|
||||
Add("CabProbe", Level(renderer.CabProbe));
|
||||
Add("Ssr", Level(renderer.ScreenReflections));
|
||||
Add("RayTracing", YesNo(renderer.RayTracing));
|
||||
Add("VolumetricFog", renderer.VolumetricFog ? Level(renderer.FogQuality) : App.Loc["No"]);
|
||||
Add("Clouds", Level(renderer.Clouds));
|
||||
Add("Grass", renderer.Grass ? renderer.GrassDistance + " m" : App.Loc["No"]);
|
||||
Add("Bloom", YesNo(renderer.Bloom));
|
||||
|
||||
if (p.Extras is { } extras)
|
||||
{
|
||||
Add("MotionBlur", YesNo(extras.MotionBlur));
|
||||
Add("ChromaticAberration", YesNo(extras.ChromaticAberration));
|
||||
Add("SmokeDisplay", YesNo(extras.Smoke));
|
||||
Add("PyScreenPriority", App.Loc[extras.PythonUpdateMs <= 200 ? "PyPriorityNormal" : "PyPriorityLowest"]);
|
||||
}
|
||||
if (p.Top is { } top)
|
||||
{
|
||||
lines.Insert(0, App.Loc["PresetUltraNote"]);
|
||||
Add("ShadowAngleLimit", TwoDecimals(top.ShadowAngleLimit));
|
||||
Add("Ini." + GraphicsTop.TargetFpsKey, YesNo(top.TargetFps > 0));
|
||||
Add("Ini." + GraphicsTop.TextureReleaseKey, YesNo(top.TextureRelease > 0));
|
||||
Add("CompressTextures", YesNo(top.CompressTextures));
|
||||
Add("IgnoreIrrelevantTrains", YesNo(top.SkipDecor));
|
||||
}
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,17 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Domain.Settings;
|
||||
using StarterNG.Infrastructure;
|
||||
|
||||
namespace StarterNG.Views;
|
||||
|
||||
// What the graphics and effects categories add to the screen: the controls of the settings the
|
||||
// new renderers read, the dependencies between them (what the simulator only does on Vulkan,
|
||||
// with DLSS, ...), and the import and export of eu07.ini.
|
||||
// What the graphics and effects categories add to the screen: the renderer and the
|
||||
// anti-aliasing, and the import and export of eu07.ini.
|
||||
public partial class Settings
|
||||
{
|
||||
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
|
||||
@@ -24,264 +23,113 @@ public partial class Settings
|
||||
new("*") { Patterns = new[] { "*" } }
|
||||
};
|
||||
|
||||
/// <summary>Set while the dependencies are brought in line, so the changes they make do not recurse.</summary>
|
||||
private bool _updatingGraphics;
|
||||
|
||||
/// <summary>
|
||||
/// What only Vulkan has, as it was when OpenGL got chosen, so that going back to
|
||||
/// Vulkan brings it back instead of leaving it switched off.
|
||||
/// </summary>
|
||||
private (AntiAliasingMode AntiAliasing, int FrameGeneration, int Reflex, bool RayTracing)? _vulkanChoices;
|
||||
|
||||
private string? _dlssProbedFor;
|
||||
private (bool Dlss, bool FrameGeneration) _dlssProbe;
|
||||
|
||||
private static bool DlssPlatform => AppServices.Current.SettingsStore.DlssPlatform;
|
||||
|
||||
private void InitGraphics()
|
||||
{
|
||||
// The notes are worked out here, not bound, so they follow a change of language by hand.
|
||||
App.Loc.LanguageChanged += UpdateGraphicsState;
|
||||
SelectExeCb.SelectionChanged += (_, _) => UpdateGraphicsState();
|
||||
}
|
||||
|
||||
private void ShowGraphics(SimulatorSettings s)
|
||||
{
|
||||
RenderEngineCb.SelectedIndex = s.RenderEngine;
|
||||
VulkanDeviceTb.Text = s.VulkanDevice;
|
||||
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
|
||||
SelectTag(DlssPresetCb, s.DlssPreset);
|
||||
SelectTag(FrameGenerationCb, s.FrameGeneration.ToString(Invariant));
|
||||
SelectTag(ReflexCb, s.Reflex.ToString(Invariant));
|
||||
|
||||
ShadowSdsmCb.IsChecked = s.ShadowSdsm;
|
||||
LightsClusteredCb.IsChecked = s.LightsClustered;
|
||||
SelectTag(LightShadowsCb, s.LightShadows.ToString(Invariant));
|
||||
SelectTag(ContactShadowsCb, s.ContactShadows.ToString(Invariant));
|
||||
SelectTag(AmbientOcclusionCb, s.AmbientOcclusion.ToString(Invariant));
|
||||
SelectOrAddTag(AoQualityCb, $"{s.AoSlices} {s.AoSteps}", $"{s.AoSlices} / {s.AoSteps}");
|
||||
AoLightingCb.IsChecked = s.AoLighting;
|
||||
SelectTag(CabProbeCb, s.CabProbe.ToString(Invariant));
|
||||
CabProbeIntervalNud.Value = s.CabProbeInterval;
|
||||
CabProbeBounceSlider.Value = s.CabProbeBounce;
|
||||
CabProbeReflectionsCb.IsChecked = s.CabProbeReflections;
|
||||
|
||||
SelectTag(SsrCb, s.Ssr.ToString(Invariant));
|
||||
RayTracingCb.IsChecked = s.RayTracing;
|
||||
RayTracingRangeSlider.Value = s.RayTracingRange;
|
||||
|
||||
VolumetricFogCb.IsChecked = s.VolumetricFog;
|
||||
SelectTag(FogQualityCb, s.FogQuality.ToString(Invariant));
|
||||
SelectTag(CloudsCb, s.Clouds.ToString(Invariant));
|
||||
CloudShadowsCb.IsChecked = s.CloudShadows;
|
||||
|
||||
BloomCb.IsChecked = s.Bloom;
|
||||
AutoExposureCb.IsChecked = s.AutoExposure;
|
||||
|
||||
GrassCb.IsChecked = s.Grass;
|
||||
GrassDistanceSlider.Value = s.GrassDistance;
|
||||
GrassDensitySlider.Value = s.GrassDensity;
|
||||
string particles = s.PrecipitationParticles.ToString(Invariant);
|
||||
SelectOrAddTag(PrecipitationCb, particles, particles);
|
||||
_fullscreenAsRead = s.Fullscreen;
|
||||
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
|
||||
ShowMonitor(s.FullscreenMonitor);
|
||||
UpdateDisplayRows();
|
||||
}
|
||||
|
||||
private void CaptureGraphics(SimulatorSettings s)
|
||||
{
|
||||
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
|
||||
s.VulkanDevice = VulkanDeviceTb.Text?.Trim() ?? "";
|
||||
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
|
||||
s.DlssPreset = SelectedTag(DlssPresetCb) ?? "default";
|
||||
s.FrameGeneration = TagInt(FrameGenerationCb, 1);
|
||||
s.Reflex = TagInt(ReflexCb, 0);
|
||||
s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
|
||||
|
||||
s.ShadowSdsm = IsChecked(ShadowSdsmCb);
|
||||
s.LightsClustered = IsChecked(LightsClusteredCb);
|
||||
s.LightShadows = TagInt(LightShadowsCb, 2);
|
||||
s.ContactShadows = TagInt(ContactShadowsCb, 0);
|
||||
s.AmbientOcclusion = TagInt(AmbientOcclusionCb, 2);
|
||||
var ao = (SelectedTag(AoQualityCb) ?? "3 4").Split(' ');
|
||||
s.AoSlices = ao.Length > 0 && int.TryParse(ao[0], NumberStyles.Integer, Invariant, out int slices) ? slices : 3;
|
||||
s.AoSteps = ao.Length > 1 && int.TryParse(ao[1], NumberStyles.Integer, Invariant, out int steps) ? steps : 4;
|
||||
s.AoLighting = IsChecked(AoLightingCb);
|
||||
s.CabProbe = TagInt(CabProbeCb, 2);
|
||||
s.CabProbeInterval = (int)(CabProbeIntervalNud.Value ?? 4);
|
||||
s.CabProbeBounce = CabProbeBounceSlider.Value;
|
||||
s.CabProbeReflections = IsChecked(CabProbeReflectionsCb);
|
||||
|
||||
s.Ssr = TagInt(SsrCb, 2);
|
||||
s.RayTracing = IsChecked(RayTracingCb);
|
||||
s.RayTracingRange = (int)RayTracingRangeSlider.Value;
|
||||
|
||||
s.VolumetricFog = IsChecked(VolumetricFogCb);
|
||||
s.FogQuality = TagInt(FogQualityCb, 2);
|
||||
s.Clouds = TagInt(CloudsCb, 2);
|
||||
s.CloudShadows = IsChecked(CloudShadowsCb);
|
||||
|
||||
s.Bloom = IsChecked(BloomCb);
|
||||
s.AutoExposure = IsChecked(AutoExposureCb);
|
||||
|
||||
s.Grass = IsChecked(GrassCb);
|
||||
s.GrassDistance = (int)GrassDistanceSlider.Value;
|
||||
s.GrassDensity = GrassDensitySlider.Value;
|
||||
s.PrecipitationParticles = TagInt(PrecipitationCb, 65536);
|
||||
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
|
||||
s.FullscreenWindowed = mode == BorderlessMode;
|
||||
// Borderless overrides fullscreen in the simulator, so the file's own word for it stays.
|
||||
s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode;
|
||||
}
|
||||
|
||||
private void OnBackendChanged()
|
||||
{
|
||||
if (_loading || _updatingGraphics)
|
||||
return;
|
||||
// ── How the simulator shows: full screen, borderless or in a window ──────
|
||||
|
||||
_updatingGraphics = true;
|
||||
try
|
||||
private const string FullscreenMode = "fullscreen";
|
||||
private const string BorderlessMode = "borderless";
|
||||
private const string WindowMode = "window";
|
||||
|
||||
/// <summary>fullscreen as the file has it, kept where borderless makes it of no account.</summary>
|
||||
private bool _fullscreenAsRead;
|
||||
|
||||
/// <summary>
|
||||
/// The mode the two keys make (application.cpp): fullscreenwindowed takes the monitor's
|
||||
/// own size and turns full screen on whatever fullscreen says.
|
||||
/// </summary>
|
||||
private static string DisplayModeOf(bool fullscreen, bool windowed) =>
|
||||
windowed ? BorderlessMode : fullscreen ? FullscreenMode : WindowMode;
|
||||
|
||||
/// <summary>A borderless screen takes the monitor's size; a window can't be put on a monitor.</summary>
|
||||
private void UpdateDisplayRows()
|
||||
{
|
||||
if (!SettingReach.IsVulkan(SelectedRenderer()))
|
||||
{
|
||||
var s = Trial();
|
||||
_vulkanChoices ??= (s.AntiAliasing, s.FrameGeneration, s.Reflex, s.RayTracing);
|
||||
if (GraphicsRules.IsDlss(s.AntiAliasing))
|
||||
SelectTag(AntiAliasingCb, "taa");
|
||||
FrameGenerationCb.SelectedIndex = 0;
|
||||
ReflexCb.SelectedIndex = 0;
|
||||
RayTracingCb.IsChecked = false;
|
||||
}
|
||||
else if (_vulkanChoices is { } kept)
|
||||
{
|
||||
if (GraphicsRules.IsDlss(kept.AntiAliasing) && DlssPlatform && SelectedTag(AntiAliasingCb) == "taa")
|
||||
SelectTag(AntiAliasingCb, AntiAliasingTag(kept.AntiAliasing));
|
||||
SelectTag(FrameGenerationCb, kept.FrameGeneration.ToString(Invariant));
|
||||
SelectTag(ReflexCb, kept.Reflex.ToString(Invariant));
|
||||
RayTracingCb.IsChecked = kept.RayTracing;
|
||||
_vulkanChoices = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_updatingGraphics = false;
|
||||
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
|
||||
Dim(ResolutionRow, mode == BorderlessMode);
|
||||
Dim(MonitorRow, mode == WindowMode);
|
||||
}
|
||||
|
||||
UpdateGraphicsState();
|
||||
/// <summary>The whole row greyed out, its label and description too, as a disabled check box is.</summary>
|
||||
private static void Dim(Control row, bool off)
|
||||
{
|
||||
row.IsEnabled = !off;
|
||||
row.Opacity = off ? 0.45 : 1;
|
||||
}
|
||||
|
||||
private ComboBoxItem? _primaryMonitorItem;
|
||||
|
||||
private IReadOnlyList<DisplayMonitor>? _monitors;
|
||||
|
||||
/// <summary>The monitors attached, read once.</summary>
|
||||
private IReadOnlyList<DisplayMonitor> MonitorList => _monitors ??= Monitors.List(AppServices.Current.Environment);
|
||||
|
||||
/// <summary>
|
||||
/// The monitor the simulator will show on (application.cpp): a full screen, borderless or
|
||||
/// not, goes to the one chosen, or the primary one when that is not connected; a window
|
||||
/// opens where the system puts it, as a rule the primary one. Null where no monitor could be read.
|
||||
/// </summary>
|
||||
private DisplayMonitor? SimulatorMonitor()
|
||||
{
|
||||
string? chosen = SelectedTag(DisplayModeCb) == WindowMode ? null : SelectedTag(MonitorCb);
|
||||
DisplayMonitor? primary = null;
|
||||
foreach (var m in MonitorList)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(chosen) && m.Id == chosen)
|
||||
return m;
|
||||
if (m.Primary)
|
||||
primary ??= m;
|
||||
}
|
||||
return primary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings the graphics controls in line with one another the way the simulator
|
||||
/// treats them, and says why something is off.
|
||||
/// The monitors found, listed once, with the primary one first; a monitor the file names
|
||||
/// that is not connected now stays on the list under its own name.
|
||||
/// </summary>
|
||||
private void UpdateGraphicsState()
|
||||
private void ShowMonitor(string id)
|
||||
{
|
||||
if (!_built || _loading || _updatingGraphics)
|
||||
return;
|
||||
|
||||
_updatingGraphics = true;
|
||||
try
|
||||
if (_primaryMonitorItem is null)
|
||||
{
|
||||
var s = Trial();
|
||||
bool vulkan = GraphicsRules.IsVulkan(s);
|
||||
bool dlssAllowed = GraphicsRules.DlssAllowed(s, DlssPlatform);
|
||||
|
||||
foreach (var item in AntiAliasingCb.Items.OfType<ComboBoxItem>())
|
||||
if (item.Tag is "dlss" or "dlaa")
|
||||
item.IsEnabled = dlssAllowed;
|
||||
if (GraphicsRules.IsDlss(s.AntiAliasing) && !dlssAllowed)
|
||||
SelectTag(AntiAliasingCb, "taa");
|
||||
|
||||
s = Trial();
|
||||
bool dlss = GraphicsRules.DlssActive(s, DlssPlatform);
|
||||
DlssPresetRow.IsEnabled = dlss;
|
||||
FrameGenerationRow.IsEnabled = dlss;
|
||||
if (!dlss && FrameGenerationCb.SelectedIndex > 0)
|
||||
FrameGenerationCb.SelectedIndex = 0;
|
||||
ReflexRow.IsEnabled = vulkan;
|
||||
if (!vulkan && ReflexCb.SelectedIndex > 0)
|
||||
ReflexCb.SelectedIndex = 0;
|
||||
VulkanDeviceRow.IsEnabled = vulkan;
|
||||
RayTracingRow.IsEnabled = vulkan;
|
||||
if (!vulkan)
|
||||
RayTracingCb.IsChecked = false;
|
||||
|
||||
s = Trial();
|
||||
BufferScaleRow.IsEnabled = GraphicsRules.BufferScaleUsed(s, DlssPlatform);
|
||||
RayTracingRangeRow.IsEnabled = vulkan && s.RayTracing;
|
||||
DynamicLightsRow.IsEnabled = GraphicsRules.DynamicLightsUsed(s);
|
||||
AoQualityRow.IsEnabled = s.AmbientOcclusion > 0;
|
||||
AoLightingRow.IsEnabled = GraphicsRules.AoLightingUsed(s);
|
||||
bool probe = GraphicsRules.CabProbeUsed(s);
|
||||
CabProbeIntervalRow.IsEnabled = probe;
|
||||
CabProbeReflectionsRow.IsEnabled = probe;
|
||||
CabProbeBounceRow.IsEnabled = GraphicsRules.CabProbeLights(s);
|
||||
FogQualityRow.IsEnabled = s.VolumetricFog;
|
||||
CloudShadowsRow.IsEnabled = s.Clouds > 0;
|
||||
GrassDistanceRow.IsEnabled = s.Grass;
|
||||
GrassDensityRow.IsEnabled = s.Grass;
|
||||
|
||||
DlssPresetInfo.Text = App.Loc[(SelectedTag(DlssPresetCb) ?? "default") switch
|
||||
_primaryMonitorItem = new ComboBoxItem { Tag = string.Empty, Content = App.Loc["MonitorPrimary"] };
|
||||
App.Loc.LanguageChanged += () => _primaryMonitorItem.Content = App.Loc["MonitorPrimary"];
|
||||
MonitorCb.Items.Add(_primaryMonitorItem);
|
||||
var monitors = MonitorList;
|
||||
for (int i = 0; i < monitors.Count; i++)
|
||||
{
|
||||
"k" => "DlssPresetInfoK",
|
||||
"j" => "DlssPresetInfoJ",
|
||||
"m" => "DlssPresetInfoM",
|
||||
"l" => "DlssPresetInfoL",
|
||||
_ => "DlssPresetInfoDefault"
|
||||
}];
|
||||
SetNote(RenderEngineNote, App.Loc[vulkan ? "REVulkanNote" : "REOpenGLNote"]);
|
||||
SetNote(AntiAliasingNote, AntiAliasingRemark(s, dlss));
|
||||
SetNote(FrameGenerationNote, FrameGenerationRemark(s, dlss));
|
||||
SetNote(ReflexNote, GraphicsRules.ReflexForced(s, DlssPlatform) ? App.Loc["ReflexForcedNote"] : "");
|
||||
SetNote(AoLightingNote, AoLightingRemark(s));
|
||||
SetNote(CabProbeNote, GraphicsRules.CabProbeUsed(s) && !GraphicsRules.CabProbeLights(s) ? App.Loc["CabProbeReflectionsOnlyNote"] : "");
|
||||
SetNote(SkipPipelineNote, GraphicsRules.TemporalWithoutPipeline(s) ? App.Loc["TemporalNeedsPipelineNote"] : "");
|
||||
}
|
||||
finally
|
||||
var m = monitors[i];
|
||||
MonitorCb.Items.Add(new ComboBoxItem
|
||||
{
|
||||
_updatingGraphics = false;
|
||||
Tag = m.Id,
|
||||
Content = $"{i + 1}. {m.Name} – {m.Width}×{m.Height}"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private string AntiAliasingRemark(SimulatorSettings s, bool dlss)
|
||||
{
|
||||
if (!DlssPlatform && GraphicsRules.IsVulkan(s))
|
||||
return App.Loc["DlssNoPlatformNote"];
|
||||
if (GraphicsRules.TemporalWithoutPipeline(s))
|
||||
return App.Loc["TemporalNeedsPipelineNote"];
|
||||
if (dlss && !DlssLibraries(s).Dlss)
|
||||
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: false));
|
||||
return "";
|
||||
if (IndexOfTag(MonitorCb, id) < 0)
|
||||
MonitorCb.Items.Add(new ComboBoxItem { Tag = id, Content = id });
|
||||
SelectTag(MonitorCb, id);
|
||||
}
|
||||
|
||||
private static string AoLightingRemark(SimulatorSettings s)
|
||||
{
|
||||
if (!GraphicsRules.AoLightingUsed(s) || !s.AoLighting)
|
||||
return "";
|
||||
if (s.SkipPipeline)
|
||||
return App.Loc["AoNeedsPipelineNote"];
|
||||
return GraphicsRules.AoLightingAddsDepthPrepass(s) ? App.Loc["AoLightingPrepassNote"] : "";
|
||||
}
|
||||
|
||||
private string FrameGenerationRemark(SimulatorSettings s, bool dlss)
|
||||
{
|
||||
if (!dlss)
|
||||
return GraphicsRules.IsVulkan(s) ? App.Loc["FrameGenerationNeedsDlssNote"] : "";
|
||||
if (s.FrameGeneration > 1 && !DlssLibraries(s).FrameGeneration)
|
||||
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: true));
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>Looked up once per simulator picked: the search for it reads the installation's directory.</summary>
|
||||
private (bool Dlss, bool FrameGeneration) DlssLibraries(SimulatorSettings s)
|
||||
{
|
||||
string key = s.SelectExeAutomatically ? "\u0001auto" : s.ExecutablePath;
|
||||
if (_dlssProbedFor != key)
|
||||
{
|
||||
var executables = AppServices.Current.Executables;
|
||||
_dlssProbe = executables.DlssLibraries(executables.Resolve(s, out _));
|
||||
_dlssProbedFor = key;
|
||||
}
|
||||
return _dlssProbe;
|
||||
}
|
||||
|
||||
private static string DlssLibraryName(bool frameGeneration) =>
|
||||
AppServices.Current.Environment.IsWindows
|
||||
? (frameGeneration ? "nvngx_dlssg.dll" : "nvngx_dlss.dll")
|
||||
: (frameGeneration ? "libnvidia-ngx-dlssg.so" : "libnvidia-ngx-dlss.so");
|
||||
|
||||
private async void ImportIniButton_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
@@ -303,7 +151,6 @@ public partial class Settings
|
||||
return;
|
||||
}
|
||||
|
||||
_vulkanChoices = null;
|
||||
ApplyToUi();
|
||||
// What came from the other file is a choice to save, not a value the screen could not show.
|
||||
_shownUnlikeSettings = new Dictionary<string, ShownValue>();
|
||||
@@ -328,9 +175,8 @@ public partial class Settings
|
||||
return;
|
||||
|
||||
// The edits on screen go into the export as they would into a save, but the
|
||||
// user's own eu07.ini is not written.
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
if (!AppServices.Current.SettingsStore.ExportTo(path))
|
||||
// user's own eu07.ini is not written, nor the settings held: the edits stay the page's, not saved.
|
||||
if (!AppServices.Current.SettingsStore.ExportTo(path, Trial()))
|
||||
{
|
||||
await MessageBox.Show(owner, string.Format(App.Loc["ExportIniFailed"], path), App.Loc["ExportIni"],
|
||||
MessageBoxButtons.Ok);
|
||||
@@ -338,7 +184,6 @@ public partial class Settings
|
||||
}
|
||||
|
||||
SaveStatus.Text = string.Format(App.Loc["ExportIniDone"], Path.GetFileName(path));
|
||||
ToolTip.SetTip(SaveStatus, path);
|
||||
}
|
||||
|
||||
private static void SetNote(TextBlock note, string text)
|
||||
@@ -376,9 +221,6 @@ public partial class Settings
|
||||
AntiAliasingMode.Msaa2 => "msaax2",
|
||||
AntiAliasingMode.Msaa4 => "msaax4",
|
||||
AntiAliasingMode.Msaa8 => "msaax8",
|
||||
AntiAliasingMode.Taa => "taa",
|
||||
AntiAliasingMode.Dlss => "dlss",
|
||||
AntiAliasingMode.Dlaa => "dlaa",
|
||||
_ => "off"
|
||||
};
|
||||
|
||||
@@ -387,9 +229,6 @@ public partial class Settings
|
||||
"msaax2" => AntiAliasingMode.Msaa2,
|
||||
"msaax4" => AntiAliasingMode.Msaa4,
|
||||
"msaax8" => AntiAliasingMode.Msaa8,
|
||||
"taa" => AntiAliasingMode.Taa,
|
||||
"dlss" => AntiAliasingMode.Dlss,
|
||||
"dlaa" => AntiAliasingMode.Dlaa,
|
||||
_ => AntiAliasingMode.Off
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
<TextBlock x:Name="SaveStatus" ctl:Announcer.Changes="True" VerticalAlignment="Center" Opacity="0.8" Text="" />
|
||||
<Button x:Name="ChangesButton" Classes="Flat" Click="ChangesButton_OnClick"
|
||||
Content="{Binding [IniChangesButton], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="DefaultsButton" Classes="Flat" Click="DefaultsButton_OnClick"
|
||||
Content="{Binding [RestoreDefaults], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="ResetButton" Classes="Flat" Click="ResetButton_OnClick"
|
||||
Content="{Binding [Reset], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="SaveButton" Classes="Flat" Click="SaveButton_OnClick"
|
||||
@@ -44,7 +46,7 @@
|
||||
PlaceholderText="{Binding [Search], Source={x:Static starterNg:App.Loc}}"
|
||||
TextChanged="SettingsSearch_OnTextChanged" />
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
|
||||
<StackPanel x:Name="ProfilePanel" DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
|
||||
<TextBlock Classes="FieldLabel"
|
||||
Text="{Binding [SettingsProfile], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch"
|
||||
@@ -67,6 +69,10 @@
|
||||
HorizontalContentAlignment="Center"
|
||||
Content="{Binding [ExportIni], Source={x:Static starterNg:App.Loc}}"
|
||||
Click="ExportIniButton_OnClick" />
|
||||
<!-- Kept out of the way on purpose: turning it on asks first, at length. -->
|
||||
<Button x:Name="AdvancedModeBtn" Classes="Flat" HorizontalAlignment="Stretch"
|
||||
HorizontalContentAlignment="Center" Margin="0,14,0,0" FontSize="11" Opacity="0.7"
|
||||
Click="AdvancedModeBtn_OnClick" />
|
||||
</StackPanel>
|
||||
|
||||
<ListBox x:Name="CategoryList" AutomationProperties.LandmarkType="Navigation" AutomationProperties.Name="{Binding [SettingsCategories], Source={x:Static starterNg:App.Loc}}" Classes="SettingsNav" SelectedIndex="0"
|
||||
@@ -131,9 +137,6 @@
|
||||
<ComboBox x:Name="ChangeLanguageCb"
|
||||
SelectionChanged="LanguageComboBox_OnSelectionChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fullscreen">
|
||||
<CheckBox x:Name="FullscreenCb" Content="{Binding [Fullscreen], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="inactivepause">
|
||||
<CheckBox x:Name="PauseInactiveCb" Content="{Binding [PauseSimInactive], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -142,8 +145,8 @@
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="mousescale" x:Name="CursorSensitivityRow"
|
||||
Label="{Binding [CursorSensitivity], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="3"
|
||||
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="4" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="2"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="mousescale">
|
||||
@@ -208,17 +211,10 @@
|
||||
<ComboBoxItem Content="{Binding [REFull], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REOld], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [RESimp], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REExperimental], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REVulkan], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="RenderEngineNote" Classes="SettingNote" IsVisible="False" />
|
||||
<!-- Amber like the UART warnings: this one stops the simulator. -->
|
||||
<TextBlock x:Name="RenderEngineWarning" IsVisible="False" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource CarbonAccentBright}"
|
||||
Text="{Binding [REExperimentalWarning], Source={x:Static starterNg:App.Loc}}" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GpuRow" ConfigKey="starter.gpu" Label="{Binding [GpuChoice], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingRow Advanced="True" x:Name="GpuRow" ConfigKey="starter.gpu" Label="{Binding [GpuChoice], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="GpuCb" Classes="Localized" SelectedIndex="0"
|
||||
SelectionChanged="GpuCb_OnSelectionChanged">
|
||||
<ComboBoxItem Content="{Binding [GpuDiscrete], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -231,10 +227,9 @@
|
||||
<ctl:SettingRow ConfigKey="gfx.extraeffects">
|
||||
<CheckBox x:Name="AdditionalShadersCb" Content="{Binding [AdditionalShadersEffects], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.skippipeline" Description="{Binding [SkipPipelineDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingRow ConfigKey="gfx.skippipeline" Advanced="True" Description="{Binding [SkipPipelineDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<CheckBox x:Name="SkipPipelineCb" Content="{Binding [SkipPipeline], Source={x:Static starterNg:App.Loc}}" />
|
||||
<TextBlock x:Name="SkipPipelineNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="usevbo" Description="{Binding [RenderVBODesc], Source={x:Static starterNg:App.Loc}}">
|
||||
@@ -249,17 +244,27 @@
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [GfxColImage], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="width, height" Label="{Binding [Resolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<!-- fullscreen and fullscreenwindowed as the simulator reads them together; see DisplayModeOf. -->
|
||||
<ctl:SettingRow ConfigKey="fullscreen, fullscreenwindowed" Label="{Binding [DisplayMode], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [DisplayModeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="DisplayModeCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="fullscreen" Content="{Binding [DisplayModeFullscreen], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="borderless" Content="{Binding [DisplayModeBorderless], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="window" Content="{Binding [DisplayModeWindow], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="MonitorRow" ConfigKey="fullscreenmonitor" Label="{Binding [FullscreenMonitor], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FullscreenMonitorDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="MonitorCb" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="ResolutionRow" ConfigKey="width, height" Label="{Binding [Resolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="ResolutionCb" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fullscreenwindowed">
|
||||
<CheckBox x:Name="FullscreenWindowedCb" Content="{Binding [FullscreenWindowed], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="BufferScaleRow" ConfigKey="gfx.buffer.percent, starter.bufferscale"
|
||||
<ctl:SettingRow x:Name="BufferScaleRow" Advanced="True" ConfigKey="gfx.framebuffer.width, gfx.framebuffer.height"
|
||||
Label="{Binding [BufforResolution], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [BufforResolutionDesc], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #bufferScale.Value, StringFormat='{}{0:0}%'}">
|
||||
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="100" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="100" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fieldofview" Label="{Binding [FieldOfView], Source={x:Static starterNg:App.Loc}}"
|
||||
@@ -268,7 +273,7 @@
|
||||
<ctl:ReadableSlider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
|
||||
IsSnapToTickEnabled="True" Value="45" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.antialiasing, multisampling"
|
||||
<ctl:SettingRow ConfigKey="multisampling"
|
||||
Label="{Binding [AntiAliasing], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [AntiAliasingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
@@ -277,18 +282,9 @@
|
||||
<ComboBoxItem Tag="msaax2" Content="MSAA x2" />
|
||||
<ComboBoxItem Tag="msaax4" Content="MSAA x4" />
|
||||
<ComboBoxItem Tag="msaax8" Content="MSAA x8" />
|
||||
<ComboBoxItem Tag="taa" Content="{Binding [AaTaa], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="dlss" Content="{Binding [AaDlss], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="dlaa" Content="{Binding [AaDlaa], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="AntiAliasingNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [GfxColSmoothness], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="vsync" Description="{Binding [VSyncDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="VSyncCb" Content="{Binding [VSync], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -296,10 +292,13 @@
|
||||
Label="{Binding [FpsLimit], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FpsLimitDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="4">
|
||||
<!-- Moves through no limit and Steps.FrameRateLimits; see SliderSteps. -->
|
||||
<!-- Moves through no limit and SliderRanges.FrameRateLimits; see SliderSteps. -->
|
||||
<ctl:ReadableSlider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
|
||||
<!-- The screens found, each with a button to match the limit to it. -->
|
||||
<WrapPanel x:Name="MonitorRates" IsVisible="False" />
|
||||
<!-- Shown with VSync on: the limit and VSync together, see UpdateMonitorRates. -->
|
||||
<TextBlock x:Name="FpsVSyncNote" Classes="FieldHint" TextWrapping="Wrap" IsVisible="False"
|
||||
Text="{Binding [FpsVSyncNote], Source={x:Static starterNg:App.Loc}}" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
@@ -331,13 +330,13 @@
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="maxtexturesize" x:Name="TexResolutionRow"
|
||||
Label="{Binding [MaxTexResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="TextureResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="maxcabtexturesize" x:Name="CabTexResolutionRow"
|
||||
Label="{Binding [MaxTexCabResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="12" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="CabTextureResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
@@ -398,7 +397,7 @@
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="shadowtune" x:Name="ShadowResolutionRow"
|
||||
Label="{Binding [ShadowsResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="10" Maximum="13" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="shaderResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
@@ -406,15 +405,15 @@
|
||||
Label="{Binding [ShaderRange], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ShaderRangeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<!-- The simulator's floor follows the map size: see shaderResolutionSlider_OnValueChanged. -->
|
||||
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
|
||||
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="400" TickFrequency="5"
|
||||
IsSnapToTickEnabled="True" Value="150"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadows.cab.range" x:Name="CabShadowRangeRow"
|
||||
Label="{Binding [CabShadowsRange], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabShadowsRangeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
|
||||
IsSnapToTickEnabled="True" Value="30"
|
||||
<!-- Moves through SliderRanges.CabShadowRanges; see SliderSteps. -->
|
||||
<ctl:ReadableSlider Name="cabShaderSourceRange"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadow.angle.min" x:Name="ShadowAngleLimitRow"
|
||||
@@ -422,7 +421,7 @@
|
||||
Description="{Binding [ShadowAngleLimitDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:ReadableSlider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
|
||||
TickFrequency="0.05" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
|
||||
TickFrequency="0.1" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Classes="FieldHint"
|
||||
@@ -435,11 +434,11 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection x:Name="LightsSection" Header="{Binding [GfxColLights], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Header="{Binding [GfxColLights], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow x:Name="DynamicLightsRow" Description="{Binding [DynamicLightsDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="dynamiclights" Label="{Binding [DynamicLights], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #DynamicLightsSlider.Value, StringFormat='{}{0:0}'}">
|
||||
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
|
||||
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="1" Maximum="7" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="7" />
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
@@ -484,7 +483,7 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection x:Name="NatureSection" Header="{Binding [GfxColNature], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Header="{Binding [GfxColNature], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="gfx.smoke" Margin="0,0,0,4">
|
||||
<CheckBox x:Name="SmokeDisplayCb" Content="{Binding [SmokeDisplay], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -554,6 +553,12 @@
|
||||
<ctl:SettingRow ConfigKey="livetraction" Description="{Binding [PowerOverheadLineOnlyDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="OverheadOnlyCb" Content="{Binding [PowerOverheadLineOnly], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveBlackBoxDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="blackbox">
|
||||
<CheckBox x:Name="BlackBoxCb" Content="{Binding [SaveBlackBox], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveTrainTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog.trains">
|
||||
<CheckBox x:Name="TrainTapesCb" Content="{Binding [SaveTrainTapes], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveSpeedometerTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog">
|
||||
<CheckBox x:Name="SpeedometerTapesCb" Content="{Binding [SaveSpeedometerTapes], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -671,7 +676,7 @@
|
||||
<StackPanel Tag="advanced" IsVisible="False">
|
||||
<TextBlock Classes="CategoryCaption" IsVisible="False"
|
||||
Text="{Binding [Advanced], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ctl:SettingsSection Header="{Binding [AdvancedResources], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Advanced="True" Header="{Binding [AdvancedResources], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="compresstex" Description="{Binding [CompressTexturesDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="CompressTexCb" Content="{Binding [CompressTextures], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -709,7 +714,7 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [AdvancedLogTools], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Advanced="True" Header="{Binding [AdvancedLogTools], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow Description="{Binding [OpenLogToolsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<Button x:Name="OpenLogToolsButton" Classes="Flat" Cursor="Hand"
|
||||
@@ -720,198 +725,6 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<!-- What only the new simulator reads; an older one passes over these keys. -->
|
||||
<ctl:SettingsSection Header="{Binding [GfxColNewRenderer], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<TextBlock Classes="SettingNote" Margin="0,0,0,11"
|
||||
Text="{Binding [GfxNewRendererNote], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ctl:SettingRow x:Name="VulkanDeviceRow" ConfigKey="gfx.vulkan.device"
|
||||
Label="{Binding [VulkanDevice], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [VulkanDeviceDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<TextBox x:Name="VulkanDeviceTb" PlaceholderText="{Binding [VulkanDeviceAuto], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="DlssPresetRow" ConfigKey="gfx.dlss.preset"
|
||||
Label="{Binding [DlssPreset], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [DlssPresetDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="DlssPresetCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="default" Content="{Binding [DlssPresetDefault], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="k" Content="{Binding [DlssPresetK], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="j" Content="{Binding [DlssPresetJ], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="m" Content="{Binding [DlssPresetM], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="l" Content="{Binding [DlssPresetL], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="DlssPresetInfo" Classes="FieldHint" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="FrameGenerationRow" ConfigKey="gfx.framegeneration"
|
||||
Label="{Binding [FrameGeneration], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FrameGenerationDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="FrameGenerationCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="x2" />
|
||||
<ComboBoxItem Tag="3" Content="x3" />
|
||||
<ComboBoxItem Tag="4" Content="x4" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="FrameGenerationNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="ReflexRow" ConfigKey="gfx.reflex"
|
||||
Label="{Binding [Reflex], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ReflexDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="ReflexCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [ReflexOn], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [ReflexBoost], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="ReflexNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="RayTracingRow" ConfigKey="gfx.raytracing" Description="{Binding [RayTracingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="RayTracingCb" Content="{Binding [RayTracing], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="RayTracingRangeRow" ConfigKey="gfx.raytracing.range"
|
||||
Label="{Binding [RayTracingRange], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #RayTracingRangeSlider.Value, StringFormat='{}{0:0} m'}">
|
||||
<ctl:ReadableSlider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.ssr" Label="{Binding [Ssr], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [SsrDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="SsrCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.lights.clustered" Description="{Binding [LightsClusteredDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="LightsClusteredCb" Content="{Binding [LightsClustered], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.lights.shadows" Label="{Binding [LightShadows], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [LightShadowsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="LightShadowsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.contactshadows" Label="{Binding [ContactShadows], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ContactShadowsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="ContactShadowsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadow.sdsm" Description="{Binding [ShadowSdsmDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="ShadowSdsmCb" Content="{Binding [ShadowSdsm], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.ao" Label="{Binding [AmbientOcclusion], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [AmbientOcclusionDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="AmbientOcclusionCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="SSAO" />
|
||||
<ComboBoxItem Tag="2" Content="GTAO" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="AoLightingRow" ConfigKey="gfx.postfx.ao.lighting" Description="{Binding [AoLightingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<CheckBox x:Name="AoLightingCb" Content="{Binding [AoLighting], Source={x:Static starterNg:App.Loc}}" />
|
||||
<TextBlock x:Name="AoLightingNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="AoQualityRow" ConfigKey="gfx.postfx.ao.quality" Label="{Binding [AmbientOcclusionQuality], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="AoQualityCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="2 3" Content="{Binding [QualityLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3 4" Content="{Binding [QualityNormal], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4 6" Content="{Binding [QualityHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="6 8" Content="{Binding [QualityVeryHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.cabprobe" Label="{Binding [CabProbe], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabProbeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="CabProbeCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="CabProbeNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeIntervalRow" ConfigKey="gfx.cabprobe.interval"
|
||||
Label="{Binding [CabProbeInterval], Source={x:Static starterNg:App.Loc}}">
|
||||
<NumericUpDown x:Name="CabProbeIntervalNud" Minimum="1" Maximum="120" Value="4" Increment="1" FormatString="0" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeBounceRow" ConfigKey="gfx.cabprobe.bounce"
|
||||
Label="{Binding [CabProbeBounce], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabProbeBounceDesc], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #CabProbeBounceSlider.Value, StringFormat='{}{0:0.0}'}">
|
||||
<ctl:ReadableSlider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeReflectionsRow" ConfigKey="gfx.cabprobe.reflections" Description="{Binding [CabProbeReflectionsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="CabProbeReflectionsCb" Content="{Binding [CabProbeReflections], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.fog" Description="{Binding [VolumetricFogDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="VolumetricFogCb" Content="{Binding [VolumetricFog], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="FogQualityRow" ConfigKey="gfx.fog.quality" Label="{Binding [FogQuality], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="FogQualityCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4" Content="{Binding [LevelUltra], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.clouds" Label="{Binding [Clouds], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CloudsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="CloudsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4" Content="{Binding [LevelUltra], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CloudShadowsRow" ConfigKey="gfx.clouds.shadows">
|
||||
<CheckBox x:Name="CloudShadowsCb" Content="{Binding [CloudShadows], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.bloom">
|
||||
<CheckBox x:Name="BloomCb" Content="{Binding [Bloom], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.autoexposure" Description="{Binding [AutoExposureDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="AutoExposureCb" Content="{Binding [AutoExposure], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.grass" Margin="0,0,0,4">
|
||||
<CheckBox x:Name="GrassCb" Content="{Binding [Grass], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GrassDistanceRow" ConfigKey="gfx.grass.distance, gfx.grass.fadedistance"
|
||||
Label="{Binding [GrassDistance], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #GrassDistanceSlider.Value, StringFormat='{}{0:0} m'}">
|
||||
<ctl:ReadableSlider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GrassDensityRow" ConfigKey="gfx.grass.density"
|
||||
Label="{Binding [GrassDensity], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #GrassDensitySlider.Value, StringFormat='{}{0:0.00}'}">
|
||||
<ctl:ReadableSlider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.precipitation.particles" Label="{Binding [Precipitation], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [PrecipitationDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="PrecipitationCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="16384" Content="{Binding [QualityVeryLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="32768" Content="{Binding [QualityLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="65536" Content="{Binding [QualityNormal], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="131072" Content="{Binding [QualityHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="262144" Content="{Binding [QualityVeryHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
|
||||
@@ -39,6 +39,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private readonly SliderSteps _anisotropy;
|
||||
|
||||
private readonly SliderSteps _drawRangeFactor;
|
||||
private readonly SliderSteps _cabShadows;
|
||||
|
||||
// False while the layout loads: the handlers it names fire as it sets their controls'
|
||||
// values, before the fields of the controls are there, and do nothing until this is set.
|
||||
@@ -50,6 +51,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
public event Action? ThumbnailSizeChanged;
|
||||
|
||||
/// <summary>The standard or the advanced mode was chosen; the scenario screen follows it.</summary>
|
||||
public static event Action? AdvancedModeChanged;
|
||||
|
||||
/// <summary>Thumbnail size the other tabs were last drawn at.</summary>
|
||||
private bool _drawnThumbs = AppServices.Current.Settings.LargeThumbnails;
|
||||
|
||||
@@ -57,14 +61,14 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_fpsLimit = new SliderSteps(FpsLimitSlider, Steps.FrameRateLimits);
|
||||
_reflections = new SliderSteps(reflectionsFramerate, Steps.ReflectionUpdates);
|
||||
_fpsLimit = new SliderSteps(FpsLimitSlider, SliderRanges.FrameRateLimits);
|
||||
_reflections = new SliderSteps(reflectionsFramerate, SliderRanges.ReflectionUpdates);
|
||||
_anisotropy = new SliderSteps(TexFilteringSlider, Steps.Anisotropy);
|
||||
_drawRangeFactor = new SliderSteps(RenderRangeSlider, Steps.DrawRangeFactors);
|
||||
_drawRangeFactor = new SliderSteps(RenderRangeSlider, SliderRanges.DrawRangeFactors);
|
||||
_cabShadows = new SliderSteps(cabShaderSourceRange, SliderRanges.CabShadowRanges);
|
||||
_built = true;
|
||||
|
||||
SettingsPathText.Text = AppServices.Current.SettingsStore.LoadedFrom;
|
||||
ToolTip.SetTip(SettingsPathText, AppServices.Current.SettingsStore.LoadedFrom);
|
||||
|
||||
this.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
@@ -104,7 +108,28 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
App.Loc.LanguageChanged += _keyRows.UpdateTexts;
|
||||
|
||||
FeedbackCb.SelectionChanged += FeedbackCb_OnSelectionChanged;
|
||||
SelectExeCb.SelectionChanged += (_, _) => UpdateIdleNotes();
|
||||
// What decides whether the simulator starts and draws at all is changed only on purpose.
|
||||
AskBeforeChange(RenderAngleVulkanCb);
|
||||
AskBeforeChange(AdditionalShadersCb);
|
||||
AskBeforeChange(SkipPipelineCb);
|
||||
AskBeforeChange(RenderVBOCb);
|
||||
// Ignoring the gamepad is the recommended default; reading it has been trouble, so turning it on is asked.
|
||||
GamepadIgnoreCb.IsCheckedChanged += async (_, _) =>
|
||||
{
|
||||
if (!AsksFirst || IsChecked(GamepadIgnoreCb) || TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
if (!await MessageBox.Show(owner, App.Loc["ConfirmGamepadUse"], App.Loc["GamepadSignalIgnore"],
|
||||
MessageBoxButtons.YesNo))
|
||||
Revert(() => GamepadIgnoreCb.IsChecked = true);
|
||||
};
|
||||
RenderEngineCb.SelectionChanged += async (_, e) =>
|
||||
{
|
||||
if (!AsksFirst || e.RemovedItems.Count == 0)
|
||||
return;
|
||||
object? previous = e.RemovedItems[0];
|
||||
if (!await ConfirmRenderingChange(App.Loc["RenderEngine"]))
|
||||
Revert(() => RenderEngineCb.SelectedItem = previous);
|
||||
};
|
||||
// Coming to the page or to the list is when a new build is looked for.
|
||||
SelectExeCb.GotFocus += (_, _) => RefreshExecutables();
|
||||
PropertyChanged += (_, e) =>
|
||||
@@ -112,16 +137,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (e.Property == IsVisibleProperty && IsVisible)
|
||||
RefreshExecutables();
|
||||
};
|
||||
FullscreenWindowedCb.IsCheckedChanged += (_, _) => UpdateIdleNotes();
|
||||
App.Loc.LanguageChanged += UpdateIdleNotes;
|
||||
App.Loc.LanguageChanged += UpdateGpuNote;
|
||||
// targetfps decides whether the draw range factor does anything.
|
||||
_keyRows.Moved += key =>
|
||||
{
|
||||
if (string.Equals(key.Key, "targetfps", StringComparison.OrdinalIgnoreCase))
|
||||
UpdateIdleNotes();
|
||||
};
|
||||
InitGraphics();
|
||||
App.Loc.LanguageChanged += UpdateAdvancedModeButton;
|
||||
App.Loc.LanguageChanged += UpdateUnknownValues;
|
||||
MotionBlurCb.IsCheckedChanged += (_, _) => UpdateDependentRows();
|
||||
ReflectionsCubeMapCb.IsCheckedChanged += (_, _) => UpdateDependentRows();
|
||||
|
||||
@@ -242,9 +260,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
App.Loc["ProfileSaveAs"], MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// Written beside the user's own eu07.ini, which stays as it is.
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
bool saved = AppServices.Current.SettingsStore.ExportTo(path);
|
||||
// Written beside the user's own eu07.ini, which stays as it is; the edits stay the page's, not saved
|
||||
bool saved = AppServices.Current.SettingsStore.ExportTo(path, Trial());
|
||||
PopulateProfileCombo();
|
||||
int idx = FindComboIndexByContent(ProfileCb, Path.GetFileNameWithoutExtension(path));
|
||||
if (idx >= 0) ProfileCb.SelectedIndex = idx;
|
||||
@@ -340,7 +357,13 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SelectExeCb.SelectedIndex = index;
|
||||
}
|
||||
|
||||
public void ReloadFromSettings() => ApplyToUi();
|
||||
/// <summary>The settings read again from the file: the page shows them, no edit of its own left.</summary>
|
||||
public void ReloadFromSettings()
|
||||
{
|
||||
ApplyToUi();
|
||||
_dirty = false;
|
||||
UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while a cab-control binding is waiting for a keypress. The window's own
|
||||
@@ -353,6 +376,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
WhileLoading(() =>
|
||||
{
|
||||
SpeedometerTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLog;
|
||||
BlackBoxCb.IsChecked = AppServices.Current.Settings.BlackBox;
|
||||
TrainTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLogTrains;
|
||||
SimLogsCb.IsChecked = AppServices.Current.Settings.DebugLog;
|
||||
});
|
||||
|
||||
@@ -391,9 +416,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
|
||||
// A reloaded file may name another simulator, or start a server.
|
||||
RefreshDerivedRows();
|
||||
UpdateUnknownValues();
|
||||
UpdateGpuNote();
|
||||
NoteShownValues();
|
||||
UpdateGraphicsState();
|
||||
UpdatePresetMarks();
|
||||
}
|
||||
|
||||
@@ -403,7 +428,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
private void ShowValues(SimulatorSettings s)
|
||||
{
|
||||
FullscreenCb.IsChecked = s.Fullscreen;
|
||||
// First, or a value outside the standard ranges would be moved into them on the way in.
|
||||
ApplyRanges(s);
|
||||
PauseInactiveCb.IsChecked = s.PauseWhenInactive;
|
||||
PauseStartCb.IsChecked = s.PauseOnStart;
|
||||
CursorSensitivitySlider.Value = s.CursorSensitivity;
|
||||
@@ -449,7 +475,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
_reflections.Value = s.ReflectionsFramerate;
|
||||
shaderResolutionSlider.Value = Log2(s.ShadowMapResolution, 12);
|
||||
shaderRange.Value = s.ShadowProjectionRange;
|
||||
cabShaderSourceRange.Value = s.CabShadowsRange;
|
||||
_cabShadows.Value = s.CabShadowsRange;
|
||||
ShadowDisplayCb.SelectedIndex = Math.Clamp(s.ShadowRankCutoff - 1, 0, 2);
|
||||
ReflectionsDetailsCb.SelectedIndex = s.ReflectionsFidelity;
|
||||
fovSlider.Value = s.FieldOfView;
|
||||
@@ -457,7 +483,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
RenderScreensThreadCb.IsChecked = s.PythonThreadedUpload;
|
||||
_fpsLimit.Value = s.FpsLimitEnabled ? s.FpsLimit : 0;
|
||||
ShadowAngleLimitSlider.Value = s.ShadowAngleLimit;
|
||||
FullscreenWindowedCb.IsChecked = s.FullscreenWindowed;
|
||||
RenderAngleVulkanCb.IsChecked = s.RenderAngleVulkan;
|
||||
|
||||
TrackCurvesSlider.Value = s.SplineFidelity;
|
||||
@@ -465,6 +490,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
PantographBreakCb.IsChecked = s.EnableTraction;
|
||||
OverheadOnlyCb.IsChecked = s.LiveTraction;
|
||||
SpeedometerTapesCb.IsChecked = s.PhysicsLog;
|
||||
BlackBoxCb.IsChecked = s.BlackBox;
|
||||
TrainTapesCb.IsChecked = s.PhysicsLogTrains;
|
||||
SimLogsCb.IsChecked = s.DebugLog;
|
||||
KeepLogsCb.IsChecked = s.MultipleLogs;
|
||||
DisplaySimulationCb.IsChecked = s.DisplaySimulation;
|
||||
@@ -486,6 +513,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
AutoCloseStarterCb.IsChecked = s.AutoCloseStarter;
|
||||
LargeThumbnailsCb.IsChecked = s.LargeThumbnails;
|
||||
AutoExpandTreeCb.IsChecked = s.AutoExpandSceneryTree;
|
||||
UpdateAdvancedModeButton();
|
||||
ReadyOverrideCb.SelectedIndex = (int)s.ReadyOverride;
|
||||
|
||||
CompressTexCb.IsChecked = s.CompressTextures;
|
||||
@@ -506,8 +534,16 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// changes marks the screen dirty, as a change by hand would.
|
||||
/// </summary>
|
||||
private void ShowAsEdits(SimulatorSettings s)
|
||||
{
|
||||
_showingEdits = true;
|
||||
try
|
||||
{
|
||||
ShowValues(s);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_showingEdits = false;
|
||||
}
|
||||
RefreshDerivedRows();
|
||||
}
|
||||
|
||||
@@ -515,9 +551,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private void RefreshDerivedRows()
|
||||
{
|
||||
UpdateQualityCaptions();
|
||||
UpdateIdleNotes();
|
||||
UpdateDependentRows();
|
||||
UpdateGraphicsState();
|
||||
}
|
||||
|
||||
// ── Levels of detail ─────────────────────────────────────────────────────
|
||||
@@ -540,8 +574,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var (section, group) in new[]
|
||||
{
|
||||
(DrawRangeSection, GraphicsGroup.DrawRange), (TexturesSection, GraphicsGroup.Textures),
|
||||
(ShadowsSection, GraphicsGroup.Shadows), (LightsSection, GraphicsGroup.Lights),
|
||||
(ReflectionsSection, GraphicsGroup.Reflections), (NatureSection, GraphicsGroup.Nature)
|
||||
(ShadowsSection, GraphicsGroup.Shadows), (ReflectionsSection, GraphicsGroup.Reflections)
|
||||
})
|
||||
{
|
||||
var levels = new ComboBox();
|
||||
@@ -564,7 +597,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var (preset, button) in _presetButtons)
|
||||
{
|
||||
button.Content = App.Loc[preset.NameKey];
|
||||
ToolTip.SetTip(button, SettingTexts.PresetSummary(preset));
|
||||
}
|
||||
|
||||
_markingLevels = true;
|
||||
@@ -574,7 +606,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var level in GraphicsPreset.All)
|
||||
levels.Items.Add(new ComboBoxItem { Content = App.Loc[level.NameKey], Tag = level });
|
||||
levels.PlaceholderText = App.Loc["PresetCustom"];
|
||||
ToolTip.SetTip(levels, App.Loc["GfxGroupLevelTip"]);
|
||||
}
|
||||
_markingLevels = false;
|
||||
|
||||
@@ -598,8 +629,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
var trial = Trial();
|
||||
var applied = _presetMemory.Apply(preset, trial);
|
||||
ShowAsEdits(trial);
|
||||
foreach (string key in applied.RowKeys)
|
||||
_keyRows.Show(key, trial.Extra[key]);
|
||||
|
||||
// Chosen as a whole, its values are choices, not ones the screen could not show.
|
||||
ForgetShown(applied.ChosenKeys);
|
||||
@@ -673,8 +702,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (_cards.Count == 0)
|
||||
return;
|
||||
|
||||
CardText.Text = CardLine(_cards[0]);
|
||||
ToolTip.SetTip(CardText, string.Join(Environment.NewLine, _cards.Select(CardLine)));
|
||||
CardText.Text = string.Join(Environment.NewLine, _cards.Select(CardLine));
|
||||
}
|
||||
|
||||
// ── The screens' refresh rates, for the frame rate limit ─────────────────
|
||||
@@ -683,39 +711,52 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
|
||||
private void BuildMonitorRates()
|
||||
{
|
||||
var displays = AppServices.Current.Displays.List();
|
||||
if (displays.Count == 0)
|
||||
return;
|
||||
|
||||
MonitorRates.IsVisible = true;
|
||||
UpdateMonitorRates(displays);
|
||||
App.Loc.LanguageChanged += () => UpdateMonitorRates(displays);
|
||||
VSyncCb.IsCheckedChanged += (_, _) => UpdateMonitorRates();
|
||||
DisplayModeCb.SelectionChanged += (_, _) =>
|
||||
{
|
||||
UpdateDisplayRows();
|
||||
UpdateMonitorRates();
|
||||
};
|
||||
MonitorCb.SelectionChanged += (_, _) => UpdateMonitorRates();
|
||||
App.Loc.LanguageChanged += UpdateMonitorRates;
|
||||
UpdateMonitorRates();
|
||||
}
|
||||
|
||||
private void UpdateMonitorRates(IReadOnlyList<Display> displays)
|
||||
/// <summary>
|
||||
/// The rate of the monitor the simulator will show on, with a button to match the limit
|
||||
/// to it. VSync already holds the frames to that rate, so with it on there is no button:
|
||||
/// fpslimit paces frames by its own clock (framepacer.h), not the refresh, so no limit
|
||||
/// of it lines up with the monitor.
|
||||
/// </summary>
|
||||
private void UpdateMonitorRates()
|
||||
{
|
||||
bool vsync = IsChecked(VSyncCb);
|
||||
FpsVSyncNote.IsVisible = vsync;
|
||||
MonitorRates.Children.Clear();
|
||||
foreach (var display in displays)
|
||||
{
|
||||
string screen = string.IsNullOrEmpty(display.Name)
|
||||
? string.Format(App.Loc["MonitorRate"], display.RefreshRate)
|
||||
: string.Format(App.Loc["MonitorRateNamed"], display.Name, display.RefreshRate);
|
||||
|
||||
int hz = SimulatorMonitor()?.RefreshRate ?? 0;
|
||||
MonitorRates.IsVisible = hz > 0;
|
||||
if (hz == 0)
|
||||
return;
|
||||
|
||||
MonitorRates.Children.Add(new TextBlock
|
||||
{
|
||||
Text = screen, FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center
|
||||
Text = string.Format(App.Loc["MonitorRate"], hz),
|
||||
FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center
|
||||
});
|
||||
if (vsync)
|
||||
return;
|
||||
|
||||
var match = new Button
|
||||
{
|
||||
Content = string.Format(App.Loc["MonitorRateUse"], display.RefreshRate),
|
||||
Content = string.Format(App.Loc["MonitorRateUse"], hz),
|
||||
Margin = new Thickness(4, 0, 14, 0)
|
||||
};
|
||||
match.Classes.Add("Outline");
|
||||
match.Classes.Add("SectionReset");
|
||||
int rate = display.RefreshRate;
|
||||
match.Click += (_, _) => _fpsLimit.Value = rate;
|
||||
match.Click += (_, _) => _fpsLimit.Value = hz;
|
||||
MonitorRates.Children.Add(match);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sections back to the simulator's own values ──────────────────────────
|
||||
|
||||
@@ -765,13 +806,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// <summary>Puts the section's rows at the simulator's own values, as edits waiting for Save.</summary>
|
||||
private void ResetSection(SettingsSection section)
|
||||
{
|
||||
var keys = ResettableKeys(section);
|
||||
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys));
|
||||
foreach (string key in keys)
|
||||
_keyRows.ShowDefault(key);
|
||||
|
||||
// Put back by hand, a value is a choice like any other.
|
||||
ForgetShown(keys);
|
||||
ShowDefaults(ResettableKeys(section));
|
||||
Announcer.Say(this, ScreenReaderNames.PickerText(ScreenReaderNames.TextOf(section.Header), App.Loc["DefaultsRestored"]));
|
||||
}
|
||||
|
||||
@@ -822,7 +857,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private string SelectedRenderer() =>
|
||||
SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
|
||||
|
||||
private RendererKind SelectedRendererKind() => SettingReach.KindOf(SelectedRenderer());
|
||||
private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer());
|
||||
|
||||
/// <summary>
|
||||
/// Writes the pending edits on this screen into the settings, so a save from
|
||||
@@ -840,7 +875,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
var language = ChangeLanguageCb.SelectedItem as ComboBoxItem;
|
||||
s.Language = language?.Content?.ToString() ?? App.Loc.CurrentLanguage;
|
||||
s.LanguageCode = language?.Tag as string ?? App.Loc.CurrentLangCode;
|
||||
s.Fullscreen = IsChecked(FullscreenCb);
|
||||
s.PauseWhenInactive = IsChecked(PauseInactiveCb);
|
||||
s.PauseOnStart = IsChecked(PauseStartCb);
|
||||
s.CursorSensitivity = (int)CursorSensitivitySlider.Value;
|
||||
@@ -880,7 +914,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
s.ReflectionsFramerate = _reflections.Value;
|
||||
s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value;
|
||||
s.ShadowProjectionRange = (int)shaderRange.Value;
|
||||
s.CabShadowsRange = (int)cabShaderSourceRange.Value;
|
||||
s.CabShadowsRange = (int)_cabShadows.Value;
|
||||
s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
|
||||
s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
|
||||
s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75);
|
||||
@@ -892,7 +926,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (fpsLimit > 0)
|
||||
s.FpsLimit = fpsLimit;
|
||||
s.ShadowAngleLimit = ShadowAngleLimitSlider.Value;
|
||||
s.FullscreenWindowed = IsChecked(FullscreenWindowedCb);
|
||||
s.RenderAngleVulkan = IsChecked(RenderAngleVulkanCb);
|
||||
|
||||
s.SplineFidelity = (int)TrackCurvesSlider.Value;
|
||||
@@ -900,6 +933,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
s.EnableTraction = IsChecked(PantographBreakCb);
|
||||
s.LiveTraction = IsChecked(OverheadOnlyCb);
|
||||
s.PhysicsLog = IsChecked(SpeedometerTapesCb);
|
||||
s.BlackBox = IsChecked(BlackBoxCb);
|
||||
s.PhysicsLogTrains = IsChecked(TrainTapesCb);
|
||||
s.DebugLog = IsChecked(SimLogsCb);
|
||||
s.MultipleLogs = IsChecked(KeepLogsCb);
|
||||
s.DisplaySimulation = IsChecked(DisplaySimulationCb);
|
||||
@@ -955,11 +990,11 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
OnControlChanged();
|
||||
};
|
||||
UartEnabledCb.IsCheckedChanged += (_, _) => ValidateUart();
|
||||
UartTuneBox.TextChanged += (_, _) =>
|
||||
OnTextEdited(UartTuneBox, () =>
|
||||
{
|
||||
ValidateUart();
|
||||
OnControlChanged();
|
||||
};
|
||||
});
|
||||
App.Loc.LanguageChanged += UpdateUartTexts;
|
||||
UpdateUartTexts();
|
||||
}
|
||||
@@ -1049,6 +1084,10 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
var store = AppServices.Current.SettingsStore;
|
||||
store.Save();
|
||||
// The file had changes from elsewhere, kept with these: show them.
|
||||
if (store.LastSaveMerged)
|
||||
ApplyToUi();
|
||||
UpdateUnknownValues();
|
||||
KeyboardConfig.Instance.Save();
|
||||
RedrawThumbnailsIfNeeded();
|
||||
// Not saved, it is still there to be saved.
|
||||
@@ -1057,12 +1096,51 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SaveStatus.Text = App.Loc[store.LastSaveFailed ? "SettingsNotSaved" : "SettingsSaved"];
|
||||
}
|
||||
|
||||
// ── Rendering changes, each confirmed ──────────────────────────────────
|
||||
|
||||
/// <summary>Set while a preset, a reset or a profile puts values on the screen: those are not clicks to confirm.</summary>
|
||||
private bool _showingEdits;
|
||||
|
||||
/// <summary>Set while a refused change is put back, which is no change to ask about.</summary>
|
||||
private bool _reverting;
|
||||
|
||||
private bool AsksFirst => _built && !_loading && !_showingEdits && !_reverting;
|
||||
|
||||
private void AskBeforeChange(CheckBox box) =>
|
||||
box.IsCheckedChanged += async (_, _) =>
|
||||
{
|
||||
if (!AsksFirst)
|
||||
return;
|
||||
if (!await ConfirmRenderingChange(ScreenReaderNames.TextOf(box.Content)))
|
||||
Revert(() => box.IsChecked = !box.IsChecked);
|
||||
};
|
||||
|
||||
private async Task<bool> ConfirmRenderingChange(string? setting)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return true;
|
||||
return await MessageBox.Show(owner, string.Format(App.Loc["ConfirmRenderingChange"], setting),
|
||||
App.Loc["GfxColRendering"], MessageBoxButtons.YesNo);
|
||||
}
|
||||
|
||||
private void Revert(Action putBack)
|
||||
{
|
||||
_reverting = true;
|
||||
try
|
||||
{
|
||||
putBack();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reverting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderEngineCb_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (!_built)
|
||||
return;
|
||||
|
||||
OnBackendChanged();
|
||||
RefreshDerivedRows();
|
||||
}
|
||||
|
||||
@@ -1118,43 +1196,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
return exes.FullPath(exes.Resolve(pick, out _));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dims the rows the simulator to be started would ignore and says why. Follows
|
||||
/// the simulator and renderer picked here, before they are saved.
|
||||
/// </summary>
|
||||
private void UpdateIdleNotes()
|
||||
{
|
||||
string exe = TargetExecutable();
|
||||
var settings = AppServices.Current.Settings;
|
||||
var target = new SimulatorTarget(
|
||||
AppServices.Current.Executables.IsWindowsBuild(exe),
|
||||
SelectedRenderer(),
|
||||
settings.NetworkServer,
|
||||
_keyRows.NumberIfSet("targetfps", settings),
|
||||
settings.FpsAverage,
|
||||
IsChecked(FullscreenWindowedCb));
|
||||
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
row.IdleNote = string.IsNullOrEmpty(row.ConfigKey)
|
||||
? null
|
||||
: IdleText(SettingReach.Why(row.ConfigKey, target));
|
||||
|
||||
RenderEngineWarning.IsVisible = SelectedRendererKind() == RendererKind.Experimental;
|
||||
}
|
||||
|
||||
private static string? IdleText(IdleReason reason) => reason switch
|
||||
{
|
||||
IdleReason.WindowsBuildOnly => App.Loc["IdleWindowsBuildOnly"],
|
||||
IdleReason.LegacyRendererOnly => App.Loc["IdleLegacyRendererOnly"],
|
||||
IdleReason.ModernRendererOnly => App.Loc["IdleModernRendererOnly"],
|
||||
IdleReason.OpenGlRenderersOnly => App.Loc["IdleOpenGlRenderersOnly"],
|
||||
IdleReason.NeedsNetworkServer => App.Loc["IdleNeedsNetworkServer"],
|
||||
IdleReason.NeedsFrameRateTarget => App.Loc["IdleNeedsFrameRateTarget"],
|
||||
IdleReason.MonitorModeInstead => App.Loc["IdleMonitorMode"],
|
||||
IdleReason.VulkanOnly => App.Loc["IdleVulkanOnly"],
|
||||
_ => null
|
||||
};
|
||||
|
||||
private void RedrawThumbnailsIfNeeded()
|
||||
{
|
||||
bool large = AppServices.Current.Settings.LargeThumbnails;
|
||||
@@ -1176,6 +1217,18 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
Announcer.Say(this, App.Loc["SettingsRestored"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page's own edits let go, and the keys': the page shows the settings as held. Not read again from the file
|
||||
/// as "Restore" does - what other pages set and not yet saved (a filter of the depot, the window maximized) stays.
|
||||
/// </summary>
|
||||
public void DiscardEdits()
|
||||
{
|
||||
ApplyToUi();
|
||||
_keyBindings.Reload();
|
||||
_dirty = false;
|
||||
UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>The list as <see cref="ResolutionChoices"/> has it for the monitors there are now, with the size selected.</summary>
|
||||
private void SelectResolution(int width, int height)
|
||||
{
|
||||
@@ -1262,7 +1315,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private void UpdateShadowResolution()
|
||||
{
|
||||
int resolution = ShowPixels(ShadowResolutionRow, shaderResolutionSlider);
|
||||
ToolTip.SetTip(shaderResolutionSlider, SettingTexts.ShadowMapWord(resolution));
|
||||
|
||||
// Below this the simulator would raise the range anyway.
|
||||
shaderRange.Minimum = SimulatorSettings.ShadowRangeFloor(resolution);
|
||||
@@ -1317,6 +1369,160 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
private void UpdateFeedbackDetailVisibility() => ApplyFilter();
|
||||
|
||||
/// <summary>
|
||||
/// The mode is the player's way of using the starter, not a setting of the simulator: it is
|
||||
/// kept straight away, as the language is, and the scenario screen follows it.
|
||||
/// </summary>
|
||||
private async void AdvancedModeBtn_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
|
||||
var settings = AppServices.Current.Settings;
|
||||
if (!settings.AdvancedSettings)
|
||||
{
|
||||
if (!await MessageBox.ShowDelayed(owner, App.Loc["AdvancedModeWarning"], App.Loc["AdvancedMode"],
|
||||
App.Loc["AdvancedModeOn"], 20))
|
||||
return;
|
||||
|
||||
settings.AdvancedSettings = true;
|
||||
AppServices.Current.SettingsStore.Save();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await MessageBox.Show(owner, App.Loc["AdvancedModeOffConfirm"], App.Loc["AdvancedMode"],
|
||||
MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// Leaving the mode leaves nothing of it behind: what only it shows goes back to the
|
||||
// simulator's own values, and the page is saved with them.
|
||||
ShowDefaults(AdvancedKeys());
|
||||
settings.AdvancedSettings = false;
|
||||
Save();
|
||||
}
|
||||
|
||||
AdvancedModeChanged?.Invoke();
|
||||
UpdateAdvancedModeButton();
|
||||
ApplyFilter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once, on the first start of this starter, for the settings an older one left: the
|
||||
/// standard mode, what only the advanced one shows at the simulator's own values, and
|
||||
/// every slider's value within its range, saved. eu07.ini is copied aside first.
|
||||
/// </summary>
|
||||
public void MoveToStandardOnce()
|
||||
{
|
||||
var settings = AppServices.Current.Settings;
|
||||
var store = AppServices.Current.SettingsStore;
|
||||
if (settings.MovedToStandard || store.LoadFailed)
|
||||
return;
|
||||
|
||||
store.KeepCopy(".before-standard");
|
||||
var moved = AdvancedKeys();
|
||||
moved.ExceptWith(SettingsStore.KeptOnMoveToStandard);
|
||||
_clamping = true;
|
||||
try
|
||||
{
|
||||
ShowDefaults(moved);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_clamping = false;
|
||||
}
|
||||
// A value moved into its slider is saved as moved, not left as the file had it.
|
||||
ForgetShown(SliderKeys());
|
||||
|
||||
bool wasAdvanced = settings.AdvancedSettings;
|
||||
settings.AdvancedSettings = false;
|
||||
settings.MovedToStandard = true;
|
||||
Save();
|
||||
|
||||
if (wasAdvanced)
|
||||
AdvancedModeChanged?.Invoke();
|
||||
UpdateAdvancedModeButton();
|
||||
ApplyFilter();
|
||||
}
|
||||
|
||||
/// <summary>Puts <paramref name="keys"/> at the simulator's own values, as edits waiting for Save.</summary>
|
||||
private void ShowDefaults(IReadOnlyCollection<string> keys)
|
||||
{
|
||||
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys));
|
||||
foreach (string key in keys)
|
||||
_keyRows.ShowDefault(key);
|
||||
// Put back by hand, a value is a choice like any other.
|
||||
ForgetShown(keys);
|
||||
}
|
||||
|
||||
/// <summary>The keys of the rows set with a slider.</summary>
|
||||
private HashSet<string> SliderKeys()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
if (row.GetLogicalDescendants().OfType<Slider>().Any())
|
||||
foreach (string key in (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
keys.Add(key);
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every setting of the page at the simulator's own values, the ones only the advanced mode
|
||||
/// shows too, as edits waiting for Save; the key bindings have a button of their own.
|
||||
/// </summary>
|
||||
private async void DefaultsButton_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
if (!await MessageBox.Show(owner, App.Loc["AllDefaultsConfirm"], App.Loc["RestoreDefaults"],
|
||||
MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var section in SettingsStack.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
keys.UnionWith(ResettableKeys(section));
|
||||
ShowDefaults(keys);
|
||||
SaveStatus.Text = App.Loc["DefaultsRestored"];
|
||||
}
|
||||
|
||||
/// <summary>The keys of every row only the advanced mode shows.</summary>
|
||||
private HashSet<string> AdvancedKeys()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var section in SettingsStack.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
{
|
||||
if (section.Advanced && !string.IsNullOrEmpty(section.ToggleKey))
|
||||
keys.Add(section.ToggleKey);
|
||||
foreach (var row in section.GetLogicalDescendants().OfType<SettingRow>())
|
||||
if (section.Advanced || row.Advanced)
|
||||
foreach (string key in (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
keys.Add(key);
|
||||
}
|
||||
keys.ExceptWith(KeptOnReset);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private bool Advanced => AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
/// <summary>Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it.</summary>
|
||||
private void UpdateUnknownValues()
|
||||
{
|
||||
var unreadable = AppServices.Current.SettingsStore.UnreadableValues();
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
{
|
||||
var keys = (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var found = keys.Where(unreadable.ContainsKey)
|
||||
.Select(key => keys.Length > 1 ? key + " " + unreadable[key] : unreadable[key])
|
||||
.ToList();
|
||||
row.UnknownValue = found.Count > 0 ? string.Format(App.Loc["UnknownIniValue"], string.Join(", ", found)) : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateAdvancedModeButton() =>
|
||||
AdvancedModeBtn.Content = App.Loc[Advanced ? "AdvancedModeOff" : "AdvancedModeMenu"];
|
||||
|
||||
private bool ConditionAllows(SettingRow row)
|
||||
{
|
||||
if (ReferenceEquals(row, GpuRow))
|
||||
@@ -1378,6 +1584,11 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SettingsScroll.IsVisible = !bindings;
|
||||
PresetBar.IsVisible = category is "graphics" or "effects" && !searching;
|
||||
|
||||
// The standard mode keeps to what a player needs; a search still finds everything,
|
||||
// since whoever types a setting's name is looking for it.
|
||||
bool advanced = Advanced;
|
||||
bool everything = advanced || searching;
|
||||
|
||||
if (bindings)
|
||||
{
|
||||
_keyBindings.RebuildList();
|
||||
@@ -1395,12 +1606,17 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var section in panel.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
{
|
||||
bool anyInSection = false;
|
||||
if (section.Level is Control level)
|
||||
level.IsVisible = advanced;
|
||||
|
||||
foreach (var row in section.GetLogicalDescendants().OfType<SettingRow>())
|
||||
{
|
||||
bool visible = ConditionAllows(row) &&
|
||||
// A value the starter cannot read is shown in either mode, so it can be put right.
|
||||
bool standard = (!section.Advanced && !row.Advanced) || !string.IsNullOrEmpty(row.UnknownValue);
|
||||
bool visible = ConditionAllows(row) && (everything || standard) &&
|
||||
(!searching || TextMatch.Contains(RowSearchText(row), query));
|
||||
row.IsVisible = visible;
|
||||
row.Classes.Set("HideKey", !advanced);
|
||||
anyInSection |= visible;
|
||||
if (visible && searching)
|
||||
_shownCount++;
|
||||
@@ -1418,11 +1634,17 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
caption.IsVisible = searching;
|
||||
|
||||
if (CategoryItem(tag) is { } item)
|
||||
{
|
||||
item.Classes.Set("NoHits", searching && !anyRow);
|
||||
// A category with nothing for the standard mode leaves the list.
|
||||
item.IsVisible = everything || anyRow;
|
||||
}
|
||||
}
|
||||
|
||||
if (searching)
|
||||
SettingsScroll.Offset = new Vector(0, 0);
|
||||
else if (CategoryList.SelectedItem is ListBoxItem { IsVisible: false })
|
||||
CategoryList.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
private ListBoxItem? CategoryItem(string tag) =>
|
||||
@@ -1487,9 +1709,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
case NumericUpDown nud:
|
||||
nud.ValueChanged += (_, _) => OnControlChanged();
|
||||
break;
|
||||
case TextBox box when ReferenceEquals(box, VulkanDeviceTb):
|
||||
box.TextChanged += (_, _) => OnControlChanged();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1498,11 +1717,22 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
toggle.IsCheckedChanged += (_, _) => OnControlChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The text as it changes, not TextChanged: that one comes later, from the
|
||||
/// dispatcher, so the text the page itself put there while loading came back
|
||||
/// as an edit once the window was shown - the first start asked to save.
|
||||
/// </summary>
|
||||
private static void OnTextEdited(TextBox box, Action edited) =>
|
||||
box.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == TextBox.TextProperty)
|
||||
edited();
|
||||
};
|
||||
|
||||
private void OnControlChanged()
|
||||
{
|
||||
MarkDirty();
|
||||
QueuePresetMarks();
|
||||
UpdateGraphicsState();
|
||||
}
|
||||
|
||||
private void MarkDirty()
|
||||
@@ -1510,13 +1740,15 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (_loading || _dirty)
|
||||
return;
|
||||
|
||||
_dirty = true;
|
||||
UpdateSaveState();
|
||||
_dirty = true; UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells.</summary>
|
||||
public bool HasUnsavedChanges => _dirty || KeyboardConfig.Instance.Dirty;
|
||||
|
||||
private void UpdateSaveState()
|
||||
{
|
||||
bool dirty = _dirty || KeyboardConfig.Instance.Dirty;
|
||||
bool dirty = HasUnsavedChanges;
|
||||
SaveButton.Classes.Set("Accent", dirty);
|
||||
SaveStatus.Text = dirty ? App.Loc["UnsavedChanges"] : string.Empty;
|
||||
}
|
||||
@@ -1530,6 +1762,28 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
return 200;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old starter's ranges (<see cref="SliderRanges"/>), in either mode, with the value
|
||||
/// <paramref name="s"/> has along with them: one from the file or a level outside them is
|
||||
/// shown as it is, so opening and saving the settings never moves it - as SliderSteps does.
|
||||
/// </summary>
|
||||
private void ApplyRanges(SimulatorSettings s)
|
||||
{
|
||||
// Clamping, the ranges stay as they are and a value past them is moved in.
|
||||
bool widen = !_clamping;
|
||||
int minTexture = Log2(SliderRanges.MinTextureSize, 9), minShadow = Log2(SliderRanges.MinShadowMap, 10);
|
||||
textureResolutionSlider.Minimum = widen ? Math.Min(minTexture, Log2(s.MaxTextureSize, 12)) : minTexture;
|
||||
shaderResolutionSlider.Minimum = widen ? Math.Min(minShadow, Log2(s.ShadowMapResolution, 12)) : minShadow;
|
||||
DynamicLightsSlider.Minimum = widen
|
||||
? Math.Min(SliderRanges.MinDynamicLights, s.DynamicLights)
|
||||
: SliderRanges.MinDynamicLights;
|
||||
foreach (var steps in new[] { _fpsLimit, _reflections, _anisotropy, _drawRangeFactor, _cabShadows })
|
||||
steps.Clamps = _clamping;
|
||||
}
|
||||
|
||||
/// <summary>Set while values are put on the screen moved into the sliders' ranges, not widening them.</summary>
|
||||
private bool _clamping;
|
||||
|
||||
private static int Log2(int value, int fallback)
|
||||
{
|
||||
if (value <= 0) return fallback;
|
||||
@@ -1569,11 +1823,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
int reach = SimulatorSettings.ShadowReach(metres, 1 << (int)shaderResolutionSlider.Value,
|
||||
SelectedRendererKind() != RendererKind.Modern);
|
||||
ShadowRangeRow.ValueText = reach == metres ? $"{metres} m" : $"{metres} m → {reach} m";
|
||||
ToolTip.SetTip(shaderRange, SettingTexts.ShadowRangeWord(reach));
|
||||
|
||||
int cabMetres = (int)cabShaderSourceRange.Value;
|
||||
int cabMetres = (int)_cabShadows.Value;
|
||||
CabShadowRangeRow.ValueText = cabMetres <= 0 ? App.Loc["RangeDisabled"] : $"{cabMetres} m";
|
||||
ToolTip.SetTip(cabShaderSourceRange, SettingTexts.CabShadowRangeWord(cabMetres));
|
||||
|
||||
ReflectionsFramerateRow.ValueText = SettingTexts.ReflectionsInterval(_reflections.Value);
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ internal sealed class SimulatorKeyRows
|
||||
// Marks the input as one of these rows, which tell about their own changes.
|
||||
input.Tag = key;
|
||||
|
||||
var setting = new SettingRow { ConfigKey = key.Key, Content = input };
|
||||
var setting = new SettingRow { ConfigKey = key.Key, Content = input, Advanced = !SimulatorKeys.Standard.Contains(key.Key) };
|
||||
var row = new Row(key, setting, input);
|
||||
_rows.Add(row);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
@@ -28,11 +29,16 @@ internal sealed class SliderSteps
|
||||
slider.Maximum = steps.Count - 1;
|
||||
}
|
||||
|
||||
/// <summary>A value past either end of the list is put at that end, not added to it.</summary>
|
||||
public bool Clamps { get; set; }
|
||||
|
||||
public double Value
|
||||
{
|
||||
get => _shown[Math.Clamp((int)Math.Round(_slider.Value), 0, _shown.Count - 1)];
|
||||
set
|
||||
{
|
||||
if (Clamps)
|
||||
value = Math.Clamp(value, _steps.Min(), _steps.Max());
|
||||
_shown = Steps.With(_steps, value);
|
||||
_slider.Maximum = _shown.Count - 1;
|
||||
int at = Steps.IndexOf(_shown, value);
|
||||
|
||||
65
StarterNG/Views/Tapes/ColumnLine.cs
Normal file
65
StarterNG/Views/Tapes/ColumnLine.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
|
||||
namespace StarterNG.Views.Tapes;
|
||||
|
||||
/// <summary>
|
||||
/// The line of a tape, one column of pixels at a time: of each column, the first, the lowest, the highest and the
|
||||
/// last point in it, entered where the column started and left where it ended, so a long trip draws as fast as a
|
||||
/// short one. The figures go out through the three calls given: one begun at its first point, a line to each next,
|
||||
/// and its end.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its state is kept in fields, not in the locals of a local function, which Sonar's analysis doesn't see changed
|
||||
/// by it (S2583 took the end of a figure after a gap for code never run).
|
||||
/// </remarks>
|
||||
internal sealed class ColumnLine(Action<Point> begin, Action<Point> lineTo, Action end)
|
||||
{
|
||||
private bool _begun;
|
||||
private int _column = int.MinValue;
|
||||
private double _top, _bottom, _first, _last;
|
||||
|
||||
/// <summary>The point of a sample, at its column of pixels.</summary>
|
||||
public void Add(int column, double value)
|
||||
{
|
||||
if (column != _column)
|
||||
{
|
||||
Flush();
|
||||
_column = column;
|
||||
_top = _bottom = _first = value;
|
||||
}
|
||||
_top = Math.Min(_top, value);
|
||||
_bottom = Math.Max(_bottom, value);
|
||||
_last = value;
|
||||
}
|
||||
|
||||
/// <summary>The line ends here, at a gap or at the end of the tape; a point added after begins a figure of its own.</summary>
|
||||
public void Break()
|
||||
{
|
||||
Flush();
|
||||
_column = int.MinValue;
|
||||
if (!_begun)
|
||||
return;
|
||||
end();
|
||||
_begun = false;
|
||||
}
|
||||
|
||||
private void Flush()
|
||||
{
|
||||
if (_column == int.MinValue)
|
||||
return;
|
||||
// Enter where the column started, leave where it ended.
|
||||
var (a, b) = _first <= _last ? (_top, _bottom) : (_bottom, _top);
|
||||
foreach (double v in new[] { _first, a, b, _last })
|
||||
{
|
||||
var p = new Point(_column, v);
|
||||
if (_begun)
|
||||
lineTo(p);
|
||||
else
|
||||
{
|
||||
begin(p);
|
||||
_begun = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user