mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-22 00:04:57 +01:00
Compare commits
59 Commits
fix/screen
...
feat/setti
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93f914c868 | ||
|
|
de943cf461 | ||
|
|
e63aa71bf8 | ||
|
|
ecf3067d85 | ||
| c07ed2fb4d | |||
| cfea240243 | |||
|
|
f0fa2d1768 | ||
|
|
2a85ca384a | ||
|
|
fa8ae760e1 | ||
|
|
100bbea83e | ||
|
|
195f358e55 | ||
|
|
be7b9c5679 | ||
|
|
c370d1509e | ||
| 3c9b578e6b | |||
| 952618be13 | |||
| 156af3fdd1 | |||
| 49b76aa66c | |||
| 9b1523ef78 | |||
| 1d5b0ea1f4 | |||
|
|
8baf2149ea | ||
|
|
aebfaf34ac | ||
|
|
5bc5da3fbf | ||
|
|
e4d092ab3e | ||
|
|
632e1003ee | ||
|
|
34ee131d61 | ||
|
|
faa06fb9d8 | ||
|
|
829a3e7a3d | ||
|
|
5b43e29f9e | ||
|
|
b63ba8fe2e | ||
|
|
76693c1494 | ||
|
|
13990a7036 | ||
|
|
5ab9bce321 | ||
|
|
f1d77addae | ||
|
|
192f9fa499 | ||
|
|
92c0283479 | ||
|
|
b2fd53f7bc | ||
|
|
06513537f0 | ||
|
|
38802845c7 | ||
|
|
bba9e3ef48 | ||
|
|
31fc4c3fdc | ||
|
|
f29ce10f5c | ||
|
|
6e2dbf9eac | ||
|
|
91c496ab48 | ||
|
|
7823bb8d09 | ||
|
|
1398545ff2 | ||
|
|
45105e7b9c | ||
|
|
4429eff4ef | ||
|
|
1ef630b1b6 | ||
|
|
7cd3ef8f1a | ||
|
|
1b41ef752a | ||
|
|
42f702a096 | ||
|
|
7f57160aae | ||
|
|
2efae83b57 | ||
|
|
34f2ce99e8 | ||
|
|
52408a9931 | ||
|
|
290b753f40 | ||
|
|
6279228a7d | ||
|
|
d4975796a8 | ||
|
|
48af11b4b2 |
@@ -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.",
|
["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",
|
["Follow"] = "Follow the train",
|
||||||
["Fit"] = "Whole map",
|
["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}",
|
["Unreadable"] = "Can't read {0}: {1}",
|
||||||
["Reading"] = "Reading {0}…",
|
["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}",
|
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
|
||||||
@@ -185,8 +185,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["EventHornMissed"] = "W6: NO HORN",
|
["EventHornMissed"] = "W6: NO HORN",
|
||||||
["EventCab"] = "Cab {0} of {1}",
|
["EventCab"] = "Cab {0} of {1}",
|
||||||
["EventSecurityBraking"] = "BRAKING BY {0}",
|
["EventSecurityBraking"] = "BRAKING BY {0}",
|
||||||
|
["EventSecurityAlarm"] = "{0} buzzer",
|
||||||
|
["EventSecurityAlarmAcknowledged"] = "{0} buzzer, acknowledged after {1:0.0} s",
|
||||||
|
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
|
||||||
["EventTimetable"] = "Timetable {0}, {1}",
|
["EventTimetable"] = "Timetable {0}, {1}",
|
||||||
["CabSpeed"] = "Speed",
|
["CabSpeed"] = "Speed",
|
||||||
|
["CabWheels"] = "wheels {0:0}",
|
||||||
["CabAiTarget"] = "AI {0:0} km/h",
|
["CabAiTarget"] = "AI {0:0} km/h",
|
||||||
["CabAcceleration"] = "Along",
|
["CabAcceleration"] = "Along",
|
||||||
["CabLateral"] = "Lateral",
|
["CabLateral"] = "Lateral",
|
||||||
@@ -305,7 +309,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
|
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
|
||||||
["Follow"] = "Śledź pociąg",
|
["Follow"] = "Śledź pociąg",
|
||||||
["Fit"] = "Cała mapa",
|
["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}",
|
["Unreadable"] = "Nie można odczytać {0}: {1}",
|
||||||
["Reading"] = "Czytanie {0}…",
|
["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}",
|
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
|
||||||
@@ -460,8 +464,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
|
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
|
||||||
["EventCab"] = "Kabina {0} w {1}",
|
["EventCab"] = "Kabina {0} w {1}",
|
||||||
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
|
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
|
||||||
|
["EventSecurityAlarm"] = "Brzęczyk {0}",
|
||||||
|
["EventSecurityAlarmAcknowledged"] = "Brzęczyk {0}, potwierdzony po {1:0.0} s",
|
||||||
|
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
|
||||||
["EventTimetable"] = "Rozkład {0}, {1}",
|
["EventTimetable"] = "Rozkład {0}, {1}",
|
||||||
["CabSpeed"] = "Prędkość",
|
["CabSpeed"] = "Prędkość",
|
||||||
|
["CabWheels"] = "koła {0:0}",
|
||||||
["CabAiTarget"] = "AI {0:0} km/h",
|
["CabAiTarget"] = "AI {0:0} km/h",
|
||||||
["CabAcceleration"] = "Wzdłużne",
|
["CabAcceleration"] = "Wzdłużne",
|
||||||
["CabLateral"] = "Boczne",
|
["CabLateral"] = "Boczne",
|
||||||
@@ -564,7 +572,11 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["FileFilter"] = "Czarna skrzynka"
|
["FileFilter"] = "Czarna skrzynka"
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>The key of the text of a simulator's command: <see cref="CommandPrefix"/> and its name.</summary>
|
||||||
|
public const string CommandPrefix = "Cmd.";
|
||||||
|
|
||||||
private readonly Dictionary<string, string> _texts;
|
private readonly Dictionary<string, string> _texts;
|
||||||
|
private readonly string _languageCode;
|
||||||
|
|
||||||
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
|
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
|
||||||
{
|
{
|
||||||
@@ -577,11 +589,15 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
/// <summary>Polish for "pl", English for any other language.</summary>
|
/// <summary>Polish for "pl", English for any other language.</summary>
|
||||||
public DefaultBlackBoxStrings(string languageCode)
|
public DefaultBlackBoxStrings(string languageCode)
|
||||||
{
|
{
|
||||||
|
_languageCode = languageCode;
|
||||||
_texts = languageCode == "pl" ? Polish : English;
|
_texts = languageCode == "pl" ? Polish : English;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
|
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
|
||||||
public static IEnumerable<string> Keys => English.Keys;
|
public static IEnumerable<string> Keys => English.Keys;
|
||||||
|
|
||||||
public string this[string key] => _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
/// <summary>A key of <see cref="CommandPrefix"/> gives what the command does (<see cref="CommandTexts"/>).</summary>
|
||||||
|
public string this[string key] =>
|
||||||
|
key.StartsWith(CommandPrefix, System.StringComparison.Ordinal) ? CommandTexts.Of(key[CommandPrefix.Length..], _languageCode)
|
||||||
|
: _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ public sealed class CabPanel : Control
|
|||||||
private const double LampRow = 14;
|
private const double LampRow = 14;
|
||||||
private const int DoorColumns = 2;
|
private const int DoorColumns = 2;
|
||||||
private const double DriveRow = 34;
|
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 Recording? _recording;
|
||||||
private double _time;
|
private double _time;
|
||||||
@@ -174,8 +175,19 @@ public sealed class CabPanel : Control
|
|||||||
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
|
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
|
||||||
context.DrawText(speed, new Point(Pad, 24));
|
context.DrawText(speed, new Point(Pad, 24));
|
||||||
Say($"{kmh} km/h");
|
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);
|
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)
|
if (s.AiValid)
|
||||||
{
|
{
|
||||||
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
|
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));
|
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
|
||||||
Say(Strings["CabGroupDoors"]);
|
Say(Strings["CabGroupDoors"]);
|
||||||
var doors = Doors(s);
|
var doors = Doors(s.AsTheCabSees);
|
||||||
double doorColumn = width / DoorColumns;
|
double doorColumn = width / DoorColumns;
|
||||||
for (int i = 0; i < doors.Length; i++)
|
for (int i = 0; i < doors.Length; i++)
|
||||||
{
|
{
|
||||||
@@ -660,12 +672,12 @@ public sealed class CabPanel : Control
|
|||||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||||
{
|
{
|
||||||
// A recording which tells them apart.
|
// A recording which tells them apart.
|
||||||
safety.Add((Strings["DevVigilance"], Security(SecurityFlags.VigilanceBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
||||||
safety.Add((Strings["DevCabSignal"], Security(SecurityFlags.CabSignalBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
||||||
safety.Add((Strings["DevSecurityBraking"], Security(SecurityFlags.Braking, Palette.LampAlarm)));
|
safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
||||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
|
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
|
||||||
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
|
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
|
||||||
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
|
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
|
||||||
|
|||||||
378
Eu07.BlackBox.Views/CommandTexts.cs
Normal file
378
Eu07.BlackBox.Views/CommandTexts.cs
Normal file
@@ -0,0 +1,378 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Eu07.BlackBox.Views;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the simulator's commands of a vehicle do, as the black box names them (input/command.cpp): Polish
|
||||||
|
/// and English. Those with a key carry the texts of the key file (eu07_input-keyboard.ini) and of the starter's
|
||||||
|
/// English; the rest, worked by the mouse in the cab or by scripts, are written here.
|
||||||
|
/// </summary>
|
||||||
|
public static class CommandTexts
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, (string Polish, string English)> Texts = new()
|
||||||
|
{
|
||||||
|
["aidriverenable"] = ("Aktywacja automechanika", "Engage the AI driver"),
|
||||||
|
["aidriverdisable"] = ("Dezaktywacja automechanika", "Disengage the AI driver"),
|
||||||
|
["jointcontrollerset"] = ("Ustawienie nastawnika zespolonego", "Set the combined controller"),
|
||||||
|
["mastercontrollerincrease"] = ("Zwiększenie nastawnika głównego", "Master controller up"),
|
||||||
|
["mastercontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika głównego", "Master controller up, fast"),
|
||||||
|
["mastercontrollerdecrease"] = ("Zmniejszenie nastawnika głównego", "Master controller down"),
|
||||||
|
["mastercontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika głównego", "Master controller down, fast"),
|
||||||
|
["mastercontrollerset"] = ("Ustawienie nastawnika głównego", "Set the master controller"),
|
||||||
|
["dynamicbrakecontrollerincrease"] = ("Zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake"),
|
||||||
|
["dynamicbrakecontrollerdecrease"] = ("Zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake"),
|
||||||
|
["dynamicbrakecontrollerset"] = ("Ustawienie hamulca elektrodynamicznego", "Set the dynamic brake"),
|
||||||
|
["dynamicbrakecontrollerincreasefast"] = ("Szybkie zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake fast"),
|
||||||
|
["dynamicbrakecontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake fast"),
|
||||||
|
["secondcontrollerincrease"] = ("Zwiększenie nastawnika boczników", "Shunt controller up"),
|
||||||
|
["secondcontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika boczników", "Shunt controller up, fast"),
|
||||||
|
["secondcontrollerdecrease"] = ("Zmniejszenie nastawnika boczników", "Shunt controller down"),
|
||||||
|
["secondcontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika boczników", "Shunt controller down, fast"),
|
||||||
|
["secondcontrollerset"] = ("Ustawienie nastawnika boczników", "Set the shunt controller"),
|
||||||
|
["mucurrentindicatorothersourceactivate"] = ("Zmiana członu dla wskaźnika prądu", "Switch the current gauge to the other unit"),
|
||||||
|
["independentbrakeincrease"] = ("Zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake"),
|
||||||
|
["independentbrakeincreasefast"] = ("Szybkie zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake, fast"),
|
||||||
|
["independentbrakedecrease"] = ("Zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake"),
|
||||||
|
["independentbrakedecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake, fast"),
|
||||||
|
["independentbrakeset"] = ("Ustawienie hamulca lokomotywy", "Set the locomotive brake"),
|
||||||
|
["independentbrakebailoff"] = ("Odluźniacz", "Bail off the locomotive brake"),
|
||||||
|
["universalbrakebutton1"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 1", "Universal brake button 1"),
|
||||||
|
["universalbrakebutton2"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 2", "Universal brake button 2"),
|
||||||
|
["universalbrakebutton3"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 3", "Universal brake button 3"),
|
||||||
|
["trainbrakeincrease"] = ("Zwiększenie stopnia hamowania zaworu maszynisty", "Train brake valve: more braking"),
|
||||||
|
["trainbrakedecrease"] = ("Zmniejszenie stopnia hamowania zaworu maszynisty", "Train brake valve: less braking"),
|
||||||
|
["trainbrakeset"] = ("Ustawienie hamulca zespolonego", "Set the train brake"),
|
||||||
|
["trainbrakecharging"] = ("Napełnianie uderzeniowe przewodu głównego", "Train brake valve: overcharge the brake pipe"),
|
||||||
|
["trainbrakerelease"] = ("Ustawienie zaworu maszynisty w pozycji jazdy", "Train brake valve: running position"),
|
||||||
|
["trainbrakefirstservice"] = ("Pozycja pierwszego stopnia hamowania", "Train brake valve: first braking step"),
|
||||||
|
["trainbrakeservice"] = ("Pozycja hamowania służbowego", "Train brake valve: service braking"),
|
||||||
|
["trainbrakefullservice"] = ("Pozycja hamowania pełnego", "Train brake valve: full service"),
|
||||||
|
["trainbrakehandleoff"] = ("Pozycja odcięcia", "Train brake valve: lap position"),
|
||||||
|
["trainbrakeemergency"] = ("Hamowanie nagłe", "Emergency braking"),
|
||||||
|
["trainbrakebasepressureincrease"] = ("Zwiększenie poziomu ciśnienia w przewodzie głównym", "Raise the brake pipe pressure level"),
|
||||||
|
["trainbrakebasepressuredecrease"] = ("Zmniejszenie poziomu ciśnienia w przewodzie głównym", "Lower the brake pipe pressure level"),
|
||||||
|
["trainbrakebasepressurereset"] = ("Domyślny poziom ciśnienia w przewodzie głównym", "Default brake pipe pressure level"),
|
||||||
|
["trainbrakeoperationtoggle"] = ("Przełączenie stanu hamulca pojazdu", "Toggle the vehicle's brake"),
|
||||||
|
["manualbrakeincrease"] = ("Zwiększenie nastawy hamulca ręcznego", "Apply more hand brake"),
|
||||||
|
["manualbrakedecrease"] = ("Zmniejszenie nastawy hamulca ręcznego", "Release hand brake"),
|
||||||
|
["alarmchaintoggle"] = ("Przełączenie stanu hamulca bezpieczeństwa", "Toggle the emergency brake"),
|
||||||
|
["alarmchainenable"] = ("Pociągnięcie hamulca bezpieczeństwa", "Pull the alarm chain"),
|
||||||
|
["alarmchaindisable"] = ("Zwolnienie hamulca bezpieczeństwa", "Release the alarm chain"),
|
||||||
|
["wheelspinbrakeactivate"] = ("Aktywacja podhamowania przeciwpoślizgowego", "Anti-slip brake"),
|
||||||
|
["sandboxactivate"] = ("Aktywacja piasecznicy", "Sander"),
|
||||||
|
["autosandboxtoggle"] = ("Przełączenie automatycznej piasecznicy", "Toggle the automatic sander"),
|
||||||
|
["autosandboxactivate"] = ("Włączenie automatycznej piasecznicy", "Turn the automatic sander on"),
|
||||||
|
["autosandboxdeactivate"] = ("Wyłączenie automatycznej piasecznicy", "Turn the automatic sander off"),
|
||||||
|
["reverserincrease"] = ("Zwiększenie pozycji nastawnika kierunku", "Reverser up"),
|
||||||
|
["reverserdecrease"] = ("Zmniejszenie pozycji nastawnika kierunku", "Reverser down"),
|
||||||
|
["reverserforwardhigh"] = ("Pozycja jazdy do przodu II nastawnika kierunku", "Reverser: forward II"),
|
||||||
|
["reverserforward"] = ("Pozycja jazdy do przodu nastawnika kierunku", "Reverser: forward"),
|
||||||
|
["reverserneutral"] = ("Pozycja neutralna nastawnika kierunku", "Reverser: neutral"),
|
||||||
|
["reverserbackward"] = ("Pozycja jazdy do tyłu nastawnika kierunku", "Reverser: backward"),
|
||||||
|
["waterpumpbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego pompy wody", "Toggle the water pump circuit breaker"),
|
||||||
|
["waterpumpbreakerclose"] = ("Załączenie wyłącznika pompy wody", "Close the water pump breaker"),
|
||||||
|
["waterpumpbreakeropen"] = ("Wyłączenie wyłącznika pompy wody", "Open the water pump breaker"),
|
||||||
|
["waterpumptoggle"] = ("Przełączenie stanu pompy wody", "Toggle the water pump"),
|
||||||
|
["waterpumpenable"] = ("Włączenie pompy wody", "Turn the water pump on"),
|
||||||
|
["waterpumpdisable"] = ("Wyłączenie pompy wody", "Turn the water pump off"),
|
||||||
|
["waterheaterbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego podgrzewacza wody", "Toggle the water heater circuit breaker"),
|
||||||
|
["waterheaterbreakerclose"] = ("Załączenie wyłącznika podgrzewacza wody", "Close the water heater breaker"),
|
||||||
|
["waterheaterbreakeropen"] = ("Wyłączenie wyłącznika podgrzewacza wody", "Open the water heater breaker"),
|
||||||
|
["waterheatertoggle"] = ("Przełączenie stanu podgrzewacza wody", "Toggle the water heater"),
|
||||||
|
["waterheaterenable"] = ("Włączenie podgrzewacza wody", "Turn the water heater on"),
|
||||||
|
["waterheaterdisable"] = ("Wyłączenie podgrzewacza wody", "Turn the water heater off"),
|
||||||
|
["watercircuitslinktoggle"] = ("Przełączenie stanu połączenia obiegów wody", "Toggle the link between the water circuits"),
|
||||||
|
["watercircuitslinkenable"] = ("Połączenie obiegów wody", "Link the water circuits"),
|
||||||
|
["watercircuitslinkdisable"] = ("Rozłączenie obiegów wody", "Unlink the water circuits"),
|
||||||
|
["fuelpumptoggle"] = ("Przełączenie stanu pompy paliwa", "Toggle the fuel pump"),
|
||||||
|
["fuelpumpenable"] = ("Włączenie pompy paliwa", "Turn the fuel pump on"),
|
||||||
|
["fuelpumpdisable"] = ("Wyłączenie pompy paliwa", "Turn the fuel pump off"),
|
||||||
|
["oilpumptoggle"] = ("Przełączenie stanu pompy oleju", "Toggle the oil pump"),
|
||||||
|
["oilpumpenable"] = ("Włączenie pompy oleju", "Turn the oil pump on"),
|
||||||
|
["oilpumpdisable"] = ("Wyłączenie pompy oleju", "Turn the oil pump off"),
|
||||||
|
["linebreakertoggle"] = ("Przełączenie stanu wyłącznika szybkiego", "Toggle the line breaker"),
|
||||||
|
["linebreakeropen"] = ("Wyłączenie wyłącznika szybkiego", "Open the line breaker"),
|
||||||
|
["linebreakerclose"] = ("Załączenie wyłącznika szybkiego", "Close the line breaker"),
|
||||||
|
["convertertoggle"] = ("Przełączenie stanu przetwornicy", "Toggle the converter"),
|
||||||
|
["converterenable"] = ("Włączenie przetwornicy", "Turn the converter on"),
|
||||||
|
["converterdisable"] = ("Wyłączenie przetwornicy", "Turn the converter off"),
|
||||||
|
["convertertogglelocal"] = ("Przełączenie stanu przetwornicy w obsadzonym członie", "Toggle the converter in the occupied unit"),
|
||||||
|
["converteroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego przetwornicy", "Reset the converter overload relay"),
|
||||||
|
["compressortoggle"] = ("Przełączenie stanu sprężarki", "Toggle the compressor"),
|
||||||
|
["compressorenable"] = ("Włączenie sprężarki", "Turn the compressor on"),
|
||||||
|
["compressordisable"] = ("Wyłączenie sprężarki", "Turn the compressor off"),
|
||||||
|
["compressortogglelocal"] = ("Przełączenie stanu sprężarki w obsadzonym członie", "Toggle the compressor in the occupied unit"),
|
||||||
|
["compressorpresetactivatenext"] = ("Następny tryb pracy sprężarek", "Next compressor mode"),
|
||||||
|
["compressorpresetactivateprevious"] = ("Poprzedni tryb pracy sprężarek", "Previous compressor mode"),
|
||||||
|
["compressorpresetactivatedefault"] = ("Domyślny tryb pracy sprężarek", "Default compressor mode"),
|
||||||
|
["motoroverloadrelaythresholdtoggle"] = ("Przełączenie rozruchu niskiego/wysokiego", "Switch between low and high starting current"),
|
||||||
|
["motoroverloadrelaythresholdsetlow"] = ("Niski próg przekaźnika nadmiarowego silników", "Motor overload relay threshold low"),
|
||||||
|
["motoroverloadrelaythresholdsethigh"] = ("Wysoki próg przekaźnika nadmiarowego silników", "Motor overload relay threshold high"),
|
||||||
|
["motoroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego silników", "Reset the traction motor overload relay"),
|
||||||
|
["universalrelayreset1"] = ("Odblokowanie zdefiniowanych przekaźników nr 1", "Reset the defined relays, set 1"),
|
||||||
|
["universalrelayreset2"] = ("Odblokowanie zdefiniowanych przekaźników nr 2", "Reset the defined relays, set 2"),
|
||||||
|
["universalrelayreset3"] = ("Odblokowanie zdefiniowanych przekaźników nr 3", "Reset the defined relays, set 3"),
|
||||||
|
["notchingrelaytoggle"] = ("Przełączenie stanu przekaźnika samoczynnego rozruchu", "Toggle the automatic notching relay"),
|
||||||
|
["epbrakecontroltoggle"] = ("Przełączenie stanu hamulca elektropneumatycznego", "Toggle the electro-pneumatic brake"),
|
||||||
|
["epbrakecontrolenable"] = ("Włączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake on"),
|
||||||
|
["epbrakecontroldisable"] = ("Wyłączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake off"),
|
||||||
|
["trainbrakeoperationmodeincrease"] = ("Zmiana trybu pracy hamulca na bardziej efektywny", "Brake operation mode: more effective"),
|
||||||
|
["trainbrakeoperationmodedecrease"] = ("Zmiana trybu pracy hamulca na prostszy", "Brake operation mode: simpler"),
|
||||||
|
["brakeactingspeedincrease"] = ("Wybór szybszego trybu działania hamulca pociągu", "Faster train brake acting speed"),
|
||||||
|
["brakeactingspeeddecrease"] = ("Wybór wolniejszego trybu działania hamulca pociągu", "Slower train brake acting speed"),
|
||||||
|
["brakeactingspeedsetcargo"] = ("Wybór trybu hamulca dla pociągu towarowego", "Brake acting speed for a freight train"),
|
||||||
|
["brakeactingspeedsetpassenger"] = ("Wybór trybu hamulca dla pociągu osobowego", "Brake acting speed for a passenger train"),
|
||||||
|
["brakeactingspeedsetrapid"] = ("Wybór trybu hamulca dla pociągu pospiesznego", "Brake acting speed for an express train"),
|
||||||
|
["brakeloadcompensationincrease"] = ("Wybór wyższego przełożenia hamulca", "Higher brake load setting"),
|
||||||
|
["brakeloadcompensationdecrease"] = ("Wybór niższego przełożenia hamulca", "Lower brake load setting"),
|
||||||
|
["mubrakingindicatortoggle"] = ("Przełączenie stanu wskaźnika hamowania członów EZT", "Toggle the EMU unit braking indicator"),
|
||||||
|
["alerteracknowledge"] = ("Wygaszenie czuwaka i SHP", "Acknowledge the vigilance device and cab signalling"),
|
||||||
|
["cabsignalacknowledge"] = ("Wygaszenie SHP", "Acknowledge the cab signalling"),
|
||||||
|
["hornlowactivate"] = ("Aktywacja syreny niskotonowej", "Low-tone horn"),
|
||||||
|
["hornhighactivate"] = ("Aktywacja syreny wysokotonowej", "High-tone horn"),
|
||||||
|
["whistleactivate"] = ("Aktywacja gwizdka", "Whistle"),
|
||||||
|
["radiotoggle"] = ("Przełączenie stanu radiotelefonu", "Toggle the radio"),
|
||||||
|
["radioenable"] = ("Włączenie radiotelefonu", "Turn the radio on"),
|
||||||
|
["radiodisable"] = ("Wyłączenie radiotelefonu", "Turn the radio off"),
|
||||||
|
["radiochannelincrease"] = ("Wybór kolejnego kanału radia", "Next radio channel"),
|
||||||
|
["radiochanneldecrease"] = ("Wybór poprzedniego kanału radia", "Previous radio channel"),
|
||||||
|
["radiochannelset"] = ("Ustawienie kanału radiotelefonu", "Set the radio channel"),
|
||||||
|
["radiostopsend"] = ("Emisja radiostopu", "Send radio-stop"),
|
||||||
|
["radiostopenable"] = ("Włączenie sygnału Radio-Stop", "Send Radio-Stop"),
|
||||||
|
["radiostopdisable"] = ("Wyłączenie sygnału Radio-Stop", "Stop sending Radio-Stop"),
|
||||||
|
["radiostoptest"] = ("Lokalny test radiostopu", "Local radio-stop test"),
|
||||||
|
["radiocall1send"] = ("Wywołanie radiowe 1", "Radio call 1"),
|
||||||
|
["radiocall3send"] = ("Emisja sygnału zew3", "Send the call-3 signal"),
|
||||||
|
["radiovolumeincrease"] = ("Zwiększenie głośności radia", "Radio volume up"),
|
||||||
|
["radiovolumedecrease"] = ("Zmniejszenie głośności radia", "Radio volume down"),
|
||||||
|
["radiovolumeset"] = ("Ustawienie głośności radiotelefonu", "Set the radio volume"),
|
||||||
|
["radiofusetoggle"] = ("Przełączenie bezpiecznika radiotelefonu", "Toggle the radio fuse"),
|
||||||
|
["radiofuseenable"] = ("Załączenie bezpiecznika radiotelefonu", "Close the radio fuse"),
|
||||||
|
["radiofusedisable"] = ("Wyłączenie bezpiecznika radiotelefonu", "Open the radio fuse"),
|
||||||
|
["cabchangeforward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku czoła pociągu", "Move to the next compartment towards the front"),
|
||||||
|
["cabchangebackward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku tyłu pociągu", "Move to the next compartment towards the rear"),
|
||||||
|
["modernlightdimmerdecrease"] = ("Przyciemnienie oświetlenia", "Dim the lights"),
|
||||||
|
["modernlightdimmerincrease"] = ("Rozjaśnienie oświetlenia", "Brighten the lights"),
|
||||||
|
["nearestcarcouplingincrease"] = ("Łączenie sprzęgów", "Couple"),
|
||||||
|
["nearestcarcouplingdisconnect"] = ("Rozłączenie sprzęgów", "Uncouple"),
|
||||||
|
["nearestcarcoupleradapterattach"] = ("Nałożenie półsprzęgu", "Attach the coupler adapter"),
|
||||||
|
["nearestcarcoupleradapterremove"] = ("Demontaż półsprzęgu", "Remove the coupler adapter"),
|
||||||
|
["occupiedcarcouplingdisconnect"] = ("Rozłączenie sprzęgów po stronie obsadzonej kabiny", "Uncouple at the occupied cab's end"),
|
||||||
|
["occupiedcarcouplingdisconnectback"] = ("Rozłączenie sprzęgu z tyłu zajmowanego pojazdu", "Uncouple at the back of the occupied car"),
|
||||||
|
["doortoggleleft"] = ("Przełączenie stanu drzwi lewych", "Toggle the left doors"),
|
||||||
|
["doortoggleright"] = ("Przełączenie stanu drzwi prawych", "Toggle the right doors"),
|
||||||
|
["doorpermitleft"] = ("Zezwolenie na otwarcie drzwi lewych", "Permit opening the left doors"),
|
||||||
|
["doorpermitright"] = ("Zezwolenie na otwarcie drzwi prawych", "Permit opening the right doors"),
|
||||||
|
["doorpermitpresetactivatenext"] = ("Aktywacja kolejnej konfiguracji zezwolenia na otwarcie drzwi", "Next door permit preset"),
|
||||||
|
["doorpermitpresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji zezwolenia na otwarcie drzwi", "Previous door permit preset"),
|
||||||
|
["dooropenleft"] = ("Otwarcie drzwi z lewej", "Open the left doors"),
|
||||||
|
["dooropenright"] = ("Otwarcie drzwi z prawej", "Open the right doors"),
|
||||||
|
["dooropenall"] = ("Otwarcie drzwi z zezwoleniem", "Open the permitted doors"),
|
||||||
|
["doorcloseleft"] = ("Zamknięcie drzwi lewych", "Close the left doors"),
|
||||||
|
["doorcloseright"] = ("Zamknięcie drzwi prawych", "Close the right doors"),
|
||||||
|
["doorcloseall"] = ("Zamknięcie wszystkich drzwi", "Close all doors"),
|
||||||
|
["doorsteptoggle"] = ("Przełączenie stanu stopnia drzwi", "Toggle the door steps"),
|
||||||
|
["doormodetoggle"] = ("Przełączenie trybu działania drzwi", "Toggle the door operation mode"),
|
||||||
|
["mirrorstoggle"] = ("Złożenie lub rozłożenie lusterek", "Fold or unfold the mirrors"),
|
||||||
|
["departureannounce"] = ("Sygnał odjazdu", "Departure signal"),
|
||||||
|
["doorlocktoggle"] = ("Przełączenie stanu blokady drzwi", "Toggle the door lock"),
|
||||||
|
["pantographcompressorvalvetoggle"] = ("Przełączenie stanu kurka trójdrogowego", "Toggle the three-way pantograph valve"),
|
||||||
|
["pantographcompressorvalveenable"] = ("Otwarcie zaworu sprężarki pantografów", "Open the pantograph compressor valve"),
|
||||||
|
["pantographcompressorvalvedisable"] = ("Zamknięcie zaworu sprężarki pantografów", "Close the pantograph compressor valve"),
|
||||||
|
["pantographcompressoractivate"] = ("Aktywacja sprężarki pomocniczej", "Auxiliary pantograph compressor"),
|
||||||
|
["pantographtogglefront"] = ("Przełączenie stanu pantografu przedniego", "Toggle the front pantograph"),
|
||||||
|
["pantographtogglerear"] = ("Przełączenie stanu pantografu tylnego", "Toggle the rear pantograph"),
|
||||||
|
["pantographraisefront"] = ("Podniesienie przedniego pantografu", "Raise the front pantograph"),
|
||||||
|
["pantographraiserear"] = ("Podniesienie tylnego pantografu", "Raise the rear pantograph"),
|
||||||
|
["pantographlowerfront"] = ("Opuszczenie przedniego pantografu", "Lower the front pantograph"),
|
||||||
|
["pantographlowerrear"] = ("Opuszczenie tylnego pantografu", "Lower the rear pantograph"),
|
||||||
|
["pantographlowerall"] = ("Opuszczenie wszystkich pantografów", "Lower all pantographs"),
|
||||||
|
["pantographselectnext"] = ("Aktywacja kolejnej konfiguracji wyboru pantografów", "Next pantograph selection preset"),
|
||||||
|
["pantographselectprevious"] = ("Aktywacja poprzedniej konfiguracji wyboru pantografów", "Previous pantograph selection preset"),
|
||||||
|
["pantographtoggleselected"] = ("Przełączenie stanu wybranych pantografów", "Toggle the selected pantographs"),
|
||||||
|
["pantographraiseselected"] = ("Podniesienie wybranych pantografów", "Raise the selected pantographs"),
|
||||||
|
["pantographlowerselected"] = ("Opuszczenie wybranych pantografów", "Lower the selected pantographs"),
|
||||||
|
["pantographvalvesupdate"] = ("Ustawienie zaworów pantografów", "Set the pantograph valves"),
|
||||||
|
["pantographvalvesoff"] = ("Zamknięcie zaworów pantografów", "Close the pantograph valves"),
|
||||||
|
["heatingtoggle"] = ("Przełączenie stanu ogrzewania pociągu", "Toggle train heating"),
|
||||||
|
["heatingenable"] = ("Włączenie ogrzewania pociągu", "Turn the train heating on"),
|
||||||
|
["heatingdisable"] = ("Wyłączenie ogrzewania pociągu", "Turn the train heating off"),
|
||||||
|
["lightspresetactivatenext"] = ("Aktywacja kolejnej konfiguracji reflektorów", "Next headlight preset"),
|
||||||
|
["lightspresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji reflektorów", "Previous headlight preset"),
|
||||||
|
["headlighttoggleleft"] = ("Przełączenie stanu lewego reflektora", "Toggle the left headlight"),
|
||||||
|
["headlightenableleft"] = ("Włączenie lewego reflektora z przodu", "Turn the front left headlight on"),
|
||||||
|
["headlightdisableleft"] = ("Wyłączenie lewego reflektora z przodu", "Turn the front left headlight off"),
|
||||||
|
["headlighttoggleright"] = ("Przełączenie stanu prawego reflektora", "Toggle the right headlight"),
|
||||||
|
["headlightenableright"] = ("Włączenie prawego reflektora z przodu", "Turn the front right headlight on"),
|
||||||
|
["headlightdisableright"] = ("Wyłączenie prawego reflektora z przodu", "Turn the front right headlight off"),
|
||||||
|
["headlighttoggleupper"] = ("Przełączenie stanu górnego reflektora", "Toggle the upper headlight"),
|
||||||
|
["headlightenableupper"] = ("Włączenie górnego reflektora z przodu", "Turn the front upper headlight on"),
|
||||||
|
["headlightdisableupper"] = ("Wyłączenie górnego reflektora z przodu", "Turn the front upper headlight off"),
|
||||||
|
["redmarkertoggleleft"] = ("Przełączenie lewego światła czerwonego", "Toggle the left red marker"),
|
||||||
|
["redmarkerenableleft"] = ("Włączenie lewego sygnału końcowego z przodu", "Turn the front left red marker on"),
|
||||||
|
["redmarkerdisableleft"] = ("Wyłączenie lewego sygnału końcowego z przodu", "Turn the front left red marker off"),
|
||||||
|
["redmarkertoggleright"] = ("Przełączenie prawego światła czerwonego", "Toggle the right red marker"),
|
||||||
|
["redmarkerenableright"] = ("Włączenie prawego sygnału końcowego z przodu", "Turn the front right red marker on"),
|
||||||
|
["redmarkerdisableright"] = ("Wyłączenie prawego sygnału końcowego z przodu", "Turn the front right red marker off"),
|
||||||
|
["headlighttogglerearleft"] = ("Przełączenie stanu lewego tylnego reflektora", "Toggle the rear left headlight"),
|
||||||
|
["headlightenablerearleft"] = ("Włączenie lewego reflektora z tyłu", "Turn the rear left headlight on"),
|
||||||
|
["headlightdisablerearleft"] = ("Wyłączenie lewego reflektora z tyłu", "Turn the rear left headlight off"),
|
||||||
|
["headlighttogglerearright"] = ("Przełączenie stanu prawego tylnego reflektora", "Toggle the rear right headlight"),
|
||||||
|
["headlightenablerearright"] = ("Włączenie prawego reflektora z tyłu", "Turn the rear right headlight on"),
|
||||||
|
["headlightdisablerearright"] = ("Wyłączenie prawego reflektora z tyłu", "Turn the rear right headlight off"),
|
||||||
|
["headlighttogglerearupper"] = ("Przełączenie stanu górnego tylnego reflektora", "Toggle the rear upper headlight"),
|
||||||
|
["headlightenablerearupper"] = ("Włączenie górnego reflektora z tyłu", "Turn the rear upper headlight on"),
|
||||||
|
["headlightdisablerearupper"] = ("Wyłączenie górnego reflektora z tyłu", "Turn the rear upper headlight off"),
|
||||||
|
["redmarkertogglerearleft"] = ("Przełączenie lewego tylnego światła czerwonego", "Toggle the rear left red marker"),
|
||||||
|
["redmarkerenablerearleft"] = ("Włączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker on"),
|
||||||
|
["redmarkerdisablerearleft"] = ("Wyłączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker off"),
|
||||||
|
["redmarkertogglerearright"] = ("Przełączenie prawego tylnego światła czerwonego", "Toggle the rear right red marker"),
|
||||||
|
["redmarkerenablerearright"] = ("Włączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker on"),
|
||||||
|
["redmarkerdisablerearright"] = ("Wyłączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker off"),
|
||||||
|
["redmarkerstoggle"] = ("Przełączenie świateł końca pociągu", "Toggle the end-of-train lights"),
|
||||||
|
["endsignalstoggle"] = ("Przełączenie tabliczek końca pociągu", "Toggle the end-of-train plates"),
|
||||||
|
["headlightsdimtoggle"] = ("Przełączenie przyciemnienia reflektorów", "Toggle headlight dimming"),
|
||||||
|
["headlightsdimenable"] = ("Przyciemnienie reflektorów", "Dim the headlights"),
|
||||||
|
["headlightsdimdisable"] = ("Pełne światło reflektorów", "Headlights at full"),
|
||||||
|
["motorconnectorsopen"] = ("Rozłączenie styczników liniowych", "Open the line contactors"),
|
||||||
|
["motorconnectorsclose"] = ("Załączenie styczników liniowych", "Close the line contactors"),
|
||||||
|
["motordisconnect"] = ("Odłączenie uszkodzonych silników", "Cut out the damaged motors"),
|
||||||
|
["interiorlighttoggle"] = ("Przełączenie stanu oświetlenia kabiny", "Toggle the cab light"),
|
||||||
|
["interiorlightenable"] = ("Włączenie oświetlenia kabiny", "Turn the cab light on"),
|
||||||
|
["interiorlightdisable"] = ("Wyłączenie oświetlenia kabiny", "Turn the cab light off"),
|
||||||
|
["interiorlightdimtoggle"] = ("Przełączenie przyciemnienia oświetlenia kabiny", "Toggle cab light dimming"),
|
||||||
|
["interiorlightdimenable"] = ("Przyciemnienie oświetlenia kabiny", "Dim the cab light"),
|
||||||
|
["interiorlightdimdisable"] = ("Pełne oświetlenie kabiny", "Cab light at full"),
|
||||||
|
["compartmentlightstoggle"] = ("Przełączenie stanu oświetlenia przedziałów", "Toggle the compartment lights"),
|
||||||
|
["compartmentlightsenable"] = ("Włączenie oświetlenia przedziałów", "Turn the compartment lights on"),
|
||||||
|
["compartmentlightsdisable"] = ("Wyłączenie oświetlenia przedziałów", "Turn the compartment lights off"),
|
||||||
|
["instrumentlighttoggle"] = ("Przełączenie stanu oświetlenia przyrządów", "Toggle the instrument lights"),
|
||||||
|
["instrumentlightenable"] = ("Włączenie oświetlenia przyrządów", "Turn the instrument lights on"),
|
||||||
|
["instrumentlightdisable"] = ("Wyłączenie oświetlenia przyrządów", "Turn the instrument lights off"),
|
||||||
|
["dashboardlighttoggle"] = ("Przełączenie stanu oświetlenia pulpitu", "Toggle the dashboard light"),
|
||||||
|
["dashboardlightenable"] = ("Włączenie oświetlenia pulpitu", "Turn the dashboard light on"),
|
||||||
|
["dashboardlightdisable"] = ("Wyłączenie oświetlenia pulpitu", "Turn the dashboard light off"),
|
||||||
|
["timetablelighttoggle"] = ("Przełączenie stanu oświetlenia rozkładu jazdy", "Toggle the timetable light"),
|
||||||
|
["timetablelightenable"] = ("Włączenie oświetlenia rozkładu jazdy", "Turn the timetable light on"),
|
||||||
|
["timetablelightdisable"] = ("Wyłączenie oświetlenia rozkładu jazdy", "Turn the timetable light off"),
|
||||||
|
["generictoggle0"] = ("Przełączenie elementu uniwersalnego nr 0", "Generic switch 0"),
|
||||||
|
["generictoggle1"] = ("Przełączenie elementu uniwersalnego nr 1", "Generic switch 1"),
|
||||||
|
["generictoggle2"] = ("Przełączenie elementu uniwersalnego nr 2", "Generic switch 2"),
|
||||||
|
["generictoggle3"] = ("Przełączenie elementu uniwersalnego nr 3", "Generic switch 3"),
|
||||||
|
["generictoggle4"] = ("Przełączenie elementu uniwersalnego nr 4", "Generic switch 4"),
|
||||||
|
["generictoggle5"] = ("Przełączenie elementu uniwersalnego nr 5", "Generic switch 5"),
|
||||||
|
["generictoggle6"] = ("Przełączenie elementu uniwersalnego nr 6", "Generic switch 6"),
|
||||||
|
["generictoggle7"] = ("Przełączenie elementu uniwersalnego nr 7", "Generic switch 7"),
|
||||||
|
["generictoggle8"] = ("Przełączenie elementu uniwersalnego nr 8", "Generic switch 8"),
|
||||||
|
["generictoggle9"] = ("Przełączenie elementu uniwersalnego nr 9", "Generic switch 9"),
|
||||||
|
["generictoggle10"] = ("Przełączenie elementu uniwersalnego nr 10", "Generic switch 10"),
|
||||||
|
["generictoggle11"] = ("Przełączenie elementu uniwersalnego nr 11", "Generic switch 11"),
|
||||||
|
["generictoggle12"] = ("Przełączenie elementu uniwersalnego nr 12", "Generic switch 12"),
|
||||||
|
["generictoggle13"] = ("Przełączenie elementu uniwersalnego nr 13", "Generic switch 13"),
|
||||||
|
["generictoggle14"] = ("Przełączenie elementu uniwersalnego nr 14", "Generic switch 14"),
|
||||||
|
["generictoggle15"] = ("Przełączenie elementu uniwersalnego nr 15", "Generic switch 15"),
|
||||||
|
["generictoggle16"] = ("Przełączenie elementu uniwersalnego nr 16", "Generic switch 16"),
|
||||||
|
["generictoggle17"] = ("Przełączenie elementu uniwersalnego nr 17", "Generic switch 17"),
|
||||||
|
["generictoggle18"] = ("Przełączenie elementu uniwersalnego nr 18", "Generic switch 18"),
|
||||||
|
["generictoggle19"] = ("Przełączenie elementu uniwersalnego nr 19", "Generic switch 19"),
|
||||||
|
["generictoggle20"] = ("Przełączenie elementu uniwersalnego nr 20", "Generic switch 20"),
|
||||||
|
["generictoggle21"] = ("Przełączenie elementu uniwersalnego nr 21", "Generic switch 21"),
|
||||||
|
["generictoggle22"] = ("Przełączenie elementu uniwersalnego nr 22", "Generic switch 22"),
|
||||||
|
["generictoggle23"] = ("Przełączenie elementu uniwersalnego nr 23", "Generic switch 23"),
|
||||||
|
["generictoggle24"] = ("Przełączenie elementu uniwersalnego nr 24", "Generic switch 24"),
|
||||||
|
["generictoggle25"] = ("Przełączenie elementu uniwersalnego nr 25", "Generic switch 25"),
|
||||||
|
["generictoggle26"] = ("Przełączenie elementu uniwersalnego nr 26", "Generic switch 26"),
|
||||||
|
["generictoggle27"] = ("Przełączenie elementu uniwersalnego nr 27", "Generic switch 27"),
|
||||||
|
["generictoggle28"] = ("Przełączenie elementu uniwersalnego nr 28", "Generic switch 28"),
|
||||||
|
["generictoggle29"] = ("Przełączenie elementu uniwersalnego nr 29", "Generic switch 29"),
|
||||||
|
["batterytoggle"] = ("Przełączenie stanu akumulatorów", "Toggle the batteries"),
|
||||||
|
["batteryenable"] = ("Włączenie baterii", "Turn the battery on"),
|
||||||
|
["batterydisable"] = ("Wyłączenie baterii", "Turn the battery off"),
|
||||||
|
["cabactivationtoggle"] = ("Przełączenie stanu aktywacji kabiny", "Toggle cab activation"),
|
||||||
|
["cabactivationenable"] = ("Aktywacja kabiny", "Activate the cab"),
|
||||||
|
["cabactivationdisable"] = ("Dezaktywacja kabiny", "Deactivate the cab"),
|
||||||
|
["motorblowerstogglefront"] = ("Przełączenie stanu wentylatorów przednich silników trakcyjnych", "Toggle the front traction motor blowers"),
|
||||||
|
["motorblowerstogglerear"] = ("Przełączenie stanu wentylatorów tylnych silników trakcyjnych", "Toggle the rear traction motor blowers"),
|
||||||
|
["motorblowersdisableall"] = ("Wyłączenie wszystkich wentylatorów silników trakcyjnych", "Switch off all traction motor blowers"),
|
||||||
|
["coolingfanstoggle"] = ("Przełączenie stanu wentylatorów oporów rozruchowych", "Toggle the starting resistor fans"),
|
||||||
|
["tempomattoggle"] = ("Przełączenie stanu tempomatu", "Toggle the cruise control"),
|
||||||
|
["springbraketoggle"] = ("Przełączenie stanu hamulca sprężynowego", "Toggle the spring brake"),
|
||||||
|
["springbrakeenable"] = ("Załączenie hamulca sprężynowego", "Apply the spring brake"),
|
||||||
|
["springbrakedisable"] = ("Zwolnienie hamulca sprężynowego", "Release the spring brake"),
|
||||||
|
["springbrakeshutofftoggle"] = ("Przełączenie stanu kurka odcinającego hamulca sprężynowego", "Toggle the spring brake shut-off cock"),
|
||||||
|
["springbrakeshutoffenable"] = ("Odcięcie hamulca sprężynowego", "Cut the spring brake off"),
|
||||||
|
["springbrakeshutoffdisable"] = ("Przywrócenie hamulca sprężynowego", "Cut the spring brake back in"),
|
||||||
|
["springbrakerelease"] = ("Luzowanie hamulca sprężynowego", "Release the spring brake"),
|
||||||
|
["distancecounteractivate"] = ("Załączenie miernika przejechanego dystansu", "Start the distance counter"),
|
||||||
|
["speedcontrolincrease"] = ("Zwiększenie prędkości utrzymywanej przez tempomat", "Cruise control speed up"),
|
||||||
|
["speedcontroldecrease"] = ("Zmniejszenie prędkości utrzymywanej przez tempomat", "Cruise control speed down"),
|
||||||
|
["speedcontrolpowerincrease"] = ("Zwiększenie maksymalnego poziomu mocy dostępnej dla tempomatu", "More power for the cruise control"),
|
||||||
|
["speedcontrolpowerdecrease"] = ("Zmniejszenie maksymalnego poziomu mocy dostępnej dla tempomatu", "Less power for the cruise control"),
|
||||||
|
["speedcontrolbutton0"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 0", "Cruise control preset speed 0"),
|
||||||
|
["speedcontrolbutton1"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 1", "Cruise control preset speed 1"),
|
||||||
|
["speedcontrolbutton2"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 2", "Cruise control preset speed 2"),
|
||||||
|
["speedcontrolbutton3"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 3", "Cruise control preset speed 3"),
|
||||||
|
["speedcontrolbutton4"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 4", "Cruise control preset speed 4"),
|
||||||
|
["speedcontrolbutton5"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 5", "Cruise control preset speed 5"),
|
||||||
|
["speedcontrolbutton6"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 6", "Cruise control preset speed 6"),
|
||||||
|
["speedcontrolbutton7"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 7", "Cruise control preset speed 7"),
|
||||||
|
["speedcontrolbutton8"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 8", "Cruise control preset speed 8"),
|
||||||
|
["speedcontrolbutton9"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 9", "Cruise control preset speed 9"),
|
||||||
|
["inverterenable1"] = ("Włączenie falownika 1", "Turn inverter 1 on"),
|
||||||
|
["inverterenable2"] = ("Włączenie falownika 2", "Turn inverter 2 on"),
|
||||||
|
["inverterenable3"] = ("Włączenie falownika 3", "Turn inverter 3 on"),
|
||||||
|
["inverterenable4"] = ("Włączenie falownika 4", "Turn inverter 4 on"),
|
||||||
|
["inverterenable5"] = ("Włączenie falownika 5", "Turn inverter 5 on"),
|
||||||
|
["inverterenable6"] = ("Włączenie falownika 6", "Turn inverter 6 on"),
|
||||||
|
["inverterenable7"] = ("Włączenie falownika 7", "Turn inverter 7 on"),
|
||||||
|
["inverterenable8"] = ("Włączenie falownika 8", "Turn inverter 8 on"),
|
||||||
|
["inverterenable9"] = ("Włączenie falownika 9", "Turn inverter 9 on"),
|
||||||
|
["inverterenable10"] = ("Włączenie falownika 10", "Turn inverter 10 on"),
|
||||||
|
["inverterenable11"] = ("Włączenie falownika 11", "Turn inverter 11 on"),
|
||||||
|
["inverterenable12"] = ("Włączenie falownika 12", "Turn inverter 12 on"),
|
||||||
|
["inverterdisable1"] = ("Wyłączenie falownika 1", "Turn inverter 1 off"),
|
||||||
|
["inverterdisable2"] = ("Wyłączenie falownika 2", "Turn inverter 2 off"),
|
||||||
|
["inverterdisable3"] = ("Wyłączenie falownika 3", "Turn inverter 3 off"),
|
||||||
|
["inverterdisable4"] = ("Wyłączenie falownika 4", "Turn inverter 4 off"),
|
||||||
|
["inverterdisable5"] = ("Wyłączenie falownika 5", "Turn inverter 5 off"),
|
||||||
|
["inverterdisable6"] = ("Wyłączenie falownika 6", "Turn inverter 6 off"),
|
||||||
|
["inverterdisable7"] = ("Wyłączenie falownika 7", "Turn inverter 7 off"),
|
||||||
|
["inverterdisable8"] = ("Wyłączenie falownika 8", "Turn inverter 8 off"),
|
||||||
|
["inverterdisable9"] = ("Wyłączenie falownika 9", "Turn inverter 9 off"),
|
||||||
|
["inverterdisable10"] = ("Wyłączenie falownika 10", "Turn inverter 10 off"),
|
||||||
|
["inverterdisable11"] = ("Wyłączenie falownika 11", "Turn inverter 11 off"),
|
||||||
|
["inverterdisable12"] = ("Wyłączenie falownika 12", "Turn inverter 12 off"),
|
||||||
|
["invertertoggle1"] = ("Przełączenie falownika 1", "Toggle inverter 1"),
|
||||||
|
["invertertoggle2"] = ("Przełączenie falownika 2", "Toggle inverter 2"),
|
||||||
|
["invertertoggle3"] = ("Przełączenie falownika 3", "Toggle inverter 3"),
|
||||||
|
["invertertoggle4"] = ("Przełączenie falownika 4", "Toggle inverter 4"),
|
||||||
|
["invertertoggle5"] = ("Przełączenie falownika 5", "Toggle inverter 5"),
|
||||||
|
["invertertoggle6"] = ("Przełączenie falownika 6", "Toggle inverter 6"),
|
||||||
|
["invertertoggle7"] = ("Przełączenie falownika 7", "Toggle inverter 7"),
|
||||||
|
["invertertoggle8"] = ("Przełączenie falownika 8", "Toggle inverter 8"),
|
||||||
|
["invertertoggle9"] = ("Przełączenie falownika 9", "Toggle inverter 9"),
|
||||||
|
["invertertoggle10"] = ("Przełączenie falownika 10", "Toggle inverter 10"),
|
||||||
|
["invertertoggle11"] = ("Przełączenie falownika 11", "Toggle inverter 11"),
|
||||||
|
["invertertoggle12"] = ("Przełączenie falownika 12", "Toggle inverter 12"),
|
||||||
|
["vehiclemoveforwards"] = ("Przesunięcie pojazdu do przodu", "Move the vehicle forwards"),
|
||||||
|
["vehiclemovebackwards"] = ("Przesunięcie pojazdu do tyłu", "Move the vehicle backwards"),
|
||||||
|
["vehicleboost"] = ("Przyspieszenie pojazdu", "Boost the vehicle"),
|
||||||
|
["wiperswitchincrease"] = ("Szybsza praca wycieraczek", "Wipers faster"),
|
||||||
|
["wiperswitchdecrease"] = ("Wolniejsza praca wycieraczek", "Wipers slower"),
|
||||||
|
["lightsset"] = ("Ustawienie świateł", "Set the lights"),
|
||||||
|
["oilfuelpumptoggle"] = ("Przełączenie pomp oleju i paliwa", "Toggle the oil and fuel pumps"),
|
||||||
|
["linebreakertoggleb"] = ("Przełączenie wyłącznika szybkiego B", "Toggle line breaker B"),
|
||||||
|
["linebreakeropenb"] = ("Wyłączenie wyłącznika szybkiego B", "Open line breaker B"),
|
||||||
|
["linebreakercloseb"] = ("Załączenie wyłącznika szybkiego B", "Close line breaker B"),
|
||||||
|
["linebreakertogglec"] = ("Przełączenie wyłącznika szybkiego C", "Toggle line breaker C"),
|
||||||
|
["linebreakeropenc"] = ("Wyłączenie wyłącznika szybkiego C", "Open line breaker C"),
|
||||||
|
["linebreakerclosec"] = ("Załączenie wyłącznika szybkiego C", "Close line breaker C"),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The text of <paramref name="command"/>, Polish for "pl", else English; its name when unknown.</summary>
|
||||||
|
public static string Of(string command, string languageCode) =>
|
||||||
|
Texts.TryGetValue(command, out var text) ? languageCode == "pl" ? text.Polish : text.English : command;
|
||||||
|
|
||||||
|
/// <summary>The commands there are texts for.</summary>
|
||||||
|
public static IEnumerable<string> Commands => Texts.Keys;
|
||||||
|
}
|
||||||
@@ -155,7 +155,9 @@ public sealed class EventList : ListBox
|
|||||||
var culture = CultureInfo.CurrentCulture;
|
var culture = CultureInfo.CurrentCulture;
|
||||||
var events = new List<BlackBoxEvent>();
|
var events = new List<BlackBoxEvent>();
|
||||||
foreach (var c in recording.UserCommands())
|
foreach (var c in recording.UserCommands())
|
||||||
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], c.Name), Palette.Command, false));
|
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"],
|
||||||
|
strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]),
|
||||||
|
Palette.Command, false));
|
||||||
foreach (var d in recording.DriverChanges)
|
foreach (var d in recording.DriverChanges)
|
||||||
{
|
{
|
||||||
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
|
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
|
||||||
@@ -176,14 +178,7 @@ public sealed class EventList : ListBox
|
|||||||
foreach (var horn in recording.UserHornChecks())
|
foreach (var horn in recording.UserHornChecks())
|
||||||
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
|
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
|
||||||
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
|
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
|
||||||
foreach (var span in recording.SecurityBrakings())
|
AddSecurity(recording, strings, events, culture);
|
||||||
{
|
|
||||||
// Which of them was not acknowledged: the lamps blinking when it braked.
|
|
||||||
string who = recording.CabAt(span.Start) is { } s
|
|
||||||
? s.Has(SecurityFlags.CabSignal) && s.Has(SecurityFlags.Vigilance) ? "CA/SHP" : s.Has(SecurityFlags.CabSignal) ? "SHP" : "CA"
|
|
||||||
: "CA";
|
|
||||||
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"], who), Palette.Bad, true));
|
|
||||||
}
|
|
||||||
AddCameras(recording, strings, events, culture);
|
AddCameras(recording, strings, events, culture);
|
||||||
AddCouplings(recording, strings, events, culture);
|
AddCouplings(recording, strings, events, culture);
|
||||||
AddCabChanges(recording, strings, events, culture);
|
AddCabChanges(recording, strings, events, culture);
|
||||||
@@ -196,6 +191,45 @@ public sealed class EventList : ListBox
|
|||||||
return events.OrderBy(e => e.Time).ToList();
|
return events.OrderBy(e => e.Time).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The train protection: its buzzer, acknowledged or not, and the braking apart. A lamp acknowledged before the
|
||||||
|
/// buzzer is the driving as usual, not told.
|
||||||
|
/// </summary>
|
||||||
|
private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
||||||
|
{
|
||||||
|
var brakings = recording.SecurityBrakings();
|
||||||
|
foreach (var span in recording.SecurityAlarms())
|
||||||
|
{
|
||||||
|
// The lamps of all its buzzing samples: one buzzer for both, the other may join it before it's acknowledged.
|
||||||
|
var lamps = recording.Cab.Where(c => c.Time >= span.Start && c.Time <= span.End && (c.VigilanceBuzzer || c.CabSignalBuzzer))
|
||||||
|
.Aggregate(SecurityFlags.None, (all, c) => all | c.Security);
|
||||||
|
string who = ProtectionName(lamps);
|
||||||
|
var before = recording.CabAt(span.Start);
|
||||||
|
string text = brakings.Any(b => b.Start >= span.Start && b.Start <= span.End)
|
||||||
|
? string.Format(culture, strings["EventSecurityAlarmMissed"], who)
|
||||||
|
// Acknowledged when the sample it ended at buzzes no more and doesn't brake, in the same vehicle: not
|
||||||
|
// the end of the recording or a gap in it, nor the power cut or the protection switched off.
|
||||||
|
: recording.CabAt(span.End) is { } after && !after.VigilanceBuzzer && !after.CabSignalBuzzer
|
||||||
|
&& !after.Has(SecurityFlags.Braking) && after.Vehicle == before?.Vehicle
|
||||||
|
? string.Format(culture, strings["EventSecurityAlarmAcknowledged"], who, span.End - span.Start)
|
||||||
|
: string.Format(culture, strings["EventSecurityAlarm"], who);
|
||||||
|
events.Add(new BlackBoxEvent(span.Start, text, Palette.Buzzer, false));
|
||||||
|
}
|
||||||
|
foreach (var span in brakings)
|
||||||
|
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"],
|
||||||
|
ProtectionName(recording.CabAt(span.Start)?.Security ?? SecurityFlags.None)),
|
||||||
|
Palette.Bad, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Which of them it was: the lamps blinking.</summary>
|
||||||
|
private static string ProtectionName(SecurityFlags lamps) =>
|
||||||
|
(lamps & (SecurityFlags.CabSignal | SecurityFlags.Vigilance)) switch
|
||||||
|
{
|
||||||
|
SecurityFlags.CabSignal | SecurityFlags.Vigilance => "CA/SHP",
|
||||||
|
SecurityFlags.CabSignal => "SHP",
|
||||||
|
_ => "CA"
|
||||||
|
};
|
||||||
|
|
||||||
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
||||||
{
|
{
|
||||||
UserVehicleChange? before = null;
|
UserVehicleChange? before = null;
|
||||||
@@ -282,6 +316,8 @@ public sealed class EventList : ListBox
|
|||||||
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
||||||
];
|
];
|
||||||
|
|
||||||
|
private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the
|
/// 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
|
/// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the
|
||||||
@@ -291,7 +327,8 @@ public sealed class EventList : ListBox
|
|||||||
{
|
{
|
||||||
CabSample? last = null;
|
CabSample? last = null;
|
||||||
bool movingOpen = false;
|
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)
|
if (last is not { } b || b.Vehicle != s.Vehicle)
|
||||||
{
|
{
|
||||||
@@ -299,8 +336,10 @@ public sealed class EventList : ListBox
|
|||||||
movingOpen = false;
|
movingOpen = false;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
bool Came(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 Went(CabDevices device) => b.Has(device) && !s.Has(device);
|
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)
|
foreach (var (device, key) in Switched)
|
||||||
{
|
{
|
||||||
if (Came(device))
|
if (Came(device))
|
||||||
|
|||||||
@@ -25,8 +25,12 @@ public sealed class MapView : Control
|
|||||||
private Recording? _recording;
|
private Recording? _recording;
|
||||||
private int _builtRevision = -1;
|
private int _builtRevision = -1;
|
||||||
private int _builtTracks = -1;
|
private int _builtTracks = -1;
|
||||||
private StreamGeometry? _tracks;
|
private TrackLayer? _tracks;
|
||||||
private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new();
|
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 readonly StreamGeometry?[] _trail = new StreamGeometry?[5];
|
||||||
private Rect _world;
|
private Rect _world;
|
||||||
|
|
||||||
@@ -135,33 +139,24 @@ public sealed class MapView : Control
|
|||||||
{
|
{
|
||||||
_builtTracks = recording.Tracks.Count;
|
_builtTracks = recording.Tracks.Count;
|
||||||
_switchWays.Clear();
|
_switchWays.Clear();
|
||||||
var tracks = new StreamGeometry();
|
|
||||||
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
|
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
|
||||||
using (var g = tracks.Open())
|
foreach (var track in recording.Tracks)
|
||||||
{
|
{
|
||||||
foreach (var track in recording.Tracks)
|
if (track.Points.Count < 2)
|
||||||
|
continue;
|
||||||
|
foreach (var p in track.Points)
|
||||||
{
|
{
|
||||||
if (track.Points.Count < 2)
|
left = Math.Min(left, -p.X);
|
||||||
continue;
|
right = Math.Max(right, -p.X);
|
||||||
foreach (var p in track.Points)
|
top = Math.Min(top, -p.Z);
|
||||||
{
|
bottom = Math.Max(bottom, -p.Z);
|
||||||
left = Math.Min(left, -p.X);
|
|
||||||
right = Math.Max(right, -p.X);
|
|
||||||
top = Math.Min(top, -p.Z);
|
|
||||||
bottom = Math.Max(bottom, -p.Z);
|
|
||||||
}
|
|
||||||
if (track.Kind == TrackKind.SwitchBranch)
|
|
||||||
{
|
|
||||||
var way = new StreamGeometry();
|
|
||||||
using (var w = way.Open())
|
|
||||||
Polyline(w, track.Points);
|
|
||||||
_switchWays.Add((track.Index, track.Branch, way));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
Polyline(g, track.Points);
|
|
||||||
}
|
}
|
||||||
|
if (track.Kind == TrackKind.SwitchBranch)
|
||||||
|
_switchWays.Add((track.Index, track.Branch, track.Points));
|
||||||
}
|
}
|
||||||
_tracks = tracks;
|
_tracks = new TrackLayer(recording.Tracks);
|
||||||
|
_switchStates = Array.Empty<int>();
|
||||||
|
_waysOff = _waysOn = null;
|
||||||
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
|
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
|
||||||
}
|
}
|
||||||
BuildTrail(recording);
|
BuildTrail(recording);
|
||||||
@@ -247,29 +242,26 @@ public sealed class MapView : Control
|
|||||||
double pixel = 1 / _scale;
|
double pixel = 1 / _scale;
|
||||||
using (context.PushTransform(toScreen))
|
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);
|
var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round);
|
||||||
if (_tracks is not null)
|
var fill = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
|
||||||
context.DrawGeometry(null, casing, _tracks);
|
if (_tracks is { } layer)
|
||||||
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)
|
|
||||||
{
|
{
|
||||||
int state = recording.SwitchAt(index, _time);
|
var view = PlaneInView(size, 6 * pixel);
|
||||||
if (state >= 0 && state != branch)
|
int level = TrackLayer.LevelFor(_scale);
|
||||||
context.DrawGeometry(null, off, way);
|
foreach (var cell in layer.CellsIn(view, level))
|
||||||
}
|
context.DrawGeometry(null, casing, cell.Casing);
|
||||||
foreach (var (index, branch, way) in _switchWays)
|
foreach (var cell in layer.CellsIn(view, level))
|
||||||
{
|
if (cell.Fill is { } tracks)
|
||||||
int state = recording.SwitchAt(index, _time);
|
context.DrawGeometry(null, fill, tracks);
|
||||||
if (state < 0 || state == branch)
|
|
||||||
context.DrawGeometry(null, on, way);
|
|
||||||
}
|
}
|
||||||
|
// 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.
|
// The way the train went, in the colour of the judgement.
|
||||||
for (int kind = 0; kind < _trail.Length; kind++)
|
for (int kind = 0; kind < _trail.Length; kind++)
|
||||||
if (_trail[kind] is { } trail)
|
if (_trail[kind] is { } trail)
|
||||||
@@ -280,12 +272,67 @@ public sealed class MapView : Control
|
|||||||
DrawHornPoints(context, recording);
|
DrawHornPoints(context, recording);
|
||||||
DrawSignals(context, recording);
|
DrawSignals(context, recording);
|
||||||
DrawPassings(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);
|
DrawUserTrain(context, recording);
|
||||||
DrawCamera(context, recording);
|
DrawCamera(context, recording);
|
||||||
DrawScale(context, size);
|
DrawScale(context, size);
|
||||||
DrawLegend(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) =>
|
private bool Visible(Point p, double margin = 20) =>
|
||||||
@@ -468,10 +515,10 @@ public sealed class MapView : Control
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
int user = recording.CabAt(_time) is { } sample && _time - sample.Time < 1.5 ? sample.Vehicle : 0;
|
||||||
foreach (var state in recording.VehiclesAt(_time))
|
foreach (var state in vehicles)
|
||||||
{
|
{
|
||||||
var info = recording.Vehicle(state.Id);
|
var info = recording.Vehicle(state.Id);
|
||||||
var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle;
|
var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle;
|
||||||
@@ -602,10 +649,19 @@ public sealed class MapView : Control
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The name of the signal or the vehicle under the pointer.</summary>
|
/// <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;
|
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;
|
string? label = null;
|
||||||
double best = 10;
|
double best = 10;
|
||||||
foreach (var signal in recording.Signals)
|
foreach (var signal in recording.Signals)
|
||||||
@@ -646,7 +702,7 @@ public sealed class MapView : Control
|
|||||||
label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration);
|
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);
|
double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer);
|
||||||
if (d < best && recording.Vehicle(state.Id) is { } info)
|
if (d < best && recording.Vehicle(state.Id) is { } info)
|
||||||
@@ -657,12 +713,7 @@ public sealed class MapView : Control
|
|||||||
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
|
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (label is null)
|
return label;
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
|
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
|
||||||
@@ -724,8 +775,13 @@ public sealed class MapView : Control
|
|||||||
_centerX = _dragCenter.X + moved.X / _scale;
|
_centerX = _dragCenter.X + moved.X / _scale;
|
||||||
_centerZ = _dragCenter.Z + moved.Y / _scale;
|
_centerZ = _dragCenter.Z + moved.Y / _scale;
|
||||||
}
|
}
|
||||||
|
InvalidateVisual();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
InvalidateVisual();
|
// Not dragged, the map is the same: drawn again only for a label to show, follow the pointer or go.
|
||||||
|
if (_hoverShown is not null ||
|
||||||
|
(_recording is { } recording && HoverLabel(recording, position, recording.VehiclesAt(_time)) is not null))
|
||||||
|
InvalidateVisual();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnPointerReleased(PointerReleasedEventArgs e)
|
protected override void OnPointerReleased(PointerReleasedEventArgs e)
|
||||||
|
|||||||
@@ -81,6 +81,8 @@ public static class Palette
|
|||||||
public static readonly IBrush LampOn = Brush("#4cc46e");
|
public static readonly IBrush LampOn = Brush("#4cc46e");
|
||||||
public static readonly IBrush LampWarning = Brush("#e8c547");
|
public static readonly IBrush LampWarning = Brush("#e8c547");
|
||||||
public static readonly IBrush LampAlarm = Brush("#f0584a");
|
public static readonly IBrush LampAlarm = Brush("#f0584a");
|
||||||
|
/// <summary>The train protection's buzzer: still to be acknowledged, not braking yet.</summary>
|
||||||
|
public static readonly IBrush Buzzer = Brush("#c77dff");
|
||||||
public static readonly IBrush LightWhite = Brush("#fff6d8");
|
public static readonly IBrush LightWhite = Brush("#fff6d8");
|
||||||
public static readonly IBrush LightRed = Brush("#ff3b30");
|
public static readonly IBrush LightRed = Brush("#ff3b30");
|
||||||
public static readonly IBrush Command = Brush("#8b96a3");
|
public static readonly IBrush Command = Brush("#8b96a3");
|
||||||
|
|||||||
@@ -309,16 +309,16 @@ public sealed class TimelineView : Control
|
|||||||
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
|
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
|
||||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||||
{
|
{
|
||||||
// The alerter and the cab signalling apart, red when not acknowledged in time.
|
// The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked.
|
||||||
rows[3].Add(x0, x1, s.Has(SecurityFlags.VigilanceBeeping) ? Palette.LampAlarm
|
rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer
|
||||||
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
|
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
|
||||||
rows[4].Add(x0, x1, s.Has(SecurityFlags.CabSignalBeeping) ? Palette.LampAlarm
|
rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer
|
||||||
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
|
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
|
||||||
if (s.Has(SecurityFlags.Braking))
|
if (s.ProtectionBraking)
|
||||||
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
|
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
||||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
|
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
|
||||||
// Where the user looked from: the samples go on in time, and so does the camera.
|
// Where the user looked from: the samples go on in time, and so does the camera.
|
||||||
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
|
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
|
||||||
@@ -590,7 +590,8 @@ public sealed class TimelineView : Control
|
|||||||
foreach (var d in recording.DriverChanges)
|
foreach (var d in recording.DriverChanges)
|
||||||
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
|
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
|
||||||
foreach (var c in recording.UserCommands())
|
foreach (var c in recording.UserCommands())
|
||||||
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], c.Name));
|
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"],
|
||||||
|
Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]));
|
||||||
}
|
}
|
||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|||||||
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(),
|
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())
|
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);
|
rec.AddCab(sample);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -520,7 +520,13 @@ public sealed class Recording
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
|
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
|
||||||
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.Has(SecurityFlags.Braking));
|
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.ProtectionBraking);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When the train protection's buzzer sounded in the user's cab: a lamp not acknowledged in time, the braking to
|
||||||
|
/// follow unless acknowledged on. Until it ends, braking included.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<TimeSpanRange> SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer);
|
||||||
|
|
||||||
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
|
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
|
||||||
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
|
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
|
||||||
|
|||||||
@@ -366,11 +366,50 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit
|
|||||||
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
||||||
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
||||||
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
|
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(CabDevices device) => (Devices & device) == device;
|
||||||
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The alerter's buzzer: its lamp not acknowledged in time. A protection with one acknowledgement for both tells
|
||||||
|
/// the cab signalling's buzzer as the alerter's too, so the alerter's lamp has to blink with it.
|
||||||
|
/// </summary>
|
||||||
|
public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance);
|
||||||
|
|
||||||
|
/// <summary>The cab signalling's buzzer: its lamp not acknowledged in time.</summary>
|
||||||
|
public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The train protection braking for an alarm not acknowledged, its lamp blinking. Braking with no lamp is the
|
||||||
|
/// protection with no power (TSecuritySystem::is_braking), a cab not started or a power cut: no driver's fault.
|
||||||
|
/// </summary>
|
||||||
|
public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal));
|
||||||
|
|
||||||
|
private const CabDevices LeftDoors = CabDevices.DoorsLeft | CabDevices.DoorPermitLeft;
|
||||||
|
private const CabDevices RightDoors = CabDevices.DoorsRight | CabDevices.DoorPermitRight;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The doors as the driver has them: the recording holds the left and right of the vehicle, and from its rear
|
||||||
|
/// cab the driver's left is the vehicle's right, as the simulator works the doors from it. Out of a cab, the
|
||||||
|
/// vehicle's.
|
||||||
|
/// </summary>
|
||||||
|
public CabSample AsTheCabSees =>
|
||||||
|
CabEnd >= 0
|
||||||
|
? this
|
||||||
|
: this with
|
||||||
|
{
|
||||||
|
Devices = (Devices & ~(LeftDoors | RightDoors))
|
||||||
|
| ((Devices & CabDevices.DoorsLeft) != 0 ? CabDevices.DoorsRight : 0)
|
||||||
|
| ((Devices & CabDevices.DoorsRight) != 0 ? CabDevices.DoorsLeft : 0)
|
||||||
|
| ((Devices & CabDevices.DoorPermitLeft) != 0 ? CabDevices.DoorPermitRight : 0)
|
||||||
|
| ((Devices & CabDevices.DoorPermitRight) != 0 ? CabDevices.DoorPermitLeft : 0)
|
||||||
|
};
|
||||||
|
|
||||||
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
|
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
|
||||||
public bool InCab => (Flags & CabFlags.InCab) != 0;
|
public bool InCab => (Flags & CabFlags.InCab) != 0;
|
||||||
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
|
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ internal sealed class BlackBoxFile
|
|||||||
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
|
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,
|
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,
|
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 =>
|
Record(0x20, w =>
|
||||||
{
|
{
|
||||||
w.Write(time);
|
w.Write(time);
|
||||||
@@ -181,6 +181,9 @@ internal sealed class BlackBoxFile
|
|||||||
w.Write(1.0f); // clutch
|
w.Write(1.0f); // clutch
|
||||||
w.Write(0.0f); // torque converter
|
w.Write(0.0f); // torque converter
|
||||||
w.Write(2.5f); // the highest brake cylinder of the train
|
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()
|
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);
|
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()
|
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||||
.WithFile(Log("a.dat"), "t")
|
.WithFile(Log("a.dat"), "t")
|
||||||
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
|
.WithFile(Log(first), "b")
|
||||||
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
|
.WithFile(Log(second), "b")
|
||||||
.WrittenAt(Log("a.dat"), early)
|
.WrittenAt(Log("a.dat"), early)
|
||||||
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
|
.WrittenAt(Log(first), early.AddSeconds(2))
|
||||||
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
|
.WrittenAt(Log(second), early.AddHours(1)));
|
||||||
|
|
||||||
var sessions = installation.Tapes.Sessions();
|
var sessions = installation.Tapes.Sessions();
|
||||||
|
|
||||||
@@ -74,12 +76,59 @@ public class BlackBoxListingTests
|
|||||||
Assert.All(sessions, session => Assert.Null(session.Launch));
|
Assert.All(sessions, session => Assert.Null(session.Launch));
|
||||||
// Newest first: the black box on its own, then the run with the tape.
|
// Newest first: the black box on its own, then the run with the tape.
|
||||||
Assert.Empty(sessions[0].Tapes);
|
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.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);
|
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]
|
[Fact]
|
||||||
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
|
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);
|
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]
|
[Fact]
|
||||||
public void A_vehicle_with_no_lamps_is_not_judged()
|
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());
|
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]
|
[Fact]
|
||||||
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
44
StarterNG.Tests/BlackBox/EventTextsTests.cs
Normal file
44
StarterNG.Tests/BlackBox/EventTextsTests.cs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
using Eu07.BlackBox;
|
||||||
|
using Eu07.BlackBox.Views;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests.BlackBox;
|
||||||
|
|
||||||
|
[Collection(AvaloniaControls.Name)]
|
||||||
|
public class EventTextsTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("pl", "aidriverenable", "Aktywacja automechanika")]
|
||||||
|
[InlineData("en", "aidriverenable", "Engage the AI driver")]
|
||||||
|
[InlineData("pl", "mastercontrollerset", "Ustawienie nastawnika głównego")]
|
||||||
|
[InlineData("pl", "headlightenablerearleft", "Włączenie lewego reflektora z tyłu")]
|
||||||
|
[InlineData("cz", "batteryenable", "Turn the battery on")]
|
||||||
|
public void A_command_is_told_by_what_it_does(string language, string command, string text) =>
|
||||||
|
Assert.Equal(text, new DefaultBlackBoxStrings(language)[DefaultBlackBoxStrings.CommandPrefix + command]);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_command_with_no_text_keeps_its_name() =>
|
||||||
|
Assert.Equal("somethingnew", new DefaultBlackBoxStrings("pl")[DefaultBlackBoxStrings.CommandPrefix + "somethingnew"]);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Every_command_has_both_texts_starting_with_a_capital()
|
||||||
|
{
|
||||||
|
foreach (string command in CommandTexts.Commands)
|
||||||
|
foreach (string language in new[] { "pl", "en" })
|
||||||
|
{
|
||||||
|
string text = CommandTexts.Of(command, language);
|
||||||
|
Assert.NotEqual(command, text);
|
||||||
|
Assert.True(char.IsUpper(text[0]), $"{command} ({language}): {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_events_name_the_commands_by_what_they_do()
|
||||||
|
{
|
||||||
|
var recording = BlackBoxReader.Read(new BlackBoxFile().Info()
|
||||||
|
.Vehicle(1, "EP07-424").User(0, 1, true).Command(12.0, 1, true, "batteryenable").Stream());
|
||||||
|
|
||||||
|
var events = EventList.Collect(recording, new DefaultBlackBoxStrings("pl"));
|
||||||
|
|
||||||
|
Assert.Contains(events, e => e.Text == "Włączenie baterii");
|
||||||
|
}
|
||||||
|
}
|
||||||
89
StarterNG.Tests/BlackBox/SecurityBrakingTests.cs
Normal file
89
StarterNG.Tests/BlackBox/SecurityBrakingTests.cs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Eu07.BlackBox;
|
||||||
|
using Eu07.BlackBox.Views;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests.BlackBox;
|
||||||
|
|
||||||
|
[Collection(AvaloniaControls.Name)]
|
||||||
|
public class SecurityBrakingTests
|
||||||
|
{
|
||||||
|
// as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too
|
||||||
|
private const byte CabSignal = 0x02, CabSignalBuzzing = 0x0e, CabSignalBraking = 0x1e, NoPower = 0x10;
|
||||||
|
|
||||||
|
private static Recording Drive(System.Func<double, byte> security)
|
||||||
|
{
|
||||||
|
var file = new BlackBoxFile().Info().Vehicle(1, "EP07-424").User(0, 1, true);
|
||||||
|
for (double t = 0; t <= 20; t += 0.5)
|
||||||
|
file.Cab(t, 1, 100, 0, security: security(t));
|
||||||
|
return BlackBoxReader.Read(file.Stream());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> Events(Recording recording)
|
||||||
|
{
|
||||||
|
var culture = CultureInfo.CurrentCulture;
|
||||||
|
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return EventList.Collect(recording, new DefaultBlackBoxStrings("pl")).Select(e => e.Text).ToList();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CultureInfo.CurrentCulture = culture;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_protection_braking_with_no_power_is_not_the_drivers_fault()
|
||||||
|
{
|
||||||
|
// no power for the first seconds, then the cab signalling not acknowledged
|
||||||
|
var recording = Drive(t => t < 5 ? NoPower : t is >= 10 and < 12 ? (byte)0x1a : (byte)0);
|
||||||
|
|
||||||
|
var braking = Assert.Single(recording.SecurityBrakings());
|
||||||
|
Assert.Equal(10, braking.Start, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_buzzer_acknowledged_in_time_is_told_apart_from_braking()
|
||||||
|
{
|
||||||
|
var recording = Drive(t => t is >= 2 and < 4 ? CabSignal : t is >= 4 and < 5.5 ? CabSignalBuzzing : (byte)0);
|
||||||
|
|
||||||
|
var events = Events(recording);
|
||||||
|
|
||||||
|
Assert.Contains("Brzęczyk SHP, potwierdzony po 1.5 s", events);
|
||||||
|
Assert.DoesNotContain(events, e => e.StartsWith("HAMOWANIE", System.StringComparison.Ordinal));
|
||||||
|
Assert.Empty(recording.SecurityBrakings());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_buzzer_cut_by_the_power_is_not_acknowledged()
|
||||||
|
{
|
||||||
|
var recording = Drive(t => t is >= 2 and < 4 ? CabSignalBuzzing : t is >= 4 and < 8 ? NoPower : (byte)0);
|
||||||
|
|
||||||
|
var events = Events(recording);
|
||||||
|
|
||||||
|
Assert.Contains("Brzęczyk SHP", events);
|
||||||
|
Assert.DoesNotContain(events, e => e.Contains("potwierdzony", System.StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_buzzer_the_other_joins_is_named_by_both()
|
||||||
|
{
|
||||||
|
// the alerter's buzzer, then a magnet passed before it's acknowledged
|
||||||
|
var recording = Drive(t => t is >= 2 and < 4 ? (byte)0x05 : t is >= 4 and < 5 ? (byte)0x0f : (byte)0);
|
||||||
|
|
||||||
|
Assert.Contains("Brzęczyk CA/SHP, potwierdzony po 3.0 s", Events(recording));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_buzzer_not_acknowledged_is_followed_by_the_braking()
|
||||||
|
{
|
||||||
|
// the cab signalling at the start: the buzzer at once, braking when not acknowledged
|
||||||
|
var recording = Drive(t => t < 3 ? CabSignalBuzzing : t < 6 ? CabSignalBraking : (byte)0);
|
||||||
|
|
||||||
|
var events = Events(recording);
|
||||||
|
|
||||||
|
Assert.Equal(["Brzęczyk SHP, bez potwierdzenia", "HAMOWANIE PRZEZ SHP"],
|
||||||
|
events.Where(e => e.Contains("SHP", System.StringComparison.Ordinal)));
|
||||||
|
Assert.DoesNotContain(events, e => e.Contains("CA", System.StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
}
|
||||||
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
119
StarterNG.Tests/CaseInsensitivePathsTests.cs
Normal file
119
StarterNG.Tests/CaseInsensitivePathsTests.cs
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
using StarterNG.Infrastructure;
|
||||||
|
using StarterNG.Tests.Fakes;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class CaseInsensitivePathsTests
|
||||||
|
{
|
||||||
|
private static InMemoryFileSystem Disk() => new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile("game/scenery/Braniewo/Base.ctr", "")
|
||||||
|
.WithFile("game/scenery/Braniewo/rozklady/TGS3657.txt", "")
|
||||||
|
.WithDirectory("game/textures/mini");
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("braniewo/base.ctr", "Braniewo/Base.ctr")]
|
||||||
|
[InlineData(@"BRANIEWO\Rozklady\tgs3657.TXT", "Braniewo/rozklady/TGS3657.txt")]
|
||||||
|
[InlineData("Braniewo/Base.ctr", "Braniewo/Base.ctr")]
|
||||||
|
[InlineData("braniewo//base.ctr", "Braniewo/Base.ctr")]
|
||||||
|
[InlineData("/braniewo/base.ctr", "Braniewo/Base.ctr")]
|
||||||
|
[InlineData(@"\Braniewo\Base.ctr", "Braniewo/Base.ctr")]
|
||||||
|
public void A_name_in_any_case_is_given_as_it_is_on_disk(string name, string onDisk) =>
|
||||||
|
Assert.Equal(onDisk, new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("braniewo/brak.ctr")]
|
||||||
|
[InlineData("brak/base.ctr")]
|
||||||
|
[InlineData("")]
|
||||||
|
public void A_name_nothing_answers_to_is_not_found(string name) =>
|
||||||
|
Assert.Null(new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_folder_is_found_only_when_one_is_asked_for()
|
||||||
|
{
|
||||||
|
var names = new CaseInsensitivePaths(Disk());
|
||||||
|
|
||||||
|
Assert.Equal("Braniewo/rozklady", names.Resolve("game/scenery", "braniewo/ROZKLADY", directory: true));
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/ROZKLADY"));
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/base.ctr", directory: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_name_written_as_on_disk_wins_over_one_in_other_case()
|
||||||
|
{
|
||||||
|
var files = Disk().WithFile("game/scenery/braniewo/base.ctr", "");
|
||||||
|
var names = new CaseInsensitivePaths(files);
|
||||||
|
|
||||||
|
Assert.Equal("braniewo/base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
|
||||||
|
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "Braniewo/base.CTR"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Of_folders_named_alike_the_one_holding_the_file_is_taken()
|
||||||
|
{
|
||||||
|
var files = Disk().WithFile("game/scenery/braniewo/tory.scm", "");
|
||||||
|
var names = new CaseInsensitivePaths(files);
|
||||||
|
|
||||||
|
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
|
||||||
|
Assert.Equal("braniewo/tory.scm", names.Resolve("game/scenery", "Braniewo/Tory.scm"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_full_path_joins_the_folder_and_the_name_on_disk() =>
|
||||||
|
Assert.Equal(Path.Combine("game/scenery", "Braniewo", "Base.ctr"),
|
||||||
|
new CaseInsensitivePaths(Disk()).Find("game/scenery", "BRANIEWO/BASE.CTR"));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_full_path_is_found_from_its_own_root()
|
||||||
|
{
|
||||||
|
string scenery = Path.GetFullPath(Path.Combine("game", "scenery"));
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(Path.Combine(scenery, "Braniewo", "Base.ctr"), "");
|
||||||
|
|
||||||
|
Assert.Equal(Path.Combine(scenery, "Braniewo", "Base.ctr"),
|
||||||
|
new CaseInsensitivePaths(files).Find("elsewhere", Path.Combine(scenery, "BRANIEWO", "base.CTR")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_disk_that_ignores_case_gives_the_name_back_as_written()
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem().WithFile("game/scenery/Braniewo/Base.ctr", "");
|
||||||
|
var names = new CaseInsensitivePaths(files);
|
||||||
|
|
||||||
|
Assert.Equal("BRANIEWO/base.CTR", names.Resolve("game/scenery", "BRANIEWO/base.CTR"));
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/brak.ctr"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Kept_listings_hold_until_forgotten()
|
||||||
|
{
|
||||||
|
var files = Disk();
|
||||||
|
var names = new CaseInsensitivePaths(files, keepListings: true);
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
|
||||||
|
|
||||||
|
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
|
||||||
|
|
||||||
|
names.Forget();
|
||||||
|
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Listings_not_kept_see_a_file_added_since()
|
||||||
|
{
|
||||||
|
var files = Disk();
|
||||||
|
var names = new CaseInsensitivePaths(files);
|
||||||
|
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
|
||||||
|
|
||||||
|
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
|
||||||
|
|
||||||
|
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_folder_that_cannot_be_listed_holds_nothing_to_find()
|
||||||
|
{
|
||||||
|
var files = Disk().DenyListing("game/scenery");
|
||||||
|
|
||||||
|
Assert.Null(new CaseInsensitivePaths(files).Resolve("game/scenery", "braniewo/base.ctr"));
|
||||||
|
}
|
||||||
|
}
|
||||||
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;
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
// Puts in services of its own: not while the controls read theirs.
|
||||||
|
[Collection(AvaloniaControls.Name)]
|
||||||
public class ConsistOrientationTests
|
public class ConsistOrientationTests
|
||||||
{
|
{
|
||||||
private readonly VehicleCatalog _catalog;
|
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
53
StarterNG.Tests/ExecutableListTests.cs
Normal file
53
StarterNG.Tests/ExecutableListTests.cs
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
using StarterNG.Views;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class ExecutableListTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void A_build_copied_in_joins_the_list_and_the_choice_stays()
|
||||||
|
{
|
||||||
|
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], "eu07.exe");
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
|
||||||
|
Assert.Equal(1, chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Automatic_stays_automatic()
|
||||||
|
{
|
||||||
|
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], null);
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
|
||||||
|
Assert.Equal(-1, chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_simulator_picked_from_elsewhere_stays_on_the_list_and_chosen()
|
||||||
|
{
|
||||||
|
const string picked = @"D:\build\eu07.exe";
|
||||||
|
|
||||||
|
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], picked);
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "eu07.exe", picked }, entries);
|
||||||
|
Assert.Equal(1, chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_chosen_file_since_removed_stays_chosen_rather_than_switch_silently()
|
||||||
|
{
|
||||||
|
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], "eu07_old.exe");
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "eu07.exe", "eu07_old.exe" }, entries);
|
||||||
|
Assert.Equal(1, chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_choice_is_found_whatever_the_case_of_its_name()
|
||||||
|
{
|
||||||
|
var (entries, chosen) = ExecutableList.Refreshed(["EU07.exe"], "eu07.exe");
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "EU07.exe" }, entries);
|
||||||
|
Assert.Equal(0, chosen);
|
||||||
|
}
|
||||||
|
}
|
||||||
82
StarterNG.Tests/ExecutableNoAvx2Tests.cs
Normal file
82
StarterNG.Tests/ExecutableNoAvx2Tests.cs
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
using StarterNG.Domain.Settings;
|
||||||
|
using StarterNG.Infrastructure.Settings;
|
||||||
|
using StarterNG.Tests.Fakes;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class ExecutableNoAvx2Tests
|
||||||
|
{
|
||||||
|
private const string Elf = "\u007fELF binary";
|
||||||
|
private static readonly DateTime Older = new(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||||
|
private static readonly DateTime Newer = new(2026, 11, 15, 0, 0, 0, DateTimeKind.Utc);
|
||||||
|
|
||||||
|
private static InMemoryFileSystem With(params string[] names)
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem();
|
||||||
|
foreach (string name in names)
|
||||||
|
files.WithExecutable(TestInstallation.At(name), Elf);
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Automatic(InMemoryFileSystem files, bool lacksAvx2) =>
|
||||||
|
Path.GetFileName(new TestInstallation(files, lacksAvx2: lacksAvx2).Executables
|
||||||
|
.Resolve(new SimulatorSettings(), out _));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("eu07_noavx2", true)]
|
||||||
|
[InlineData("eu07-x64_2026-11-15_abc1234_noavx2.exe", true)]
|
||||||
|
[InlineData("EU07_NOAVX2.EXE", true)]
|
||||||
|
[InlineData("eu07", false)]
|
||||||
|
[InlineData("eu07-x64_2026-11-15_abc1234.exe", false)]
|
||||||
|
[InlineData("eu07_noavx2_old.exe", false)]
|
||||||
|
public void A_build_without_avx2_is_known_by_the_end_of_its_name(string name, bool noAvx2) =>
|
||||||
|
Assert.Equal(noAvx2, ExecutableLocator.IsNoAvx2(name));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_avx2_the_build_without_it_is_chosen_over_the_canonical_one() =>
|
||||||
|
Assert.Equal("eu07_noavx2", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: true));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void With_avx2_the_build_made_for_it_stays_first() =>
|
||||||
|
Assert.Equal("eu07", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: false));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void With_avx2_a_build_without_it_is_used_when_it_is_the_only_one() =>
|
||||||
|
Assert.Equal("eu07_noavx2", Automatic(With("eu07_noavx2"), lacksAvx2: false));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_avx2_the_newest_build_without_it_is_chosen()
|
||||||
|
{
|
||||||
|
var files = With("eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
|
||||||
|
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
|
||||||
|
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
|
||||||
|
|
||||||
|
Assert.Equal("eu07_2026-11-15_bbb_noavx2", Automatic(files, lacksAvx2: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_avx2_and_no_build_without_it_the_usual_choice_stands() =>
|
||||||
|
Assert.Equal("eu07", Automatic(With("eu07-dev", "eu07"), lacksAvx2: true));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Only_a_build_with_avx2_on_a_processor_without_it_will_not_run()
|
||||||
|
{
|
||||||
|
var lacking = new TestInstallation(lacksAvx2: true).Executables;
|
||||||
|
var able = new TestInstallation(lacksAvx2: false).Executables;
|
||||||
|
|
||||||
|
Assert.True(lacking.WillNotRunHere("eu07.exe"));
|
||||||
|
Assert.False(lacking.WillNotRunHere("eu07-x64_noavx2.exe"));
|
||||||
|
Assert.False(able.WillNotRunHere("eu07.exe"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_newest_build_without_avx2_is_offered_by_name()
|
||||||
|
{
|
||||||
|
var files = With("eu07", "eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
|
||||||
|
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
|
||||||
|
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
|
||||||
|
|
||||||
|
Assert.Equal("eu07_2026-11-15_bbb_noavx2", new TestInstallation(files).Executables.NewestNoAvx2());
|
||||||
|
Assert.Null(new TestInstallation(With("eu07")).Executables.NewestNoAvx2());
|
||||||
|
}
|
||||||
|
}
|
||||||
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 HashSet<string> _executable;
|
||||||
private readonly Dictionary<string, string> _links;
|
private readonly Dictionary<string, string> _links;
|
||||||
private readonly HashSet<string> _unreadable;
|
private readonly HashSet<string> _unreadable;
|
||||||
|
private readonly HashSet<string> _unseekable;
|
||||||
private readonly HashSet<string> _unlistable;
|
private readonly HashSet<string> _unlistable;
|
||||||
private readonly Dictionary<string, DateTime> _written;
|
private readonly Dictionary<string, DateTime> _written;
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
_executable = new HashSet<string>(comparer);
|
_executable = new HashSet<string>(comparer);
|
||||||
_links = new Dictionary<string, string>(comparer);
|
_links = new Dictionary<string, string>(comparer);
|
||||||
_unreadable = new HashSet<string>(comparer);
|
_unreadable = new HashSet<string>(comparer);
|
||||||
|
_unseekable = new HashSet<string>(comparer);
|
||||||
_unlistable = new HashSet<string>(comparer);
|
_unlistable = new HashSet<string>(comparer);
|
||||||
_written = new Dictionary<string, DateTime>(comparer);
|
_written = new Dictionary<string, DateTime>(comparer);
|
||||||
}
|
}
|
||||||
@@ -51,6 +53,13 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
return this;
|
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)
|
public InMemoryFileSystem AllowReading(string path)
|
||||||
{
|
{
|
||||||
_unreadable.Remove(Normalize(path));
|
_unreadable.Remove(Normalize(path));
|
||||||
@@ -97,6 +106,8 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool IgnoresCase => _comparison == StringComparison.OrdinalIgnoreCase;
|
||||||
|
|
||||||
public bool FileExists(string path) => _files.ContainsKey(Normalize(path));
|
public bool FileExists(string path) => _files.ContainsKey(Normalize(path));
|
||||||
|
|
||||||
/// <summary>A link counts as the directory it points at, as the disk has it.</summary>
|
/// <summary>A link counts as the directory it points at, as the disk has it.</summary>
|
||||||
@@ -113,7 +124,11 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
|
|
||||||
public byte[] ReadAllBytes(string path) => Bytes(path);
|
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);
|
public void WriteAllText(string path, string contents) => WithFile(path, contents);
|
||||||
|
|
||||||
@@ -273,6 +288,9 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
return;
|
return;
|
||||||
slash = key.LastIndexOf('/');
|
slash = key.LastIndexOf('/');
|
||||||
}
|
}
|
||||||
|
// An absolute Unix path's parent is the root, "/", which normalises to "".
|
||||||
|
if (slash == 0)
|
||||||
|
_directories.Add("");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Normalize(string path) =>
|
private static string Normalize(string path) =>
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public sealed class TestInstallation
|
|||||||
{
|
{
|
||||||
public const string Root = "game";
|
public const string Root = "game";
|
||||||
|
|
||||||
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
|
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
|
||||||
{
|
{
|
||||||
Files = files ?? new InMemoryFileSystem();
|
Files = files ?? new InMemoryFileSystem();
|
||||||
Paths = new GamePaths(Root);
|
Paths = new GamePaths(Root);
|
||||||
@@ -35,7 +35,8 @@ public sealed class TestInstallation
|
|||||||
SettingsPaths.VehicleCacheDirectory());
|
SettingsPaths.VehicleCacheDirectory());
|
||||||
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
|
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
|
||||||
|
|
||||||
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
|
// The processor of the machine running the tests is not the one tested.
|
||||||
|
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
|
||||||
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
|
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
|
||||||
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
|
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
|
||||||
}
|
}
|
||||||
|
|||||||
65
StarterNG.Tests/FolderChangesTests.cs
Normal file
65
StarterNG.Tests/FolderChangesTests.cs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
using StarterNG.Infrastructure.Adapters;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public sealed class FolderChangesTests : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
|
||||||
|
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-changes-" + Guid.NewGuid().ToString("N"));
|
||||||
|
|
||||||
|
public FolderChangesTests() => Directory.CreateDirectory(Path.Combine(_root, "sub"));
|
||||||
|
|
||||||
|
public void Dispose() => Directory.Delete(_root, recursive: true);
|
||||||
|
|
||||||
|
private static async Task<bool> Reported(FolderChanges changes, Action change)
|
||||||
|
{
|
||||||
|
var told = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
changes.Changed += () => told.TrySetResult();
|
||||||
|
change();
|
||||||
|
return await Task.WhenAny(told.Task, Task.Delay(Patience)) == told.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_file_written_below_the_folder_is_reported()
|
||||||
|
{
|
||||||
|
string file = Path.Combine(_root, "sub", "a.scm");
|
||||||
|
File.WriteAllText(file, "old");
|
||||||
|
using var changes = new FolderChanges(_root);
|
||||||
|
|
||||||
|
Assert.True(changes.Watching);
|
||||||
|
Assert.True(await Reported(changes, () => File.WriteAllText(file, "new text")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_save_through_a_renamed_temp_file_is_reported()
|
||||||
|
{
|
||||||
|
string file = Path.Combine(_root, "test.scn");
|
||||||
|
File.WriteAllText(file, "old");
|
||||||
|
using var changes = new FolderChanges(_root);
|
||||||
|
|
||||||
|
Assert.True(await Reported(changes, () =>
|
||||||
|
{
|
||||||
|
string temp = file + ".tmp";
|
||||||
|
File.WriteAllText(temp, "new");
|
||||||
|
File.Move(temp, file, overwrite: true);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_file_removed_is_reported()
|
||||||
|
{
|
||||||
|
string file = Path.Combine(_root, "gone.scn");
|
||||||
|
File.WriteAllText(file, "x");
|
||||||
|
using var changes = new FolderChanges(_root);
|
||||||
|
|
||||||
|
Assert.True(await Reported(changes, () => File.Delete(file)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_missing_folder_is_not_watched_and_does_not_throw()
|
||||||
|
{
|
||||||
|
using var changes = new FolderChanges(Path.Combine(_root, "nowhere"));
|
||||||
|
|
||||||
|
Assert.False(changes.Watching);
|
||||||
|
}
|
||||||
|
}
|
||||||
192
StarterNG.Tests/FolderLooksTests.cs
Normal file
192
StarterNG.Tests/FolderLooksTests.cs
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
[Collection(AvaloniaControls.Name)]
|
||||||
|
public sealed class FolderLooksTests : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
|
||||||
|
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-looks-" + Guid.NewGuid().ToString("N"));
|
||||||
|
private readonly ManualTime _time = new();
|
||||||
|
private readonly Window _window;
|
||||||
|
private int _looks;
|
||||||
|
|
||||||
|
public FolderLooksTests()
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(_root);
|
||||||
|
HeadlessDrawing.Ensure();
|
||||||
|
_window = new Window();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_window.Close();
|
||||||
|
Directory.Delete(_root, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private FolderLooks Opened(string folder)
|
||||||
|
{
|
||||||
|
var looks = new FolderLooks(_window, () => folder, () =>
|
||||||
|
{
|
||||||
|
_looks++;
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}, _time);
|
||||||
|
_window.Show();
|
||||||
|
Controls.Settle();
|
||||||
|
_looks = 0;
|
||||||
|
return looks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ManualTimer Quiet => _time.Timers.Single(t => t.Period == Timeout.InfiniteTimeSpan);
|
||||||
|
private ManualTimer Often => _time.Timers.Single(t => t.Period != Timeout.InfiniteTimeSpan);
|
||||||
|
|
||||||
|
// Waited for without leaving the thread: the window belongs to it.
|
||||||
|
private static void Until(Func<bool> condition) => Assert.True(SpinWait.SpinUntil(condition, Patience), "waited too long");
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Nothing_is_watched_before_the_window_opens()
|
||||||
|
{
|
||||||
|
_ = new FolderLooks(_window, () => _root, () => Task.CompletedTask, _time);
|
||||||
|
|
||||||
|
Assert.Empty(_time.Timers);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_watched_folder_is_looked_at_anyway_seldom()
|
||||||
|
{
|
||||||
|
var looks = Opened(_root);
|
||||||
|
|
||||||
|
Assert.True(looks.Watching);
|
||||||
|
Assert.Equal(FolderLooks.Watched, Often.Due);
|
||||||
|
Assert.Equal(FolderLooks.Watched, Often.Period);
|
||||||
|
Assert.Equal(Timeout.InfiniteTimeSpan, Quiet.Due);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_folder_the_system_reports_nothing_of_is_looked_at_often()
|
||||||
|
{
|
||||||
|
var looks = Opened(Path.Combine(_root, "nowhere"));
|
||||||
|
|
||||||
|
Assert.False(looks.Watching);
|
||||||
|
Assert.Equal(FolderLooks.Unwatched, Often.Period);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_tick_looks_on_the_ui_thread_once_it_gets_there()
|
||||||
|
{
|
||||||
|
Opened(_root);
|
||||||
|
|
||||||
|
Often.Fire();
|
||||||
|
Assert.Equal(0, _looks);
|
||||||
|
Controls.Settle();
|
||||||
|
|
||||||
|
Assert.Equal(1, _looks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_change_is_looked_at_once_the_reports_stop()
|
||||||
|
{
|
||||||
|
Opened(_root);
|
||||||
|
|
||||||
|
File.WriteAllText(Path.Combine(_root, "test.scn"), "new");
|
||||||
|
Until(() => Quiet.Due == FolderLooks.Quiet);
|
||||||
|
Controls.Settle();
|
||||||
|
Assert.Equal(0, _looks);
|
||||||
|
|
||||||
|
Quiet.Fire();
|
||||||
|
Controls.Settle();
|
||||||
|
|
||||||
|
Assert.Equal(1, _looks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Coming_back_to_the_window_looks()
|
||||||
|
{
|
||||||
|
Opened(_root);
|
||||||
|
|
||||||
|
_window.Activate();
|
||||||
|
Controls.Settle();
|
||||||
|
|
||||||
|
Assert.Equal(1, _looks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Asked_it_looks()
|
||||||
|
{
|
||||||
|
var looks = Opened(_root);
|
||||||
|
|
||||||
|
Assert.True(looks.LookAsync().IsCompletedSuccessfully);
|
||||||
|
|
||||||
|
Assert.Equal(1, _looks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Closed_it_stops_the_timers()
|
||||||
|
{
|
||||||
|
Opened(_root);
|
||||||
|
|
||||||
|
_window.Close();
|
||||||
|
|
||||||
|
Assert.Equal(2, _time.Timers.Count);
|
||||||
|
Assert.All(_time.Timers, t => Assert.True(t.Disposed));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ManualTime : TimeProvider
|
||||||
|
{
|
||||||
|
private readonly List<ManualTimer> _timers = new();
|
||||||
|
|
||||||
|
public IReadOnlyList<ManualTimer> Timers
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_timers)
|
||||||
|
return _timers.ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||||
|
{
|
||||||
|
var timer = new ManualTimer(() => callback(state), dueTime, period);
|
||||||
|
lock (_timers)
|
||||||
|
_timers.Add(timer);
|
||||||
|
return timer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ManualTimer : ITimer
|
||||||
|
{
|
||||||
|
private readonly Action _tick;
|
||||||
|
private long _dueTicks;
|
||||||
|
|
||||||
|
public ManualTimer(Action tick, TimeSpan due, TimeSpan period)
|
||||||
|
{
|
||||||
|
_tick = tick;
|
||||||
|
_dueTicks = due.Ticks;
|
||||||
|
Period = period;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TimeSpan Due => TimeSpan.FromTicks(Interlocked.Read(ref _dueTicks));
|
||||||
|
public TimeSpan Period { get; private set; }
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
|
||||||
|
public void Fire() => _tick();
|
||||||
|
|
||||||
|
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||||
|
{
|
||||||
|
if (Disposed)
|
||||||
|
throw new ObjectDisposedException(nameof(ManualTimer));
|
||||||
|
Interlocked.Exchange(ref _dueTicks, dueTime.Ticks);
|
||||||
|
Period = period;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => Disposed = true;
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,16 +26,13 @@ public class GraphicsPresetTests
|
|||||||
var store = new TestInstallation().SettingsStore;
|
var store = new TestInstallation().SettingsStore;
|
||||||
var low = Defaults().Copy();
|
var low = Defaults().Copy();
|
||||||
var top = 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.Minimal with { Extras = null }).ApplyTo(low);
|
||||||
(GraphicsPreset.Ultra with { Extras = null, Top = null }).ApplyTo(top);
|
(GraphicsPreset.Ultra with { Extras = null, Top = null }).ApplyTo(top);
|
||||||
|
|
||||||
var lowKeys = store.Render(low);
|
var lowKeys = store.Render(low);
|
||||||
var topKeys = store.Render(top);
|
var topKeys = store.Render(top);
|
||||||
var differing = lowKeys.Keys.Union(topKeys.Keys)
|
var differing = lowKeys.Keys.Union(topKeys.Keys)
|
||||||
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key))
|
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key));
|
||||||
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal));
|
|
||||||
|
|
||||||
Assert.Equal(GraphicsPreset.Keys.OrderBy(k => k), differing.OrderBy(k => k));
|
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.
|
// Sizes and filtering run out of steps above High.
|
||||||
Climbs(p => p.TextureSize, 1);
|
Climbs(p => p.TextureSize, 1);
|
||||||
Climbs(p => p.CabTextureSize, 1);
|
Climbs(p => p.CabTextureSize, 2);
|
||||||
Climbs(p => p.Anisotropy, 1);
|
Climbs(p => p.Anisotropy, 1);
|
||||||
|
|
||||||
// Four steps or three for six levels.
|
// Four steps or three for six levels.
|
||||||
@@ -65,28 +62,23 @@ public class GraphicsPresetTests
|
|||||||
Climbs(p => p.ReflectionsFidelity, 3);
|
Climbs(p => p.ReflectionsFidelity, 3);
|
||||||
Climbs(p => p.ShadowRank, 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.DynamicLights, 2);
|
||||||
Climbs(p => p.DrawRange, 1);
|
Climbs(p => p.DrawRangeFactor, 3);
|
||||||
Climbs(p => p.DrawRangeFactor, 2);
|
|
||||||
Climbs(p => p.CabShadowsRange, 1);
|
Climbs(p => p.CabShadowsRange, 1);
|
||||||
|
|
||||||
Climbs(p => p.ShadowMap, 1);
|
Climbs(p => p.ShadowMap, 2);
|
||||||
Climbs(p => p.ShadowRange, 0);
|
Climbs(p => p.ShadowRange, 1);
|
||||||
Climbs(p => p.ReflectionsRate, 0);
|
// The old starter's steps begin at once a second: the lower levels share it.
|
||||||
Climbs(p => p.DistanceFactor, 0);
|
Climbs(p => p.ReflectionsRate, 2);
|
||||||
Climbs(p => p.BufferScale, 0);
|
|
||||||
Climbs(p => p.SleeperDistance, 0);
|
|
||||||
Climbs(p => p.ReflectedInstances, 0);
|
|
||||||
Climbs(p => p.ReflectedVehicles, 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void No_step_up_a_scale_is_more_than_a_few_steps_of_its_slider()
|
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.
|
// 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();
|
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, 1, 4));
|
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 })
|
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 high = store.Render(AtHigh());
|
||||||
|
|
||||||
var differing = own.Keys.Union(high.Keys)
|
var differing = own.Keys.Union(high.Keys)
|
||||||
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key))
|
.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");
|
|
||||||
|
|
||||||
Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range",
|
Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range",
|
||||||
"gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k));
|
"gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k));
|
||||||
@@ -128,6 +118,8 @@ public class GraphicsPresetTests
|
|||||||
var again = new TestInstallation(installation.Files).SettingsStore;
|
var again = new TestInstallation(installation.Files).SettingsStore;
|
||||||
again.Load();
|
again.Load();
|
||||||
Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(again.Settings));
|
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]
|
[Fact]
|
||||||
@@ -144,158 +136,102 @@ public class GraphicsPresetTests
|
|||||||
again.StartAtHighWithoutOwnSettings();
|
again.StartAtHighWithoutOwnSettings();
|
||||||
|
|
||||||
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(again.Settings));
|
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(again.Settings));
|
||||||
|
Assert.False(again.Settings.MovedToStandard);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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]
|
[Fact]
|
||||||
public void The_new_renderers_scales_never_go_down()
|
public void Ultra_is_the_top_of_what_the_old_starter_offered()
|
||||||
{
|
|
||||||
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()
|
|
||||||
{
|
{
|
||||||
var ultra = GraphicsPreset.Ultra;
|
var ultra = GraphicsPreset.Ultra;
|
||||||
double Top(string key) => SimulatorKeys.Named(key).Maximum;
|
|
||||||
|
|
||||||
Assert.Equal(8192, ultra.TextureSize);
|
Assert.Equal(8192, ultra.TextureSize);
|
||||||
Assert.Equal(8192, ultra.CabTextureSize);
|
Assert.Equal(GraphicsRules.MaxCabTextureSize, ultra.CabTextureSize);
|
||||||
Assert.Equal(8192, ultra.ShadowMap);
|
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(Steps.Anisotropy.Max(), ultra.Anisotropy);
|
||||||
Assert.Equal(AntiAliasingMode.Msaa8, ultra.AntiAliasing);
|
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.SmokeFidelity);
|
||||||
Assert.Equal(4, ultra.SplineFidelity);
|
Assert.Equal(4, ultra.SplineFidelity);
|
||||||
Assert.Equal(200, ultra.BufferScale);
|
Assert.Equal(SliderRanges.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
|
||||||
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(100, ultra.CabShadowsRange);
|
Assert.Equal(100, ultra.CabShadowsRange);
|
||||||
|
|
||||||
var extras = ultra.Extras!;
|
var extras = ultra.Extras!;
|
||||||
Assert.Equal(200, extras.PythonUpdateMs);
|
Assert.Equal(200, extras.PythonUpdateMs);
|
||||||
Assert.True(extras.MotionBlur && extras.ChromaticAberration && extras.Smoke);
|
Assert.True(extras.MotionBlur && extras.ChromaticAberration && extras.Smoke);
|
||||||
|
|
||||||
var top = ultra.Top!;
|
Assert.True(ultra.Top!.Screens);
|
||||||
Assert.Equal(Top(GraphicsTop.ScreenWindowFpsKey), top.ScreenWindowFps);
|
|
||||||
Assert.True(top.Screens && top.ScreenMipmaps && top.Sky && top.Cab && top.AirCouplers && top.SmoothTraction);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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.
|
[Fact]
|
||||||
Assert.Equal(0.2, top.ShadowAngleLimit);
|
public void No_level_sets_what_only_the_advanced_mode_shows()
|
||||||
Assert.Equal(0, top.TargetFps);
|
{
|
||||||
Assert.Equal(0, top.TextureRelease);
|
var set = GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys).ToList();
|
||||||
Assert.False(top.CompressTextures);
|
|
||||||
Assert.False(top.SkipDecor);
|
// 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]
|
[Fact]
|
||||||
@@ -304,16 +240,14 @@ public class GraphicsPresetTests
|
|||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
settings.ShadowAngleLimit = 0.8;
|
settings.ShadowAngleLimit = 0.8;
|
||||||
settings.IgnoreIrrelevantTrains = true;
|
settings.IgnoreIrrelevantTrains = true;
|
||||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
settings.PythonScreens = false;
|
||||||
settings.Extra[GraphicsTop.TextureReleaseKey] = "2";
|
|
||||||
|
|
||||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||||
|
|
||||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
||||||
Assert.Equal(0.2, settings.ShadowAngleLimit);
|
Assert.Equal(0.2, settings.ShadowAngleLimit);
|
||||||
Assert.False(settings.IgnoreIrrelevantTrains);
|
Assert.True(settings.PythonScreens);
|
||||||
Assert.Equal("0", settings.Extra[GraphicsTop.TargetFpsKey]);
|
Assert.True(settings.IgnoreIrrelevantTrains);
|
||||||
Assert.Equal("0", settings.Extra[GraphicsTop.TextureReleaseKey]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -335,12 +269,12 @@ public class GraphicsPresetTests
|
|||||||
{
|
{
|
||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
settings.IgnoreIrrelevantTrains = true;
|
settings.IgnoreIrrelevantTrains = true;
|
||||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
settings.ShadowAngleLimit = 0.8;
|
||||||
|
|
||||||
preset.ApplyTo(settings);
|
preset.ApplyTo(settings);
|
||||||
|
|
||||||
Assert.True(settings.IgnoreIrrelevantTrains, preset.NameKey);
|
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));
|
Assert.Same(preset, GraphicsPreset.Matching(settings));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -352,26 +286,11 @@ public class GraphicsPresetTests
|
|||||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
||||||
|
|
||||||
settings.Extra[GraphicsPreset.ReflectedVehiclesKey] = "250";
|
settings.ReflectionsFramerate = 25;
|
||||||
|
|
||||||
Assert.Null(GraphicsPreset.Matching(settings));
|
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]
|
[Fact]
|
||||||
public void Shadows_reach_further_with_every_level_that_has_them()
|
public void Shadows_reach_further_with_every_level_that_has_them()
|
||||||
{
|
{
|
||||||
@@ -405,29 +324,17 @@ public class GraphicsPresetTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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)
|
foreach (var preset in GraphicsPreset.All)
|
||||||
{
|
{
|
||||||
var settings = Defaults().Copy();
|
Assert.True(preset.TextureSize >= SliderRanges.MinTextureSize, preset.NameKey);
|
||||||
settings.BufferScalePercent = 120;
|
Assert.True(preset.ShadowMap >= SliderRanges.MinShadowMap, preset.NameKey);
|
||||||
|
Assert.True(preset.DynamicLights >= SliderRanges.MinDynamicLights, preset.NameKey);
|
||||||
preset.ApplyTo(settings);
|
Assert.Contains(preset.ReflectionsRate, SliderRanges.ReflectionUpdates);
|
||||||
Assert.Equal(preset.BufferScale, settings.BufferScalePercent);
|
|
||||||
|
|
||||||
settings.BufferScalePercent = 120;
|
|
||||||
Assert.Null(GraphicsPreset.Matching(settings));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[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]
|
[Fact]
|
||||||
public void The_lowest_level_is_not_recognised_with_one_of_its_extras_undone()
|
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();
|
var settings = Defaults().Copy();
|
||||||
settings.MotionBlur = false;
|
settings.MotionBlur = false;
|
||||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
settings.ShadowAngleLimit = 0.8;
|
||||||
|
|
||||||
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Medium, settings);
|
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Medium, settings);
|
||||||
|
|
||||||
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
||||||
Assert.False(settings.MotionBlur);
|
Assert.False(settings.MotionBlur);
|
||||||
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
|
Assert.Equal(0.8, settings.ShadowAngleLimit);
|
||||||
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
|
|
||||||
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,14 +380,12 @@ public class GraphicsPresetTests
|
|||||||
|
|
||||||
var entering = memory.Apply(GraphicsPreset.Minimal, settings);
|
var entering = memory.Apply(GraphicsPreset.Minimal, settings);
|
||||||
Assert.Equal(GraphicsPreset.Minimal.Extras, GraphicsExtras.Of(settings));
|
Assert.Equal(GraphicsPreset.Minimal.Extras, GraphicsExtras.Of(settings));
|
||||||
Assert.Equal(GraphicsPreset.RowKeys, entering.RowKeys);
|
|
||||||
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), entering.ChosenKeys);
|
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), entering.ChosenKeys);
|
||||||
|
|
||||||
var leaving = memory.Apply(GraphicsPreset.Medium, settings);
|
var leaving = memory.Apply(GraphicsPreset.Medium, settings);
|
||||||
|
|
||||||
Assert.Equal(before, GraphicsExtras.Of(settings));
|
Assert.Equal(before, GraphicsExtras.Of(settings));
|
||||||
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
||||||
Assert.Equal(GraphicsPreset.RowKeys, leaving.RowKeys);
|
|
||||||
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), leaving.ChosenKeys);
|
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), leaving.ChosenKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -492,7 +396,6 @@ public class GraphicsPresetTests
|
|||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
settings.MotionBlur = false;
|
settings.MotionBlur = false;
|
||||||
settings.ShadowAngleLimit = 0.8;
|
settings.ShadowAngleLimit = 0.8;
|
||||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
|
||||||
var extras = GraphicsExtras.Of(settings);
|
var extras = GraphicsExtras.Of(settings);
|
||||||
var top = GraphicsTop.Of(settings);
|
var top = GraphicsTop.Of(settings);
|
||||||
|
|
||||||
@@ -502,7 +405,6 @@ public class GraphicsPresetTests
|
|||||||
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
||||||
Assert.Equal(top, GraphicsTop.Of(settings));
|
Assert.Equal(top, GraphicsTop.Of(settings));
|
||||||
Assert.Same(GraphicsPreset.VeryHigh, GraphicsPreset.Matching(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);
|
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys), applied.ChosenKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,12 +414,11 @@ public class GraphicsPresetTests
|
|||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
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(GraphicsExtras.None, GraphicsExtras.Of(settings));
|
||||||
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(settings));
|
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(settings));
|
||||||
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
|
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
|
||||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -526,19 +427,18 @@ public class GraphicsPresetTests
|
|||||||
var memory = new GraphicsPresetMemory();
|
var memory = new GraphicsPresetMemory();
|
||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
settings.MotionBlur = false;
|
settings.MotionBlur = false;
|
||||||
|
settings.ShadowAngleLimit = 0.8;
|
||||||
var extras = GraphicsExtras.Of(settings);
|
var extras = GraphicsExtras.Of(settings);
|
||||||
var top = GraphicsTop.Of(settings);
|
var top = GraphicsTop.Of(settings);
|
||||||
|
|
||||||
memory.Apply(GraphicsPreset.Minimal, 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.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));
|
Assert.Same(GraphicsPreset.Minimal, GraphicsPreset.Matching(settings));
|
||||||
// Ultra's own values go, Minimal has no say over them.
|
// Ultra's own values go, Minimal has no say over them.
|
||||||
Assert.Equal(top, GraphicsTop.Of(settings));
|
Assert.Equal(top, GraphicsTop.Of(settings));
|
||||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toMinimal.RowKeys);
|
|
||||||
|
|
||||||
memory.Apply(GraphicsPreset.Medium, settings);
|
memory.Apply(GraphicsPreset.Medium, settings);
|
||||||
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
||||||
@@ -560,7 +460,6 @@ public class GraphicsPresetTests
|
|||||||
var applied = memory.Apply(GraphicsPreset.High, settings);
|
var applied = memory.Apply(GraphicsPreset.High, settings);
|
||||||
|
|
||||||
Assert.True(settings.MotionBlur);
|
Assert.True(settings.MotionBlur);
|
||||||
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
|
|
||||||
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -596,33 +495,15 @@ public class GraphicsPresetTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void Every_level_sits_on_the_steps_the_screen_offers()
|
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)
|
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.Anisotropy, preset.Anisotropy) >= 0, preset.NameKey);
|
||||||
Assert.True(Steps.IndexOf(Steps.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
|
Assert.True(Steps.IndexOf(SliderRanges.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
|
||||||
Assert.True(Steps.IndexOf(Steps.DrawRangeFactors, preset.DrawRangeFactor) >= 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 })
|
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(size is >= 512 and <= 8192 && (size & (size - 1)) == 0, preset.NameKey);
|
||||||
Assert.True(preset.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), 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.Equal(inGroups.Distinct(), inGroups);
|
||||||
Assert.Empty(inGroups.Except(GraphicsPreset.Keys).Except(GraphicsExtras.Keys).Except(GraphicsTop.Keys));
|
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));
|
GraphicsPreset.Keys.Except(inGroups).OrderBy(key => key, StringComparer.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -669,27 +550,22 @@ public class GraphicsPresetTests
|
|||||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||||
|
|
||||||
Assert.All(Groups().LevelsOf(settings).Values, level => Assert.Same(GraphicsPreset.Ultra, level));
|
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]
|
[Fact]
|
||||||
public void A_part_moved_by_hand_is_at_no_level_and_the_others_keep_theirs()
|
public void A_part_moved_by_hand_is_at_no_level_and_the_others_keep_theirs()
|
||||||
{
|
{
|
||||||
var settings = AtHigh();
|
var settings = AtHigh();
|
||||||
settings.DynamicLights = 6;
|
settings.ReflectionsFidelity = 0;
|
||||||
|
|
||||||
var levels = Groups().LevelsOf(settings);
|
var levels = Groups().LevelsOf(settings);
|
||||||
|
|
||||||
Assert.Null(levels[GraphicsGroup.Lights]);
|
Assert.Null(levels[GraphicsGroup.Reflections]);
|
||||||
Assert.Same(GraphicsPreset.High, levels[GraphicsGroup.Shadows]);
|
Assert.Same(GraphicsPreset.High, levels[GraphicsGroup.Shadows]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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();
|
var groups = Groups();
|
||||||
foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null))
|
foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null))
|
||||||
@@ -697,8 +573,9 @@ public class GraphicsPresetTests
|
|||||||
var settings = Defaults().Copy();
|
var settings = Defaults().Copy();
|
||||||
foreach (var group in GraphicsGroup.All)
|
foreach (var group in GraphicsGroup.All)
|
||||||
settings = groups.Apply(group, level, settings);
|
settings = groups.Apply(group, level, settings);
|
||||||
settings.BufferScalePercent = level.BufferScale;
|
|
||||||
settings.AntiAliasing = level.AntiAliasing;
|
settings.AntiAliasing = level.AntiAliasing;
|
||||||
|
settings.DynamicLights = level.DynamicLights;
|
||||||
|
settings.SmokeFidelity = level.SmokeFidelity;
|
||||||
|
|
||||||
Assert.Same(level, GraphicsPreset.Matching(settings));
|
Assert.Same(level, GraphicsPreset.Matching(settings));
|
||||||
}
|
}
|
||||||
@@ -718,14 +595,15 @@ public class GraphicsPresetTests
|
|||||||
{
|
{
|
||||||
var groups = Groups();
|
var groups = Groups();
|
||||||
var settings = AtHigh();
|
var settings = AtHigh();
|
||||||
|
settings.ShadowAngleLimit = 0.8;
|
||||||
|
|
||||||
var ultra = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.Ultra, settings);
|
var ultra = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.Ultra, settings);
|
||||||
Assert.False(ultra.CompressTextures);
|
Assert.Equal(0.2, ultra.ShadowAngleLimit);
|
||||||
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Textures]);
|
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Shadows]);
|
||||||
|
|
||||||
var back = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.High, ultra);
|
var back = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.High, ultra);
|
||||||
Assert.Equal(GraphicsTop.None.CompressTextures, back.CompressTextures);
|
Assert.Equal(GraphicsTop.None.ShadowAngleLimit, back.ShadowAngleLimit);
|
||||||
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Textures]);
|
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Shadows]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -736,8 +614,9 @@ public class GraphicsPresetTests
|
|||||||
|
|
||||||
settings.Smoke = false;
|
settings.Smoke = false;
|
||||||
|
|
||||||
var nature = Groups().Apply(GraphicsGroup.Nature, GraphicsPreset.VeryHigh, settings);
|
var shadows = Groups().Apply(GraphicsGroup.Shadows, GraphicsPreset.VeryHigh, settings);
|
||||||
Assert.False(nature.Smoke);
|
Assert.False(shadows.Smoke);
|
||||||
Assert.Equal(GraphicsPreset.VeryHigh.SmokeFidelity, nature.SmokeFidelity);
|
Assert.False(shadows.MotionBlur);
|
||||||
|
Assert.Equal(GraphicsPreset.VeryHigh.ShadowMap, shadows.ShadowMapResolution);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,17 +17,17 @@ public class GraphicsSettingsTests
|
|||||||
return installation;
|
return installation;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static SimulatorSettings Read(string text, bool dlssPlatform = true)
|
private static SimulatorSettings Read(string text)
|
||||||
{
|
{
|
||||||
var s = new SimulatorSettings();
|
var s = new SimulatorSettings();
|
||||||
new SettingsSerializer(dlssPlatform).Read(s, ConfigFile.Parse(text));
|
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
|
||||||
return s;
|
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);
|
var c = ConfigFile.Parse(text);
|
||||||
new SettingsSerializer(dlssPlatform).Write(s, c);
|
new SettingsSerializer().Write(s, c);
|
||||||
return c.ToText();
|
return c.ToText();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,63 +37,54 @@ public class GraphicsSettingsTests
|
|||||||
private static string? Line(string text, string key) =>
|
private static string? Line(string text, string key) =>
|
||||||
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
|
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]
|
[Theory]
|
||||||
[InlineData("full", GraphicsBackend.OpenGL)]
|
[InlineData("default", "default")]
|
||||||
[InlineData("default", GraphicsBackend.OpenGL)]
|
[InlineData("full", "default")]
|
||||||
[InlineData("gl46", GraphicsBackend.OpenGL)]
|
[InlineData("gl46", "default")]
|
||||||
[InlineData("legacy", GraphicsBackend.OpenGL)]
|
[InlineData("vulkan", "default")]
|
||||||
[InlineData("experimental", GraphicsBackend.OpenGL)]
|
[InlineData("vulkan14", "default")]
|
||||||
[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("legacy", "legacy")]
|
[InlineData("legacy", "legacy")]
|
||||||
[InlineData("simpleshader", "legacy")]
|
[InlineData("simpleshader", "legacy")]
|
||||||
|
[InlineData("off", "legacy")]
|
||||||
[InlineData("simple", "simple")]
|
[InlineData("simple", "simple")]
|
||||||
[InlineData("experimental", "experimental")]
|
[InlineData("experimental", "default")]
|
||||||
[InlineData("vulkan14", "vulkan")]
|
public void A_renderer_is_written_by_the_name_master_knows(string read, string written)
|
||||||
public void A_renderer_is_written_by_its_name(string read, string written)
|
|
||||||
{
|
{
|
||||||
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
|
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]
|
[Fact]
|
||||||
public void An_older_renderer_stays_chosen_and_can_be_chosen_again()
|
public void An_older_renderer_stays_chosen_and_can_be_chosen_again()
|
||||||
{
|
{
|
||||||
var installation = WithIni("gfxrenderer legacy\n");
|
var installation = WithIni("gfxrenderer legacy\n");
|
||||||
var store = installation.SettingsStore;
|
var store = installation.SettingsStore;
|
||||||
|
|
||||||
store.Settings.Clouds = 3;
|
store.Settings.FieldOfView = 50;
|
||||||
store.Save();
|
store.Save();
|
||||||
Assert.Contains("gfxrenderer legacy", installation.Files.ReadAllText(UserIni));
|
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.Settings.RenderEngine = SimulatorSettings.RenderEngineOf("simple");
|
||||||
store.Save();
|
store.Save();
|
||||||
Assert.Contains("gfxrenderer simple", installation.Files.ReadAllText(UserIni));
|
Assert.Contains("gfxrenderer simple", installation.Files.ReadAllText(UserIni));
|
||||||
Assert.Equal(GraphicsBackend.OpenGL, store.Settings.Backend);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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 =
|
string[] old =
|
||||||
{
|
{
|
||||||
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes",
|
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes", "gfx.shadows.cab.range 20"
|
||||||
"gfx.framebuffer.width 1920", "gfx.framebuffer.height 1080", "gfx.shadows.cab.range 20"
|
|
||||||
};
|
};
|
||||||
var installation = WithIni(string.Join("\n", old) + "\n");
|
var installation = WithIni(string.Join("\n", old) + "\n");
|
||||||
installation.SettingsStore.Settings.Clouds = 3;
|
installation.SettingsStore.Settings.FieldOfView = 50;
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
@@ -101,6 +92,24 @@ public class GraphicsSettingsTests
|
|||||||
Assert.All(old, line => Assert.Contains(line, saved));
|
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]
|
[Fact]
|
||||||
public void Levels_leave_the_switches_only_an_older_simulator_reads()
|
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));
|
Assert.Equal((false, true, true), (s.UseVbo, s.UseGLES, s.RenderAngleVulkan));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void The_new_graphics_keys_are_read()
|
[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" +
|
Assert.Equal(expected, Read(text).AntiAliasing);
|
||||||
"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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Missing_keys_take_the_simulators_defaults()
|
public void Multisampling_is_written_to_its_own_key_only()
|
||||||
{
|
|
||||||
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()
|
|
||||||
{
|
{
|
||||||
var s = Read("multisampling 1\n");
|
var s = Read("multisampling 1\n");
|
||||||
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
|
|
||||||
|
|
||||||
string text = Write(s);
|
string text = Write(s);
|
||||||
|
|
||||||
Assert.Equal("multisampling 1", Line(text, "multisampling"));
|
Assert.Equal("multisampling 1", Line(text, "multisampling"));
|
||||||
Assert.Equal("gfx.antialiasing msaax2", Line(text, "gfx.antialiasing"));
|
Assert.Null(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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -278,10 +153,23 @@ public class GraphicsSettingsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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(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"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -312,7 +200,7 @@ public class GraphicsSettingsTests
|
|||||||
{
|
{
|
||||||
var s = new SimulatorSettings();
|
var s = new SimulatorSettings();
|
||||||
GraphicsPreset.High.ApplyTo(s);
|
GraphicsPreset.High.ApplyTo(s);
|
||||||
s.Clouds = 4;
|
s.DynamicLights = 2;
|
||||||
|
|
||||||
Assert.Null(GraphicsPreset.Matching(s));
|
Assert.Null(GraphicsPreset.Matching(s));
|
||||||
}
|
}
|
||||||
@@ -328,82 +216,62 @@ public class GraphicsSettingsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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 };
|
foreach (var level in GraphicsPreset.All)
|
||||||
var opengl = new SimulatorSettings();
|
{
|
||||||
|
var s = new SimulatorSettings { IgnoreIrrelevantTrains = false };
|
||||||
|
level.ApplyTo(s);
|
||||||
|
Assert.False(s.IgnoreIrrelevantTrains, level.NameKey);
|
||||||
|
|
||||||
GraphicsPreset.Ultra.ApplyTo(vulkan);
|
s.IgnoreIrrelevantTrains = true;
|
||||||
GraphicsPreset.Ultra.ApplyTo(opengl);
|
level.ApplyTo(s);
|
||||||
|
Assert.True(s.IgnoreIrrelevantTrains, level.NameKey);
|
||||||
Assert.True(vulkan.RayTracing);
|
}
|
||||||
Assert.False(opengl.RayTracing);
|
|
||||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(opengl));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_level_keeps_dlss_on_vulkan()
|
|
||||||
{
|
|
||||||
var s = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine, AntiAliasing = AntiAliasingMode.Dlss };
|
|
||||||
|
|
||||||
GraphicsPreset.Ultra.ApplyTo(s);
|
|
||||||
|
|
||||||
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
|
|
||||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(s));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_level_replaces_taa_with_its_own_multisampling()
|
|
||||||
{
|
|
||||||
var s = new SimulatorSettings { AntiAliasing = AntiAliasingMode.Taa };
|
|
||||||
|
|
||||||
GraphicsPreset.Medium.ApplyTo(s);
|
|
||||||
|
|
||||||
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_import_takes_the_settings_but_keeps_this_installations_simulator_and_the_unmanaged_lines()
|
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");
|
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\ngfx.clouds ultra\ngfxrenderer vulkan\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"));
|
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
|
||||||
var s = installation.SettingsStore.Settings;
|
var s = installation.SettingsStore.Settings;
|
||||||
Assert.Equal(4, s.Clouds);
|
Assert.Equal(60, s.FieldOfView);
|
||||||
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
|
Assert.Equal(SimulatorSettings.RenderEngineOf("legacy"), s.RenderEngine);
|
||||||
Assert.Equal("eu07_local.exe", s.ExecutablePath);
|
Assert.Equal("eu07_local.exe", s.ExecutablePath);
|
||||||
|
|
||||||
// Nothing is written until saved, and the save keeps the user's own lines.
|
// 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();
|
installation.SettingsStore.Save();
|
||||||
string saved = installation.Files.ReadAllText(UserIni);
|
string saved = installation.Files.ReadAllText(UserIni);
|
||||||
Assert.Contains("calibratein 0 0 0 0", saved);
|
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);
|
Assert.Contains("starter.exe.path eu07_local.exe", saved);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_import_of_a_missing_file_changes_nothing()
|
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.False(installation.SettingsStore.ImportFrom("/nowhere/eu07.ini"));
|
||||||
Assert.Equal(1, installation.SettingsStore.Settings.Clouds);
|
Assert.Equal(50, installation.SettingsStore.Settings.FieldOfView);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_export_writes_a_complete_file_elsewhere_and_leaves_the_users_one_alone()
|
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");
|
var installation = WithIni("calibratein 0 0 0 0\nfieldofview 45\n");
|
||||||
installation.SettingsStore.Settings.Clouds = 3;
|
installation.SettingsStore.Settings.FieldOfView = 60;
|
||||||
|
|
||||||
Assert.True(installation.SettingsStore.ExportTo("/export/eu07.ini"));
|
Assert.True(installation.SettingsStore.ExportTo("/export/eu07.ini"));
|
||||||
|
|
||||||
string exported = installation.Files.ReadAllText("/export/eu07.ini");
|
string exported = installation.Files.ReadAllText("/export/eu07.ini");
|
||||||
Assert.Contains("calibratein 0 0 0 0", exported);
|
Assert.Contains("calibratein 0 0 0 0", exported);
|
||||||
Assert.Contains("gfx.clouds high", exported);
|
Assert.Contains("fieldofview 60", exported);
|
||||||
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
|
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -417,30 +285,34 @@ public class GraphicsSettingsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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()
|
Assert.True(Read("").IgnoreGamepad);
|
||||||
.WithDirectory(TestInstallation.Root)
|
Assert.Equal("input.gamepad no", Line(Write(Read("")), "input.gamepad"));
|
||||||
.WithExecutable(TestInstallation.At("eu07.exe"), "MZ binary")
|
Assert.False(Read("input.gamepad yes\n").IgnoreGamepad);
|
||||||
.WithFile(TestInstallation.At("nvngx_dlss.dll"), "dll");
|
Assert.True(Read("input.gamepad no\n").IgnoreGamepad);
|
||||||
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")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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()
|
Assert.False(Read("").AdvancedSettings);
|
||||||
.WithDirectory(TestInstallation.Root)
|
Assert.True(Read("starter.settings.advanced yes\n").AdvancedSettings);
|
||||||
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
|
|
||||||
.WithFile(TestInstallation.At("libnvidia-ngx-dlssg.so.310.4.0"), "so");
|
|
||||||
var installation = new TestInstallation(files);
|
|
||||||
|
|
||||||
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]
|
[Fact]
|
||||||
@@ -455,139 +327,4 @@ public class GraphicsSettingsTests
|
|||||||
c.Set("b", "9");
|
c.Set("b", "9");
|
||||||
Assert.Equal("b 9\nc 3\na 1\n", c.ToText().Replace("\r\n", "\n"));
|
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
|
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] " +
|
"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 " +
|
"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";
|
"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) =>
|
int security = 0) =>
|
||||||
string.Create(CultureInfo.InvariantCulture,
|
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} ") +
|
$"{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);
|
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]
|
[Fact]
|
||||||
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
28
StarterNG.Tests/LoadingScreenLogoTests.cs
Normal file
28
StarterNG.Tests/LoadingScreenLogoTests.cs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
using StarterNG.Infrastructure;
|
||||||
|
using StarterNG.Tests.Fakes;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class LoadingScreenLogoTests
|
||||||
|
{
|
||||||
|
private static InMemoryFileSystem Logos() => new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile("game/Textures/Logo/EP09_Logo.PNG", "png")
|
||||||
|
.WithFile("game/Textures/Logo/Braniewo.JPG", "jpg")
|
||||||
|
.WithFile("game/Textures/Logo/Logo1.BMP", "bmp")
|
||||||
|
.WithFile("game/Textures/Logo/notes.txt", "");
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ep09_logo", null, "EP09_Logo.PNG")]
|
||||||
|
[InlineData("ep09_logo.bmp", "braniewo", "EP09_Logo.PNG")]
|
||||||
|
[InlineData(null, "braniewo", "Braniewo.JPG")]
|
||||||
|
[InlineData("brak", "brak", "Logo1.BMP")]
|
||||||
|
public void The_logo_is_found_whatever_the_case_of_its_name_and_extension(string? logo, string? scenery,
|
||||||
|
string onDisk) =>
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine("game", "Textures", "Logo", onDisk)),
|
||||||
|
Path.GetFullPath(LoadingScreen.FindSource(Logos(), "game", logo, scenery, new Random(1))!));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void With_no_logo_folder_there_is_no_logo() =>
|
||||||
|
Assert.Null(LoadingScreen.FindSource(new InMemoryFileSystem(caseSensitive: true), "game", "x", "y",
|
||||||
|
new Random(1)));
|
||||||
|
}
|
||||||
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
61
StarterNG.Tests/MonitorsTests.cs
Normal file
61
StarterNG.Tests/MonitorsTests.cs
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
80
StarterNG.Tests/OneAtATimeTests.cs
Normal file
80
StarterNG.Tests/OneAtATimeTests.cs
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
using StarterNG.Application;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class OneAtATimeTests
|
||||||
|
{
|
||||||
|
private static async Task Until(Func<bool> condition)
|
||||||
|
{
|
||||||
|
var giveUp = DateTime.UtcNow.AddSeconds(5);
|
||||||
|
while (!condition())
|
||||||
|
{
|
||||||
|
Assert.True(DateTime.UtcNow < giveUp, "waited too long");
|
||||||
|
await Task.Delay(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Asked_once_it_runs_once()
|
||||||
|
{
|
||||||
|
int runs = 0;
|
||||||
|
var once = new OneAtATime(() => { runs++; return Task.CompletedTask; });
|
||||||
|
|
||||||
|
await once.RunAsync();
|
||||||
|
|
||||||
|
Assert.Equal(1, runs);
|
||||||
|
Assert.False(once.IsRunning);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Asked_while_running_it_runs_once_more_after_not_alongside()
|
||||||
|
{
|
||||||
|
int runs = 0, together = 0, most = 0;
|
||||||
|
var gates = new Queue<TaskCompletionSource>();
|
||||||
|
var once = new OneAtATime(async () =>
|
||||||
|
{
|
||||||
|
runs++;
|
||||||
|
most = Math.Max(most, ++together);
|
||||||
|
var gate = new TaskCompletionSource();
|
||||||
|
gates.Enqueue(gate);
|
||||||
|
await gate.Task;
|
||||||
|
together--;
|
||||||
|
});
|
||||||
|
|
||||||
|
var first = once.RunAsync();
|
||||||
|
// Three requests during the first run make one more run, not three.
|
||||||
|
await once.RunAsync();
|
||||||
|
await once.RunAsync();
|
||||||
|
await once.RunAsync();
|
||||||
|
Assert.Equal(1, runs);
|
||||||
|
|
||||||
|
gates.Dequeue().SetResult();
|
||||||
|
await Until(() => Volatile.Read(ref runs) == 2);
|
||||||
|
await Until(() => gates.Count == 1);
|
||||||
|
gates.Dequeue().SetResult();
|
||||||
|
await first;
|
||||||
|
|
||||||
|
Assert.Equal(2, runs);
|
||||||
|
Assert.Equal(1, most);
|
||||||
|
Assert.False(once.IsRunning);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_failed_run_does_not_keep_it_busy()
|
||||||
|
{
|
||||||
|
bool fail = true;
|
||||||
|
int runs = 0;
|
||||||
|
var once = new OneAtATime(() =>
|
||||||
|
{
|
||||||
|
runs++;
|
||||||
|
return fail ? Task.FromException(new IOException("locked")) : Task.CompletedTask;
|
||||||
|
});
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<IOException>(once.RunAsync);
|
||||||
|
fail = false;
|
||||||
|
await once.RunAsync();
|
||||||
|
|
||||||
|
Assert.Equal(2, runs);
|
||||||
|
Assert.False(once.IsRunning);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,20 @@ public sealed class PhysicalFileSystemTests : IDisposable
|
|||||||
Assert.Equal(new[] { path }, Directory.GetFiles(_root));
|
Assert.Equal(new[] { path }, Directory.GetFiles(_root));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_pattern_lists_names_in_any_letter_case()
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.Combine(_root, "PKP", "EP09"));
|
||||||
|
foreach (string name in new[] { "Braniewo.SCN", "kato.scn", "notes.txt", Path.Combine("PKP", "EP09", "EP09.FIZ"),
|
||||||
|
Path.Combine("PKP", "EP09", "ep09dumb.fiz") })
|
||||||
|
File.WriteAllText(Path.Combine(_root, name), "");
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "Braniewo.SCN", "kato.scn" },
|
||||||
|
_files.GetFiles(_root, "*.scn").Select(Path.GetFileName).Order(StringComparer.Ordinal));
|
||||||
|
Assert.Equal(new[] { "EP09.FIZ", "ep09dumb.fiz" },
|
||||||
|
_files.GetFilesRecursive(_root, "*.fiz").Select(Path.GetFileName).Order(StringComparer.Ordinal));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_atomic_write_that_cannot_finish_leaves_what_stood_there()
|
public void An_atomic_write_that_cannot_finish_leaves_what_stood_there()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -65,6 +65,19 @@ public class PhysicsAndAssetsTests
|
|||||||
Assert.Equal(125, physics.VMax);
|
Assert.Equal(125, physics.VMax);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_include_named_in_other_case_is_followed()
|
||||||
|
{
|
||||||
|
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(Fiz("pkp", "ep07", "ep07"), "include Common.FIZ 84000 end")
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "pkp", "ep07", "common.fiz"), "Param: M=(1) Vmax=125"));
|
||||||
|
|
||||||
|
var physics = installation.Physics.For("pkp/ep07/", "ep07")!;
|
||||||
|
|
||||||
|
Assert.Equal(84000, physics.Mass);
|
||||||
|
Assert.Equal(125, physics.VMax);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void A_dot_in_the_model_name_is_part_of_the_name()
|
public void A_dot_in_the_model_name_is_part_of_the_name()
|
||||||
{
|
{
|
||||||
@@ -202,4 +215,31 @@ public class PhysicsAndAssetsTests
|
|||||||
|
|
||||||
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
|
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_livery_with_no_folder_is_looked_for_in_dynamic_itself()
|
||||||
|
{
|
||||||
|
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "EP09.bmp"), "bitmap")
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "ep09.e3d"), "model"));
|
||||||
|
var catalog = new StarterNG.Domain.Vehicles.VehicleCatalog(installation.MiniTextures);
|
||||||
|
catalog.Textures.Add(new StarterNG.Domain.Vehicles.VehicleTexture { Directory = "", Skinfile = "ep09", Model = "EP09" });
|
||||||
|
|
||||||
|
Assert.Empty(installation.MissingAssets.Scan(catalog));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_skin_and_model_on_disk_in_other_case_are_not_reported()
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "textures.txt"),
|
||||||
|
"EP09-014.mat=ep09.e3d,ep09")
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "ep09-014.BMP"), "bitmap")
|
||||||
|
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "EP09.E3D"), "model");
|
||||||
|
var installation = new TestInstallation(files);
|
||||||
|
installation.Vehicles.Load(installation.Library.Vehicles);
|
||||||
|
Assert.NotEmpty(installation.Library.Vehicles.Textures);
|
||||||
|
|
||||||
|
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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));
|
||||||
|
}
|
||||||
@@ -182,6 +182,20 @@ public class TimetableLocatorTests
|
|||||||
Assert.NotNull(new TimetableLocator(files).Resolve(scenery, "r1.txt"));
|
Assert.NotNull(new TimetableLocator(files).Resolve(scenery, "r1.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(@"rozklady\tgs3657")]
|
||||||
|
[InlineData("ROZKLADY/TGS3657.TXT")]
|
||||||
|
public void A_timetable_named_in_other_case_or_with_backslashes_is_found_as_on_disk(string name)
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$n Braniewo")
|
||||||
|
.WithFile(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"), "rozkład");
|
||||||
|
var scenery = Assert.Single(new TestInstallation(files).Sceneries.LoadAll());
|
||||||
|
|
||||||
|
Assert.Equal(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"),
|
||||||
|
new TimetableLocator(files).Resolve(scenery, name));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void The_formats_none_and_a_missing_file_both_resolve_to_nothing()
|
public void The_formats_none_and_a_missing_file_both_resolve_to_nothing()
|
||||||
{
|
{
|
||||||
@@ -195,3 +209,26 @@ public class TimetableLocatorTests
|
|||||||
Assert.Null(locator.Resolve(scenery, null));
|
Assert.Null(locator.Resolve(scenery, null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class AttachmentLocatorTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData(@"scenery\Braniewo\opis.PDF")]
|
||||||
|
[InlineData("SCENERY/braniewo/Opis.pdf")]
|
||||||
|
public void An_attachment_named_in_other_case_is_found_as_on_disk(string named)
|
||||||
|
{
|
||||||
|
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"), "%PDF"));
|
||||||
|
|
||||||
|
Assert.Equal(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"),
|
||||||
|
new AttachmentLocator(installation.Files, installation.Paths)
|
||||||
|
.Resolve(new SceneryAttachment { FilePath = named }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("scenery/brak.pdf")]
|
||||||
|
[InlineData("")]
|
||||||
|
public void An_attachment_that_is_not_there_is_not_found(string named) =>
|
||||||
|
Assert.Null(new AttachmentLocator(new InMemoryFileSystem(caseSensitive: true), new TestInstallation().Paths)
|
||||||
|
.Resolve(new SceneryAttachment { FilePath = named }));
|
||||||
|
}
|
||||||
|
|||||||
@@ -89,6 +89,23 @@ public class SceneryRepositoryTests
|
|||||||
Assert.Equal(Path.Combine("game", "scenery", "images", "kato.jpg"), image);
|
Assert.Equal(Path.Combine("game", "scenery", "images", "kato.jpg"), image);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("calkowo_v2_kopalniaA.jpg", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
|
||||||
|
[InlineData(@"Images\Calkowo_V2_KopalniaA.JPG", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
|
||||||
|
[InlineData("CALKOWO_V2.JPG", "game/scenery/Calkowo_v2.jpg")]
|
||||||
|
public void The_preview_image_is_found_whatever_the_case_it_is_named_in(string named, string onDisk)
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile("game/scenery/calkowo.scn", "//$i " + named)
|
||||||
|
.WithFile("game/scenery/images/calkowo_v2_kopalniaA.jpg", "binary")
|
||||||
|
.WithFile("game/scenery/Calkowo_v2.jpg", "binary");
|
||||||
|
var scenery = Assert.Single(Build(files, out _).LoadAll());
|
||||||
|
|
||||||
|
string? image = new SceneryImageLocator(files).Resolve(scenery);
|
||||||
|
|
||||||
|
Assert.Equal(Path.GetFullPath(onDisk), Path.GetFullPath(image!));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void A_scenery_without_an_image_directive_resolves_to_nothing()
|
public void A_scenery_without_an_image_directive_resolves_to_nothing()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -270,10 +270,10 @@ public class ScenerySyntaxTests
|
|||||||
trainset td/rozklad tdo_n1734 0.0 0.1
|
trainset td/rozklad tdo_n1734 0.0 0.1
|
||||||
//$o Skład gotowy na żeberku.
|
//$o Skład gotowy na żeberku.
|
||||||
endtrainset
|
endtrainset
|
||||||
include koniec.scm
|
include koniec.scm end
|
||||||
""";
|
""";
|
||||||
|
|
||||||
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => new IncludeLookup(true));
|
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
|
||||||
|
|
||||||
Assert.Empty(scenery.Faults);
|
Assert.Empty(scenery.Faults);
|
||||||
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
|
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
|
||||||
@@ -326,18 +326,66 @@ public class ScenerySyntaxTests
|
|||||||
endoptional
|
endoptional
|
||||||
""";
|
""";
|
||||||
|
|
||||||
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => new IncludeLookup(name is "tory.scm" or "budynek.inc")).Faults;
|
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => name is "tory.scm" or "budynek.inc").Faults;
|
||||||
|
|
||||||
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
|
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]
|
[Fact]
|
||||||
public void An_include_named_in_another_case_is_found_as_the_simulator_finds_it()
|
public void An_include_named_in_another_case_is_found_as_the_simulator_finds_it()
|
||||||
{
|
{
|
||||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
.WithLegacyFile("game/scenery/x.scn", "FirstInit\ninclude Tomaszewo/Auta.SCM end\n")
|
.WithLegacyFile("game/scenery/x.scn", "FirstInit\ninclude Tomaszewo/Auta.SCM end\n")
|
||||||
.WithLegacyFile("game/scenery/tomaszewo/auta.scm",
|
.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 repository = TestScenery.Repository(files);
|
||||||
|
|
||||||
var scenery = repository.Load("game/scenery/x.scn")!;
|
var scenery = repository.Load("game/scenery/x.scn")!;
|
||||||
@@ -347,9 +395,9 @@ public class ScenerySyntaxTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_include_on_disk_only_in_other_letter_case_is_what_linux_misses()
|
public void An_include_on_disk_in_other_letter_case_is_no_fault()
|
||||||
{
|
{
|
||||||
// The simulator folds the name to lower case and opens it so.
|
// The simulator finds the file whatever the case of its letters, on Linux too.
|
||||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
.WithLegacyFile("game/scenery/braniewo_szeroki.scn",
|
.WithLegacyFile("game/scenery/braniewo_szeroki.scn",
|
||||||
"include braniewo/base.ctr end\ninclude Braniewo/Tory.SCM end\n")
|
"include braniewo/base.ctr end\ninclude Braniewo/Tory.SCM end\n")
|
||||||
@@ -357,21 +405,20 @@ public class ScenerySyntaxTests
|
|||||||
.WithFile("game/scenery/braniewo/tory.scm", "");
|
.WithFile("game/scenery/braniewo/tory.scm", "");
|
||||||
var repository = TestScenery.Repository(files);
|
var repository = TestScenery.Repository(files);
|
||||||
|
|
||||||
var faults = repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults;
|
Assert.Empty(repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults);
|
||||||
|
|
||||||
Assert.Equal((SceneryFaultKind.IncludeLetterCase, "braniewo_szeroki.scn", 1, "Braniewo/Base.ctr", "braniewo/base.ctr"),
|
|
||||||
Seen(Assert.Single(faults)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(true)]
|
[InlineData(null)]
|
||||||
[InlineData(false)]
|
[InlineData("lk2_sandbox.sbt")]
|
||||||
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(bool sbt)
|
[InlineData("Lk2_Sandbox.SBT")]
|
||||||
|
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(string? sbtOnDisk)
|
||||||
{
|
{
|
||||||
|
bool sbt = sbtOnDisk is not null;
|
||||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
.WithLegacyFile("game/scenery/Lk2_Sandbox.scn", "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n");
|
.WithLegacyFile("game/scenery/Lk2_Sandbox.scn", "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n");
|
||||||
if (sbt)
|
if (sbt)
|
||||||
files.WithFile("game/scenery/lk2_sandbox.sbt", "EU07");
|
files.WithFile("game/scenery/" + sbtOnDisk, "EU07");
|
||||||
var repository = TestScenery.Repository(files);
|
var repository = TestScenery.Repository(files);
|
||||||
|
|
||||||
var scenery = repository.Load("game/scenery/Lk2_Sandbox.scn")!;
|
var scenery = repository.Load("game/scenery/Lk2_Sandbox.scn")!;
|
||||||
@@ -379,4 +426,35 @@ public class ScenerySyntaxTests
|
|||||||
Assert.Equal(sbt, scenery.HasCompanionTimetable);
|
Assert.Equal(sbt, scenery.HasCompanionTimetable);
|
||||||
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,24 @@ public class SceneryTranslationsTests
|
|||||||
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
|
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_tables_are_found_whatever_the_case_of_their_names()
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$d @brief")
|
||||||
|
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "braniewo_en.json"),
|
||||||
|
"""{ "brief": "English" }""")
|
||||||
|
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "BRANIEWO_PL.json"),
|
||||||
|
"""{ "brief": "Polski" }""");
|
||||||
|
var installation = new TestInstallation(files);
|
||||||
|
var scenery = Assert.Single(installation.Sceneries.LoadAll());
|
||||||
|
var translations = new SceneryTranslations(files, installation.Log);
|
||||||
|
|
||||||
|
translations.LoadFor(scenery, "Polski");
|
||||||
|
|
||||||
|
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Literal_text_and_unknown_keys_are_left_alone()
|
public void Literal_text_and_unknown_keys_are_left_alone()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -158,14 +158,12 @@ public class ScreenReaderNamesTests
|
|||||||
var slider = new Slider();
|
var slider = new Slider();
|
||||||
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
|
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
|
||||||
row.Description = "Gra zajmie cały ekran.";
|
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.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
|
||||||
Assert.Null(AutomationProperties.GetName(check));
|
Assert.Null(AutomationProperties.GetName(check));
|
||||||
|
|
||||||
row.Description = null;
|
row.Description = null;
|
||||||
row.IdleNote = null;
|
|
||||||
Assert.Null(AutomationProperties.GetHelpText(check));
|
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -492,7 +492,7 @@ public class SettingsStoreTests
|
|||||||
[InlineData("mousescale 1.5 0.5", false, true, "mousescale 1.5 -0.5")]
|
[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", true, false, "mousescale -1.5 0.5")]
|
||||||
[InlineData("mousescale -1.5 -0.5", false, 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")]
|
[InlineData("mousescale 2.5 0.5", false, true, "mousescale 2.5 -0.5")]
|
||||||
// Further than the slider goes.
|
// Further than the slider goes.
|
||||||
[InlineData("mousescale 12 0.5", true, false, "mousescale -12 0.5")]
|
[InlineData("mousescale 12 0.5", true, false, "mousescale -12 0.5")]
|
||||||
public void A_mouse_scale_keeps_its_numbers_when_an_axis_is_inverted(
|
public void A_mouse_scale_keeps_its_numbers_when_an_axis_is_inverted(
|
||||||
@@ -540,7 +540,35 @@ public class SettingsStoreTests
|
|||||||
|
|
||||||
installation.SettingsStore.Save();
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
Assert.Equal("mousescale 2 0.2", LineFor(installation, "mousescale"));
|
Assert.Equal("mousescale 2 0.5", LineFor(installation, "mousescale"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
// The second number is always 0.5, as the old starter wrote it; its sign is the inversion.
|
||||||
|
[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")]
|
||||||
|
// A zero locks that axis in the simulator: the camera turns only left/right.
|
||||||
|
// X goes back to the default.
|
||||||
|
[InlineData("mousescale 0.5 0", "mousescale 0.5 0.5")]
|
||||||
|
[InlineData("mousescale 0.5 -0", "mousescale 0.5 0.5")]
|
||||||
|
[InlineData("mousescale 0 0.5", "mousescale 2 0.5")]
|
||||||
|
[InlineData("mousescale 0 0", "mousescale 2 0.5")]
|
||||||
|
[InlineData("mousescale 1.5 NaN", "mousescale 1.5 0.5")]
|
||||||
|
[InlineData("mousescale Infinity -0.5", "mousescale 2 -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 0.5 0.5\t// (3.2 0.5) komentarz")]
|
||||||
|
// A decimal comma: the simulator reads "0,2" as 0.
|
||||||
|
[InlineData("mousescale 0.5 0,2", "mousescale 0.5 0.5")]
|
||||||
|
public void A_mouse_scale_axis_that_would_not_move_gets_the_default(string line, string written)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Equal(written, LineFor(installation, "mousescale"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── A file that could not be read ────────────────────────────────────────
|
// ── A file that could not be read ────────────────────────────────────────
|
||||||
@@ -885,12 +913,8 @@ public class SettingsStoreTests
|
|||||||
[InlineData("default")]
|
[InlineData("default")]
|
||||||
[InlineData("simpleshader")]
|
[InlineData("simpleshader")]
|
||||||
[InlineData("off")]
|
[InlineData("off")]
|
||||||
[InlineData("opengl")]
|
|
||||||
[InlineData("gl46")]
|
|
||||||
[InlineData("vulkan14")]
|
|
||||||
[InlineData("legacy")]
|
[InlineData("legacy")]
|
||||||
[InlineData("simple")]
|
[InlineData("simple")]
|
||||||
[InlineData("experimental")]
|
|
||||||
public void A_renderer_word_the_simulator_reads_as_another_stays_until_changed(string word)
|
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"));
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
|
||||||
@@ -901,16 +925,33 @@ public class SettingsStoreTests
|
|||||||
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
|
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]
|
[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(1, "legacy")]
|
||||||
[InlineData(2, "simple")]
|
[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)
|
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
|
// application.cpp on master knows default, legacy and simple; "simpleshader" and "off"
|
||||||
// other word - "simpleshader" and "off" from older starters - is legacy.
|
// from older starters are legacy, and any other word gets the full renderer.
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n"));
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n"));
|
||||||
installation.SettingsStore.Load();
|
installation.SettingsStore.Load();
|
||||||
installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine;
|
installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine;
|
||||||
@@ -926,8 +967,10 @@ public class SettingsStoreTests
|
|||||||
[InlineData("full", 0)]
|
[InlineData("full", 0)]
|
||||||
[InlineData("gl46", 0)]
|
[InlineData("gl46", 0)]
|
||||||
[InlineData("opengl", 0)]
|
[InlineData("opengl", 0)]
|
||||||
[InlineData("vulkan", 4)]
|
[InlineData("vulkan", 0)]
|
||||||
[InlineData("VULKAN14", 4)]
|
[InlineData("VULKAN14", 0)]
|
||||||
|
[InlineData("whatever", 0)]
|
||||||
|
[InlineData("experimental", 0)]
|
||||||
[InlineData("simpleshader", 1)]
|
[InlineData("simpleshader", 1)]
|
||||||
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine)
|
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine)
|
||||||
{
|
{
|
||||||
@@ -935,7 +978,7 @@ public class SettingsStoreTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[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"));
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1000\nheight 500\n"));
|
||||||
installation.SettingsStore.Load();
|
installation.SettingsStore.Load();
|
||||||
@@ -944,19 +987,20 @@ public class SettingsStoreTests
|
|||||||
installation.SettingsStore.Save();
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
string saved = SavedLines(installation);
|
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.width 500\n", saved);
|
||||||
Assert.Contains("gfx.framebuffer.height 250\n", saved);
|
Assert.Contains("gfx.framebuffer.height 250\n", saved);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("gfx.buffer.percent 0.5\n", 50)]
|
[InlineData("width 1000\ngfx.framebuffer.width 500\n", 50)]
|
||||||
[InlineData("gfx.buffer.percent 75\n", 75)]
|
[InlineData("width 1000\ngfx.framebuffer.width 100\n", 25)]
|
||||||
[InlineData("gfx.buffer.percent 10\n", 25)]
|
[InlineData("width 1000\ngfx.framebuffer.width 3000\n", 100)]
|
||||||
[InlineData("gfx.buffer.percent 300\n", 200)]
|
[InlineData("gfx.framebuffer.width 500\n", 100)]
|
||||||
[InlineData("starter.bufferscale 60\n", 60)]
|
[InlineData("starter.bufferscale 60\n", 60)]
|
||||||
[InlineData("starter.bufferscale 60\ngfx.buffer.percent 80\n", 80)]
|
[InlineData("starter.bufferscale 60\nwidth 1000\ngfx.framebuffer.width 800\n", 60)]
|
||||||
public void The_buffer_is_read_from_the_key_the_new_simulator_goes_by(string ini, int percent)
|
[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));
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
|
||||||
@@ -965,36 +1009,6 @@ public class SettingsStoreTests
|
|||||||
Assert.Equal(percent, installation.SettingsStore.Settings.BufferScalePercent);
|
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]
|
[Fact]
|
||||||
public void A_field_of_view_down_to_ten_degrees_survives_a_save()
|
public void A_field_of_view_down_to_ten_degrees_survives_a_save()
|
||||||
{
|
{
|
||||||
@@ -1257,6 +1271,39 @@ public class SettingsStoreTests
|
|||||||
Assert.False(store.LoadFailed);
|
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]
|
[Fact]
|
||||||
public void A_missing_profile_leaves_the_settings_as_they_are()
|
public void A_missing_profile_leaves_the_settings_as_they_are()
|
||||||
{
|
{
|
||||||
@@ -1302,4 +1349,189 @@ public class SettingsStoreTests
|
|||||||
Assert.False(store.LoadFailed);
|
Assert.False(store.LoadFailed);
|
||||||
Assert.Equal(60, store.Settings.FieldOfView);
|
Assert.Equal(60, store.Settings.FieldOfView);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("physicslog yes\n", true)]
|
||||||
|
[InlineData("physicslog no\n", false)]
|
||||||
|
[InlineData("physicslog yes\nblackbox no\n", false)]
|
||||||
|
[InlineData("physicslog no\nblackbox yes\n", true)]
|
||||||
|
public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
|
||||||
|
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Tapes_turned_on_write_the_black_box_and_leave_the_physics_log_off()
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.BlackBox = true;
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||||
|
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line()
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.Width = 1600;
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Null(LineFor(installation, "blackbox"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("physicslog yes\nblackbox yes\n")]
|
||||||
|
[InlineData("physicslog no\nblackbox yes\n")]
|
||||||
|
public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.BlackBox = false;
|
||||||
|
installation.SettingsStore.Settings.PhysicsLog = false;
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Equal("blackbox no", LineFor(installation, "blackbox"));
|
||||||
|
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_physics_log_turned_off_keeps_the_tapes_it_brought()
|
||||||
|
{
|
||||||
|
// an ini of before the black box had a key: the tapes came with the physics log
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.PhysicsLog = false;
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("physicslog no\n", false, false)]
|
||||||
|
[InlineData("physicslog no\nphysicslog.trains yes\n", true, true)]
|
||||||
|
[InlineData("physicslog no\nphysicslog.trains yes\nblackbox no\n", true, false)]
|
||||||
|
public void The_logs_of_the_trains_are_read_and_bring_the_black_box_as_the_simulator_has_it(string ini, bool trains, bool recorded)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
|
||||||
|
Assert.Equal(trains, installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||||
|
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("physicslog yes\nblackbox yes\n")]
|
||||||
|
[InlineData("physicslog no\nblackbox yes\n")]
|
||||||
|
public void Recording_turned_on_before_the_tapes_of_the_trains_is_moved_to_them(string ini)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
var s = installation.SettingsStore.Settings;
|
||||||
|
Assert.False(s.PhysicsLog);
|
||||||
|
Assert.True(s.PhysicsLogTrains);
|
||||||
|
Assert.True(s.BlackBox);
|
||||||
|
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||||
|
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
||||||
|
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("physicslog yes\n", true)]
|
||||||
|
[InlineData("physicslog yes\nblackbox no\n", true)]
|
||||||
|
[InlineData("physicslog yes\nblackbox yes\nphysicslog.trains no\n", true)]
|
||||||
|
[InlineData("physicslog no\nblackbox yes\nphysicslog.trains no\n", false)]
|
||||||
|
public void Without_a_black_box_line_saying_yes_or_with_the_trains_tapes_line_nothing_is_moved(string ini, bool physicsLog)
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
|
||||||
|
Assert.Equal(physicsLog, installation.SettingsStore.Settings.PhysicsLog);
|
||||||
|
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is()
|
||||||
|
{
|
||||||
|
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
|
||||||
|
var files = new InMemoryFileSystem()
|
||||||
|
.WithFile(UserIni, "physicslog yes\nphysicslog.trains no\n")
|
||||||
|
.WithFile(backup, "physicslog yes\nblackbox yes\n");
|
||||||
|
var store = WithHome(files).SettingsStore;
|
||||||
|
store.Load();
|
||||||
|
|
||||||
|
Assert.True(store.ImportFrom(backup));
|
||||||
|
store.Save();
|
||||||
|
|
||||||
|
Assert.False(store.Settings.PhysicsLog);
|
||||||
|
Assert.True(store.Settings.PhysicsLogTrains);
|
||||||
|
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on()
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\nblackbox yes\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.PhysicsLog = true;
|
||||||
|
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
|
||||||
|
Assert.True(installation.SettingsStore.Settings.PhysicsLog);
|
||||||
|
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||||
|
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them()
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
Assert.Null(LineFor(installation, "physicslog.trains"));
|
||||||
|
|
||||||
|
installation.SettingsStore.Settings.PhysicsLogTrains = true;
|
||||||
|
installation.SettingsStore.Settings.BlackBox = true;
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
||||||
|
// it says no more than the logs of the trains bring
|
||||||
|
Assert.Null(LineFor(installation, "blackbox"));
|
||||||
|
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_black_box_line_written_once_goes_away_when_it_says_no_more()
|
||||||
|
{
|
||||||
|
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||||
|
installation.SettingsStore.Load();
|
||||||
|
installation.SettingsStore.Settings.BlackBox = true;
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
installation.SettingsStore.Settings.BlackBox = false;
|
||||||
|
installation.SettingsStore.Save();
|
||||||
|
|
||||||
|
Assert.Null(LineFor(installation, "blackbox"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
45
StarterNG.Tests/SoftwareRenderTests.cs
Normal file
45
StarterNG.Tests/SoftwareRenderTests.cs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class SoftwareRenderTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--software-render")]
|
||||||
|
[InlineData("--Software-Render")]
|
||||||
|
public void The_switch_asks_for_it_in_any_case(string arg)
|
||||||
|
{
|
||||||
|
Assert.True(SoftwareRender.AskedIn(new[] { "--other", arg }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_the_switch_the_graphics_card_draws()
|
||||||
|
{
|
||||||
|
Assert.False(SoftwareRender.AskedIn(Array.Empty<string>()));
|
||||||
|
Assert.False(SoftwareRender.AskedIn(new[] { "--software" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Windows_draws_on_the_processor_into_a_plain_window_surface()
|
||||||
|
{
|
||||||
|
var options = SoftwareRender.Win32Options;
|
||||||
|
|
||||||
|
Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode);
|
||||||
|
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void X11_draws_on_the_processor()
|
||||||
|
{
|
||||||
|
Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Both_platforms_options_go_to_the_same_builder()
|
||||||
|
{
|
||||||
|
var builder = AppBuilder.Configure<Avalonia.Application>();
|
||||||
|
|
||||||
|
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,6 +40,18 @@ public class StartSimulationTests
|
|||||||
Assert.Contains($"vehicle\t{driven}\tPKP/EP07\tep07.mmd", noted);
|
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]
|
[Fact]
|
||||||
public void Without_the_physics_log_nothing_is_noted()
|
public void Without_the_physics_log_nothing_is_noted()
|
||||||
{
|
{
|
||||||
|
|||||||
98
StarterNG.Tests/SystemGraphicsLibrariesTests.cs
Normal file
98
StarterNG.Tests/SystemGraphicsLibrariesTests.cs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
using StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class SystemGraphicsLibrariesTests
|
||||||
|
{
|
||||||
|
private const string System32 = @"C:\Windows\System32";
|
||||||
|
private const string Game = @"E:\SteamLibrary\steamapps\common\MaSzyna";
|
||||||
|
|
||||||
|
private static readonly IntPtr Dxgi = new(0x1000);
|
||||||
|
private static readonly IntPtr D3d11 = new(0x2000);
|
||||||
|
|
||||||
|
private static SystemGraphicsLibraries Take(Func<string, bool> beside, Dictionary<string, IntPtr> system)
|
||||||
|
{
|
||||||
|
return SystemGraphicsLibraries.Take(System32, Game, beside, Load);
|
||||||
|
|
||||||
|
bool Load(string path, out IntPtr handle)
|
||||||
|
{
|
||||||
|
handle = system.GetValueOrDefault(Path.GetFileName(path));
|
||||||
|
return handle != IntPtr.Zero;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SystemGraphicsLibraries WithDxgiAndD3d11(Func<string, bool> beside) =>
|
||||||
|
Take(beside, new Dictionary<string, IntPtr> { ["dxgi.dll"] = Dxgi, ["d3d11.dll"] = D3d11 });
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_import_by_name_gets_the_system_library_with_or_without_its_extension()
|
||||||
|
{
|
||||||
|
var taken = WithDxgiAndD3d11(_ => false);
|
||||||
|
|
||||||
|
Assert.Equal(Dxgi, taken.Resolve("dxgi"));
|
||||||
|
Assert.Equal(Dxgi, taken.Resolve("dxgi.dll"));
|
||||||
|
Assert.Equal(D3d11, taken.Resolve("D3D11.DLL"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Other_libraries_and_ones_the_system_lacks_are_left_to_the_usual_search()
|
||||||
|
{
|
||||||
|
var taken = WithDxgiAndD3d11(_ => false);
|
||||||
|
|
||||||
|
Assert.Equal(IntPtr.Zero, taken.Resolve("user32.dll"));
|
||||||
|
Assert.Equal(IntPtr.Zero, taken.Resolve("opengl32"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void They_are_loaded_from_the_system_folder_dxgi_first()
|
||||||
|
{
|
||||||
|
var asked = new List<string>();
|
||||||
|
SystemGraphicsLibraries.Take(System32, Game, _ => false, Load);
|
||||||
|
|
||||||
|
Assert.Equal(SystemGraphicsLibraries.Names.Select(n => Path.Combine(System32, n + ".dll")), asked);
|
||||||
|
Assert.Equal("dxgi", SystemGraphicsLibraries.Names[0]);
|
||||||
|
|
||||||
|
bool Load(string path, out IntPtr handle)
|
||||||
|
{
|
||||||
|
asked.Add(path);
|
||||||
|
handle = IntPtr.Zero;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_wrapper_beside_the_starter_is_noted()
|
||||||
|
{
|
||||||
|
var taken = WithDxgiAndD3d11(path => path == Path.Combine(Game, "dxgi.dll"));
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "dxgi.dll" }, taken.Shadowed);
|
||||||
|
Assert.Contains("dxgi.dll", taken.Note);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void With_nothing_beside_the_starter_there_is_nothing_to_note()
|
||||||
|
{
|
||||||
|
var taken = WithDxgiAndD3d11(_ => false);
|
||||||
|
|
||||||
|
Assert.Empty(taken.Shadowed);
|
||||||
|
Assert.Null(taken.Note);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Only_windows_has_system_libraries_to_take()
|
||||||
|
{
|
||||||
|
var taken = SystemGraphicsLibraries.TakeOnWindows();
|
||||||
|
|
||||||
|
Assert.Equal(OperatingSystem.IsWindows(), taken is not null);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_assembly_with_a_resolver_of_its_own_keeps_it()
|
||||||
|
{
|
||||||
|
var taken = WithDxgiAndD3d11(_ => false);
|
||||||
|
var assembly = typeof(SystemGraphicsLibrariesTests).Assembly;
|
||||||
|
|
||||||
|
Assert.True(taken.ServeTo(assembly));
|
||||||
|
Assert.False(taken.ServeTo(assembly));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -130,6 +130,17 @@ public class TapeLaunchTests
|
|||||||
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
|
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
|
||||||
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), name));
|
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), name));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_train_number_comes_from_a_timetable_named_in_other_case_with_backslashes()
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile(TestInstallation.At("scenery", "Baltyk", "EIE1531.txt"), "[ Rodzaj i numer pociagu | EIE1531 ]\r\n");
|
||||||
|
|
||||||
|
Assert.Equal("EIE1531", new StarterNG.Infrastructure.Sceneries.TimetableLocator(files)
|
||||||
|
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""),
|
||||||
|
@"baltyk\eie1531"));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void A_timetable_that_is_not_there_gives_no_train_number() =>
|
public void A_timetable_that_is_not_there_gives_no_train_number() =>
|
||||||
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
|
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
|
||||||
|
|||||||
22
StarterNG.Tests/TextureFolderTests.cs
Normal file
22
StarterNG.Tests/TextureFolderTests.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
using StarterNG.Domain.Vehicles;
|
||||||
|
using StarterNG.Infrastructure.Vehicles;
|
||||||
|
using StarterNG.Tests.Fakes;
|
||||||
|
|
||||||
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
|
public class TextureFolderTests
|
||||||
|
{
|
||||||
|
private static readonly TestInstallation Installation = new(new InMemoryFileSystem(caseSensitive: true)
|
||||||
|
.WithFile("game/dynamic/PKP/EP09_v1/textures.txt", "")
|
||||||
|
.WithDirectory("game/Other/Folder"));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("pkp/ep09_v1/", "dynamic/PKP/EP09_v1")]
|
||||||
|
[InlineData(@"PKP\EP09_V1", "dynamic/PKP/EP09_v1")]
|
||||||
|
[InlineData("other/folder/", "Other/Folder")]
|
||||||
|
[InlineData("pkp/brak/", "pkp/brak")]
|
||||||
|
public void A_liverys_folder_is_found_as_it_is_named_on_disk(string named, string onDisk) =>
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine("game", onDisk)),
|
||||||
|
Path.GetFullPath(TextureFolder.Of(Installation.Files, Installation.Paths,
|
||||||
|
new VehicleTexture { Directory = named })));
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using StarterNG.Classes;
|
using StarterNG.Classes;
|
||||||
using StarterNG.Domain;
|
using StarterNG.Domain;
|
||||||
|
using StarterNG.Domain.Settings;
|
||||||
using StarterNG.Views;
|
using StarterNG.Views;
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
namespace StarterNG.Tests;
|
||||||
@@ -58,6 +59,63 @@ public class TrainsetDisplayTests
|
|||||||
Assert.False(TrainsetDisplay.ListedIn(picked, showAi: false, drivableOnly: true, current: picked));
|
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]
|
[Theory]
|
||||||
[InlineData(eDriverType.Headdriver, 0)]
|
[InlineData(eDriverType.Headdriver, 0)]
|
||||||
[InlineData(eDriverType.Reardriver, 1)]
|
[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
|
// 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.
|
// 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
|
public class WarehouseEditTests
|
||||||
{
|
{
|
||||||
private const string Text =
|
private const string Text =
|
||||||
@@ -96,6 +98,23 @@ public class WarehouseEditTests
|
|||||||
Assert.Null(Stored("edit-changed"));
|
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]
|
[Fact]
|
||||||
public void Nothing_is_written_with_nothing_open()
|
public void Nothing_is_written_with_nothing_open()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -207,8 +207,12 @@ public partial class App : Avalonia.Application
|
|||||||
if (check.ExecutableMissing())
|
if (check.ExecutableMissing())
|
||||||
await main.OfferExecutablePickAsync();
|
await main.OfferExecutablePickAsync();
|
||||||
|
|
||||||
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
|
// A build without AVX2 in the folder is started instead, and needs no notice.
|
||||||
await main.ShowCpuNoticeAsync();
|
var services = AppServices.Current;
|
||||||
|
if (services.Settings.CpuNotice
|
||||||
|
&& services.Executables.Resolve(services.Settings, out _) is var executable
|
||||||
|
&& services.Executables.WillNotRunHere(executable))
|
||||||
|
await main.ShowCpuNoticeAsync(executable);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ namespace StarterNG.Application.Abstractions;
|
|||||||
|
|
||||||
public interface IFileSystem
|
public interface IFileSystem
|
||||||
{
|
{
|
||||||
|
/// <summary>Whether a name finds its file whatever the case of its letters, as on Windows and macOS.</summary>
|
||||||
|
bool IgnoresCase { get; }
|
||||||
|
|
||||||
bool FileExists(string path);
|
bool FileExists(string path);
|
||||||
|
|
||||||
bool DirectoryExists(string path);
|
bool DirectoryExists(string path);
|
||||||
|
|||||||
@@ -56,19 +56,19 @@ public sealed class AppServices
|
|||||||
var missingAssets = new MissingAssetScanner(files, paths);
|
var missingAssets = new MissingAssetScanner(files, paths);
|
||||||
SceneryTexts = new SceneryTranslations(files, log);
|
SceneryTexts = new SceneryTranslations(files, log);
|
||||||
Timetables = new TimetableLocator(files);
|
Timetables = new TimetableLocator(files);
|
||||||
|
Attachments = new AttachmentLocator(files, paths);
|
||||||
LoadWeights = new LoadWeightsRepository(files, paths, log);
|
LoadWeights = new LoadWeightsRepository(files, paths, log);
|
||||||
Library = new GameLibrary(Vehicles, Sceneries, MiniTextures, Physics, log);
|
Library = new GameLibrary(Vehicles, Sceneries, MiniTextures, Physics, log);
|
||||||
State = new AppState();
|
State = new AppState();
|
||||||
SceneryFiles = new SceneryFileWatch(files, Sceneries, Library, State);
|
SceneryFiles = new SceneryFileWatch(files, Sceneries, Library, State);
|
||||||
|
|
||||||
Executables = new ExecutableLocator(files, paths, environment, log);
|
Executables = new ExecutableLocator(files, paths, environment, log);
|
||||||
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(dlssPlatform: !environment.IsMacOS), Executables);
|
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(), Executables);
|
||||||
MissingVehicleLog = new MissingVehicleLog(SettingsStore.Settings, missingAssets, Library, log);
|
MissingVehicleLog = new MissingVehicleLog(SettingsStore.Settings, missingAssets, Library, log);
|
||||||
Favorites = new FavoriteSceneries(files, log, settingsPaths.FavoritesPath());
|
Favorites = new FavoriteSceneries(files, log, settingsPaths.FavoritesPath());
|
||||||
Tapes = new HaslerTapes(files, paths, log, clock, Timetables, () => State.SimulatorRunning);
|
Tapes = new HaslerTapes(files, paths, log, clock, Timetables, () => State.SimulatorRunning);
|
||||||
Gpus = new LinuxGpus(files, environment);
|
Gpus = new LinuxGpus(files, environment);
|
||||||
GraphicsCards = new GraphicsCards(files, environment, Gpus);
|
GraphicsCards = new GraphicsCards(files, environment, Gpus);
|
||||||
Displays = new Displays(files, environment);
|
|
||||||
StartSimulation = new StartSimulation(State, SettingsStore, Library.Vehicles, Executables,
|
StartSimulation = new StartSimulation(State, SettingsStore, Library.Vehicles, Executables,
|
||||||
files, paths, Processes, random, log, Gpus, environment,
|
files, paths, Processes, random, log, Gpus, environment,
|
||||||
new WineConfigLink(files, environment, settingsPaths, log), Tapes);
|
new WineConfigLink(files, environment, settingsPaths, log), Tapes);
|
||||||
@@ -122,6 +122,8 @@ public sealed class AppServices
|
|||||||
|
|
||||||
public TimetableLocator Timetables { get; }
|
public TimetableLocator Timetables { get; }
|
||||||
|
|
||||||
|
public AttachmentLocator Attachments { get; }
|
||||||
|
|
||||||
public LoadWeightsRepository LoadWeights { get; }
|
public LoadWeightsRepository LoadWeights { get; }
|
||||||
|
|
||||||
public GameLibrary Library { get; }
|
public GameLibrary Library { get; }
|
||||||
@@ -138,8 +140,6 @@ public sealed class AppServices
|
|||||||
|
|
||||||
public GraphicsCards GraphicsCards { get; }
|
public GraphicsCards GraphicsCards { get; }
|
||||||
|
|
||||||
public Displays Displays { get; }
|
|
||||||
|
|
||||||
public SettingsPaths SettingsPaths { get; }
|
public SettingsPaths SettingsPaths { get; }
|
||||||
|
|
||||||
public MissingVehicleLog MissingVehicleLog { get; }
|
public MissingVehicleLog MissingVehicleLog { get; }
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ public sealed class HaslerTapes
|
|||||||
{
|
{
|
||||||
private const int RememberedLaunches = 30;
|
private const int RememberedLaunches = 30;
|
||||||
private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2);
|
private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2);
|
||||||
|
private static readonly TimeSpan TapesAfterBlackBox = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
private readonly IFileSystem _files;
|
private readonly IFileSystem _files;
|
||||||
private readonly IGamePaths _paths;
|
private readonly IGamePaths _paths;
|
||||||
@@ -244,8 +245,9 @@ public sealed class HaslerTapes
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The runs the tapes came from, the running or latest one first. A tape belongs
|
/// 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
|
/// 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
|
/// began between them; one with no launch goes with the black box recording when it
|
||||||
/// time, as a run writes them all at its end.
|
/// was written, or else with those written about the same time, as a run writes its
|
||||||
|
/// logs until it ends.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IReadOnlyList<TapeSession> Sessions()
|
public IReadOnlyList<TapeSession> Sessions()
|
||||||
{
|
{
|
||||||
@@ -278,11 +280,15 @@ public sealed class HaslerTapes
|
|||||||
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
|
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)
|
var loose = tapes.Where(t => tapeLaunch[t] is null)
|
||||||
.Select(t => (Written: t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
.Select(t => (Written: RecordingAt(t.LastWriteUtc, recordings)?.LastWriteUtc ?? t.LastWriteUtc,
|
||||||
.Concat(boxes.Where(b => LaunchOf(b, launches) is null)
|
Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
||||||
.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
.Concat(looseBoxes.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
||||||
.OrderBy(file => file.Written);
|
.OrderBy(file => file.Written);
|
||||||
var run = new List<TapeFile>();
|
var run = new List<TapeFile>();
|
||||||
var runBoxes = new List<BlackBoxRecording>();
|
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) =>
|
private TapeFile ReadTape(string path) =>
|
||||||
new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(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);
|
return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HaslerTape? Load(TapeFile file)
|
// the tape followed as the simulator writes it: what of its file was read, and where it ended
|
||||||
|
private readonly object _followedLock = new();
|
||||||
|
private (string Path, long Read, byte[] Tail, HaslerTape.Reader Reader)? _followed;
|
||||||
|
// what of the end of the read part is kept, to tell the file still has it: one begun anew doesn't
|
||||||
|
private const int FollowedTail = 256;
|
||||||
|
|
||||||
|
public HaslerTape? Load(TapeFile file) => Load(file, follow: false);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The tape of this file no longer followed: what was kept of it is let go. Another file's, followed for another
|
||||||
|
/// window, stays.
|
||||||
|
/// </summary>
|
||||||
|
public void Forget(string path)
|
||||||
{
|
{
|
||||||
try
|
lock (_followedLock)
|
||||||
|
if (_followed?.Path == path)
|
||||||
|
_followed = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the file has between the two: less, up to its end, when it was cut shorter since its length was taken
|
||||||
|
private static byte[] Bytes(Stream stream, long from, long to)
|
||||||
|
{
|
||||||
|
stream.Seek(from, SeekOrigin.Begin);
|
||||||
|
var bytes = new byte[to - from];
|
||||||
|
int read = stream.ReadAtLeast(bytes, bytes.Length, throwOnEndOfStream: false);
|
||||||
|
return read == bytes.Length ? bytes : bytes[..read];
|
||||||
|
}
|
||||||
|
|
||||||
|
// the end of what was read, after the part added to it
|
||||||
|
private static byte[] Tail(byte[] before, byte[] added)
|
||||||
|
{
|
||||||
|
if (added.Length >= FollowedTail)
|
||||||
|
return added[^FollowedTail..];
|
||||||
|
var keptBefore = Math.Min(before.Length, FollowedTail - added.Length);
|
||||||
|
return [.. before[^keptBefore..], .. added];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The tape of the file. Followed, the one read last and grown since: only what was added is read, so a log
|
||||||
|
/// written fast, at a higher time speed, is kept up with; a line not ended yet waits for the next time. Not
|
||||||
|
/// followed, or another file, or one shorter than was read - begun anew - it is read whole, and kept to be
|
||||||
|
/// followed from there.
|
||||||
|
/// </summary>
|
||||||
|
public HaslerTape? Load(TapeFile file, bool follow)
|
||||||
|
{
|
||||||
|
lock (_followedLock)
|
||||||
{
|
{
|
||||||
// Through OpenRead, which does not mind the simulator still writing the file.
|
try
|
||||||
using var stream = _files.OpenRead(file.Path);
|
{
|
||||||
using var reader = new StreamReader(stream, Encoding.ASCII);
|
// Through OpenRead, which does not mind the simulator still writing the file.
|
||||||
return HaslerTape.Parse(reader.ReadToEnd());
|
using var stream = _files.OpenRead(file.Path);
|
||||||
}
|
if (!stream.CanSeek)
|
||||||
catch (Exception ex)
|
{
|
||||||
{
|
_followed = null;
|
||||||
_log.Log($"reading {file.Path}", ex);
|
using var whole = new StreamReader(stream, Encoding.ASCII);
|
||||||
return null;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
45
StarterNG/Application/OneAtATime.cs
Normal file
45
StarterNG/Application/OneAtATime.cs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace StarterNG.Application;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs a piece of work one at a time. Asked again while it runs, it does not start a
|
||||||
|
/// second one alongside, nor forget the request: it runs once more when the first ends,
|
||||||
|
/// however many times it was asked meanwhile. For the UI thread, which calls it alone.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OneAtATime
|
||||||
|
{
|
||||||
|
private readonly Func<Task> _work;
|
||||||
|
private bool _running;
|
||||||
|
private bool _again;
|
||||||
|
|
||||||
|
public OneAtATime(Func<Task> work) => _work = work;
|
||||||
|
|
||||||
|
public bool IsRunning => _running;
|
||||||
|
|
||||||
|
public async Task RunAsync()
|
||||||
|
{
|
||||||
|
if (_running)
|
||||||
|
{
|
||||||
|
_again = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_running = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
do
|
||||||
|
{
|
||||||
|
_again = false;
|
||||||
|
await _work();
|
||||||
|
}
|
||||||
|
while (_again);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_running = false;
|
||||||
|
_again = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -75,6 +76,9 @@ public sealed class SettingsStore
|
|||||||
|
|
||||||
public string SavePath => _savePath;
|
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 RegisterCapture(ISettingsCapture capture) => _capture = capture;
|
||||||
|
|
||||||
public void Load()
|
public void Load()
|
||||||
@@ -92,9 +96,30 @@ public sealed class SettingsStore
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
GraphicsPreset.High.ApplyTo(Settings);
|
GraphicsPreset.High.ApplyTo(Settings);
|
||||||
|
// Nothing of an older starter to bring over: the settings start in the standard mode.
|
||||||
|
Settings.MovedToStandard = true;
|
||||||
Save();
|
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)
|
public void LoadFrom(string path)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -113,6 +138,9 @@ public sealed class SettingsStore
|
|||||||
|
|
||||||
_serializer.Read(Settings, _config);
|
_serializer.Read(Settings, _config);
|
||||||
_synced = Render(Settings);
|
_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();
|
TouchConfigAge();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,8 +185,30 @@ public sealed class SettingsStore
|
|||||||
return;
|
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));
|
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);
|
_synced = Render(Settings);
|
||||||
|
LastSaveMerged = merged;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -185,16 +235,8 @@ public sealed class SettingsStore
|
|||||||
else
|
else
|
||||||
config.Set(change.Key, change.After);
|
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>
|
/// <summary>
|
||||||
/// Takes the settings of another eu07.ini (a backup, a file from another machine)
|
/// 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
|
/// into the current ones, keeping what belongs to this installation: the chosen
|
||||||
@@ -220,9 +262,6 @@ public sealed class SettingsStore
|
|||||||
var gpu = s.Gpu;
|
var gpu = s.Gpu;
|
||||||
string lastScenery = s.LastScenery;
|
string lastScenery = s.LastScenery;
|
||||||
bool maximized = s.WindowMaximized;
|
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;
|
|
||||||
|
|
||||||
_serializer.Read(s, imported);
|
_serializer.Read(s, imported);
|
||||||
|
|
||||||
@@ -231,8 +270,8 @@ public sealed class SettingsStore
|
|||||||
s.Gpu = gpu;
|
s.Gpu = gpu;
|
||||||
s.LastScenery = lastScenery;
|
s.LastScenery = lastScenery;
|
||||||
s.WindowMaximized = maximized;
|
s.WindowMaximized = maximized;
|
||||||
s.CabLampLight = cabLampLight;
|
// an ini of before the tapes of the trains goes the same way as a profile
|
||||||
s.DepthPrepassScene = depthPrepassScene;
|
SettingsSerializer.MoveToTrainTapes(s);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,7 +279,8 @@ public sealed class SettingsStore
|
|||||||
/// Writes the settings as a complete eu07.ini somewhere else - this user's file
|
/// 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.
|
/// with the settings applied - leaving the file itself and its state alone.
|
||||||
/// </summary>
|
/// </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)
|
if (LoadFailed)
|
||||||
{
|
{
|
||||||
@@ -249,7 +289,7 @@ public sealed class SettingsStore
|
|||||||
}
|
}
|
||||||
|
|
||||||
var copy = ConfigFile.Parse(_config.ToText());
|
var copy = ConfigFile.Parse(_config.ToText());
|
||||||
ApplyChanges(copy, Changes(Settings));
|
ApplyChanges(copy, Changes(settings ?? Settings));
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -278,6 +318,86 @@ public sealed class SettingsStore
|
|||||||
return keys;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) && 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>
|
/// <summary>
|
||||||
/// What saving <paramref name="settings"/> would change in the file: the keys
|
/// 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.
|
/// changed since it was read, those it lacks, and the ones no simulator reads.
|
||||||
@@ -290,6 +410,8 @@ public sealed class SettingsStore
|
|||||||
var shown = _capture?.ShownUnlikeSettings ?? new Dictionary<string, ShownValue>();
|
var shown = _capture?.ShownUnlikeSettings ?? new Dictionary<string, ShownValue>();
|
||||||
var changes = new List<IniChange>();
|
var changes = new List<IniChange>();
|
||||||
var listed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
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)
|
foreach (string key in SettingsSerializer.ObsoleteKeys)
|
||||||
Add(key, null);
|
Add(key, null);
|
||||||
@@ -316,6 +438,14 @@ public sealed class SettingsStore
|
|||||||
return Uart.FeaturesStand(_config.GetRaw(key), value);
|
return Uart.FeaturesStand(_config.GetRaw(key), value);
|
||||||
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
|
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
|
||||||
return _config.GetRaw(key) == value;
|
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;
|
||||||
string? synced = _synced.GetValueOrDefault(key);
|
string? synced = _synced.GetValueOrDefault(key);
|
||||||
if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced)
|
if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced)
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ public sealed class StartSimulation
|
|||||||
if (saveSettings)
|
if (saveSettings)
|
||||||
_settings.CaptureAndSave();
|
_settings.CaptureAndSave();
|
||||||
|
|
||||||
if (_settings.Settings.PhysicsLog)
|
if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox || _settings.Settings.PhysicsLogTrains)
|
||||||
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
|
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
|
||||||
|
|
||||||
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)
|
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)
|
||||||
|
|||||||
@@ -58,5 +58,9 @@ public sealed class WarehouseEdit
|
|||||||
|
|
||||||
PresetStore.Save(Name, entry);
|
PresetStore.Save(Name, entry);
|
||||||
_saved = 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.
|
// Its first line, or -1 when the file runs to its end.
|
||||||
private int _end = -1;
|
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)
|
public static ConfigFile Parse(string text)
|
||||||
{
|
{
|
||||||
var cfg = new ConfigFile();
|
var cfg = new ConfigFile();
|
||||||
@@ -37,7 +40,10 @@ public sealed class ConfigFile
|
|||||||
|
|
||||||
private void IndexLine(int line)
|
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;
|
return;
|
||||||
|
|
||||||
if (_end < 0 && key.Equals(EndKey, StringComparison.OrdinalIgnoreCase))
|
if (_end < 0 && key.Equals(EndKey, StringComparison.OrdinalIgnoreCase))
|
||||||
@@ -52,6 +58,7 @@ public sealed class ConfigFile
|
|||||||
{
|
{
|
||||||
_index.Clear();
|
_index.Clear();
|
||||||
_end = -1;
|
_end = -1;
|
||||||
|
_inBlock = false;
|
||||||
for (int line = 0; line < _lines.Count; line++)
|
for (int line = 0; line < _lines.Count; line++)
|
||||||
IndexLine(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)
|
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] == '/' &&
|
if (body[i] == '"')
|
||||||
(i == 0 || char.IsWhiteSpace(body[i - 1])))
|
quoted = !quoted;
|
||||||
|
else if (!quoted && i + 1 < body.Length && body[i] == '/' && body[i + 1] is '/' or '*')
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
return -1;
|
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)
|
private static int IndexOfWhitespace(string s)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < s.Length; i++)
|
for (int i = 0; i < s.Length; i++)
|
||||||
|
|||||||
@@ -19,11 +19,27 @@ public class SettingRow : ContentControl
|
|||||||
AvaloniaProperty.Register<SettingRow, string?>(nameof(ValueText));
|
AvaloniaProperty.Register<SettingRow, string?>(nameof(ValueText));
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Why the simulator to be started would pass this setting over; the row dims
|
/// A setting for those who know what it does: the standard mode leaves it out, as
|
||||||
/// and says so. The input stays usable - the file may serve another build.
|
/// one a player can break the game with or has no need of.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static readonly StyledProperty<string?> IdleNoteProperty =
|
public static readonly StyledProperty<bool> AdvancedProperty =
|
||||||
AvaloniaProperty.Register<SettingRow, string?>(nameof(IdleNote));
|
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
|
public string? Label
|
||||||
{
|
{
|
||||||
@@ -49,12 +65,6 @@ public class SettingRow : ContentControl
|
|||||||
set => SetValue(ValueTextProperty, value);
|
set => SetValue(ValueTextProperty, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string? IdleNote
|
|
||||||
{
|
|
||||||
get => GetValue(IdleNoteProperty);
|
|
||||||
set => SetValue(IdleNoteProperty, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public SettingRow()
|
public SettingRow()
|
||||||
{
|
{
|
||||||
UpdatePseudoClasses();
|
UpdatePseudoClasses();
|
||||||
@@ -68,22 +78,19 @@ public class SettingRow : ContentControl
|
|||||||
change.Property == DescriptionProperty ||
|
change.Property == DescriptionProperty ||
|
||||||
change.Property == ConfigKeyProperty ||
|
change.Property == ConfigKeyProperty ||
|
||||||
change.Property == ValueTextProperty ||
|
change.Property == ValueTextProperty ||
|
||||||
change.Property == IdleNoteProperty ||
|
change.Property == UnknownValueProperty ||
|
||||||
change.Property == ContentProperty)
|
change.Property == ContentProperty)
|
||||||
UpdatePseudoClasses();
|
UpdatePseudoClasses();
|
||||||
|
|
||||||
if (change.Property == IdleNoteProperty)
|
|
||||||
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
|
|
||||||
|
|
||||||
if (change.Property == LabelProperty || change.Property == ContentProperty)
|
if (change.Property == LabelProperty || change.Property == ContentProperty)
|
||||||
ScreenReaderNames.NameInputs(Content, Label);
|
ScreenReaderNames.NameInputs(Content, Label);
|
||||||
|
|
||||||
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
|
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
|
||||||
ScreenReaderNames.TellValue(Content, ValueText);
|
ScreenReaderNames.TellValue(Content, ValueText);
|
||||||
|
|
||||||
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
|
if (change.Property == DescriptionProperty || change.Property == UnknownValueProperty ||
|
||||||
change.Property == ContentProperty)
|
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.
|
// 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);
|
base.OnLoaded(e);
|
||||||
ScreenReaderNames.NameInputs(Content, Label);
|
ScreenReaderNames.NameInputs(Content, Label);
|
||||||
ScreenReaderNames.TellValue(Content, ValueText);
|
ScreenReaderNames.TellValue(Content, ValueText);
|
||||||
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
|
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdatePseudoClasses()
|
private void UpdatePseudoClasses()
|
||||||
@@ -102,6 +109,6 @@ public class SettingRow : ContentControl
|
|||||||
PseudoClasses.Set(":no-key", string.IsNullOrEmpty(ConfigKey));
|
PseudoClasses.Set(":no-key", string.IsNullOrEmpty(ConfigKey));
|
||||||
PseudoClasses.Set(":no-value", string.IsNullOrEmpty(ValueText));
|
PseudoClasses.Set(":no-value", string.IsNullOrEmpty(ValueText));
|
||||||
PseudoClasses.Set(":no-content", Content is null);
|
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
|
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 =
|
public static readonly StyledProperty<object?> ToggleProperty =
|
||||||
AvaloniaProperty.Register<SettingsSection, object?>(nameof(Toggle));
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,16 +61,16 @@ public enum SceneryFaultKind
|
|||||||
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
|
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
|
||||||
MissingInclude,
|
MissingInclude,
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// An include whose file is there only under a name in other letter case: the
|
|
||||||
/// simulator looks for it in lower case, which on Linux misses it. The
|
|
||||||
/// <see cref="SceneryFault.Subject"/> holds the name on disk.
|
|
||||||
/// </summary>
|
|
||||||
IncludeLetterCase,
|
|
||||||
|
|
||||||
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
|
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
|
||||||
IncludeNotClosed,
|
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>
|
/// <summary>A trainset the starter could not read, for a reason none of the above names.</summary>
|
||||||
TrainsetUnreadable,
|
TrainsetUnreadable,
|
||||||
|
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ namespace StarterNG.Domain.Sceneries;
|
|||||||
/// include, so they are not loaded twice.
|
/// include, so they are not loaded twice.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// Only the plain <c>include path end</c> form: an include with parameters needs
|
/// Only the plain <c>include path end</c> form, or <c>include path</c> as the last
|
||||||
/// them put in, and one whose <c>end</c> is not on its line is read by the
|
/// thing in the file, where the simulator runs out of words before it would
|
||||||
/// simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
|
/// 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
|
/// 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.
|
/// marker comments, which is how a trainset is told to belong to it.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
@@ -29,7 +30,8 @@ public static class SceneryIncludes
|
|||||||
private static readonly Regex FirstInit = new(@"\bFirstInit\b", RegexOptions.IgnoreCase);
|
private static readonly Regex FirstInit = new(@"\bFirstInit\b", RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
private static readonly Regex Include = new(
|
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);
|
private static readonly Regex HasTrainset = new(@"^[ \t]*trainset\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,6 @@ using System.Linq;
|
|||||||
|
|
||||||
namespace StarterNG.Domain.Sceneries;
|
namespace StarterNG.Domain.Sceneries;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// What the simulator makes of an include: whether it opens the file - and when
|
|
||||||
/// it does not, the file that is there under a name differing only in letter case.
|
|
||||||
/// </summary>
|
|
||||||
public readonly record struct IncludeLookup(bool Opens, string? OnDisk = null);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Goes through a scenery's text for the parts the starter reads - trainsets,
|
/// Goes through a scenery's text for the parts the starter reads - trainsets,
|
||||||
/// vehicles, includes - finding where each trainset and loose vehicle is, and
|
/// vehicles, includes - finding where each trainset and loose vehicle is, and
|
||||||
@@ -35,17 +29,22 @@ public static class ScenerySyntax
|
|||||||
|
|
||||||
/// <param name="text">The scenery's text, its includes put in place.</param>
|
/// <param name="text">The scenery's text, its includes put in place.</param>
|
||||||
/// <param name="file">The scenery's file name, for faults in its own text.</param>
|
/// <param name="file">The scenery's file name, for faults in its own text.</param>
|
||||||
/// <param name="findInclude">
|
/// <param name="opensInclude">
|
||||||
/// What the simulator makes of an include, named as the include names it; null
|
/// Whether the simulator opens an include, named as the include names it; null
|
||||||
/// leaves includes unchecked.
|
/// leaves includes unchecked.
|
||||||
/// </param>
|
/// </param>
|
||||||
public static Result Scan(string text, string file, Func<string, IncludeLookup>? findInclude = 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);
|
string code = SceneryCode.Mask(text, out int unclosed);
|
||||||
var tokens = SceneryCode.Tokens(code);
|
var tokens = SceneryCode.Tokens(code);
|
||||||
var lines = new SceneryLines(text, file);
|
var lines = new SceneryLines(text, file);
|
||||||
|
|
||||||
var simulator = new Reading(tokens, lines, findInclude, asSimulator: true);
|
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true, loadsVehicle);
|
||||||
simulator.Run();
|
simulator.Run();
|
||||||
var author = new Reading(tokens, lines, null, asSimulator: false);
|
var author = new Reading(tokens, lines, null, asSimulator: false);
|
||||||
author.Run();
|
author.Run();
|
||||||
@@ -116,7 +115,8 @@ public static class ScenerySyntax
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sealed class Reading(
|
private sealed class Reading(
|
||||||
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, IncludeLookup>? findInclude, bool asSimulator)
|
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator,
|
||||||
|
Func<string, string, bool>? loadsVehicle = null)
|
||||||
{
|
{
|
||||||
public readonly List<(int Start, int End, string Name)> Trainsets = new();
|
public readonly List<(int Start, int End, string Name)> Trainsets = new();
|
||||||
public readonly List<(int, int)> Loose = new();
|
public readonly List<(int, int)> Loose = new();
|
||||||
@@ -259,6 +259,9 @@ public static class ScenerySyntax
|
|||||||
return tokens.Count - 1;
|
return tokens.Count - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (complete)
|
||||||
|
Definition(at, name);
|
||||||
|
|
||||||
var (fault, trackless) = CheckFields(at, complete, inTrainset, name);
|
var (fault, trackless) = CheckFields(at, complete, inTrainset, name);
|
||||||
if (fault is null && !closed)
|
if (fault is null && !closed)
|
||||||
fault = SceneryFaultKind.VehicleNotClosed;
|
fault = SceneryFaultKind.VehicleNotClosed;
|
||||||
@@ -273,6 +276,16 @@ public static class ScenerySyntax
|
|||||||
return end;
|
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.
|
// 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)
|
private int ListVehicle(int at, bool complete, bool closed, int meant)
|
||||||
{
|
{
|
||||||
@@ -375,13 +388,8 @@ public static class ScenerySyntax
|
|||||||
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
|
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (findInclude is not null && Plain(name) && findInclude(name) is { Opens: false } lookup)
|
if (opensInclude is not null && Plain(name) && !opensInclude(name))
|
||||||
{
|
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
|
||||||
if (lookup.OnDisk is { } onDisk)
|
|
||||||
Fault(SceneryFaultKind.IncludeLetterCase, token.Index, onDisk, name);
|
|
||||||
else
|
|
||||||
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The simulator takes its parameters up to the word "end", written just so,
|
// The simulator takes its parameters up to the word "end", written just so,
|
||||||
// whatever comes before it.
|
// whatever comes before it.
|
||||||
@@ -389,7 +397,8 @@ public static class ScenerySyntax
|
|||||||
while (end < tokens.Count && tokens[end].Text != "end")
|
while (end < tokens.Count && tokens[end].Text != "end")
|
||||||
end++;
|
end++;
|
||||||
int last = Math.Min(end, tokens.Count - 1);
|
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));
|
Fault(SceneryFaultKind.IncludeNotClosed, token.Index, token: name, swallowed: (at + 1, last));
|
||||||
return last;
|
return last;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Globalization;
|
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
namespace StarterNG.Domain.Settings;
|
namespace StarterNG.Domain.Settings;
|
||||||
@@ -40,176 +39,42 @@ public sealed record GraphicsExtras(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What only Ultra sets, switches and limits with no scale to climb. Not every best is the
|
/// What only Ultra sets, with no scale to climb: the longest shadows, at the bottom of their
|
||||||
/// top of a scale: shadows are longest with the limit at its bottom, the regulator and the
|
/// limit, and the screens drawn. What only the advanced mode shows no level sets.
|
||||||
/// 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.
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ShadowAngleLimit">gfx.shadow.angle.min: how low the sun counts for shadows, so how long they
|
/// <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>
|
/// 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="Screens">python.enabled.</param>
|
||||||
/// <param name="ScreenWindowFps">python.fpslimit: read only by the screens' separate windows
|
public sealed record GraphicsTop(double ShadowAngleLimit, bool Screens)
|
||||||
/// (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)
|
|
||||||
{
|
{
|
||||||
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>
|
/// <summary>The eu07.ini keys these values live in.</summary>
|
||||||
public static readonly IReadOnlyList<string> Keys = RowKeys.Concat(new[]
|
public static readonly IReadOnlyList<string> Keys = new[] { "gfx.shadow.angle.min", "python.enabled" };
|
||||||
{
|
|
||||||
"gfx.shadow.angle.min", "python.enabled", "python.mipmaps", "compresstex", "starter.ignoreirrelevant"
|
|
||||||
}).ToList();
|
|
||||||
|
|
||||||
/// <summary>What they are with nothing set, as <see cref="GraphicsExtras.None"/>.</summary>
|
/// <summary>What they are with nothing set, as <see cref="GraphicsExtras.None"/>.</summary>
|
||||||
public static readonly GraphicsTop None =
|
public static readonly GraphicsTop None = new(0.2, true);
|
||||||
new(0.2, 0, 100, 0, true, true, true, false, true, true, true, true);
|
|
||||||
|
|
||||||
public static GraphicsTop Of(SimulatorSettings s) =>
|
public static GraphicsTop Of(SimulatorSettings s) => new(s.ShadowAngleLimit, s.PythonScreens);
|
||||||
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 void ApplyTo(SimulatorSettings s)
|
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;
|
s.ShadowAngleLimit = ShadowAngleLimit;
|
||||||
Number(TargetFpsKey, TargetFps);
|
|
||||||
Number(ScreenWindowFpsKey, ScreenWindowFps);
|
|
||||||
Number(TextureReleaseKey, TextureRelease);
|
|
||||||
s.PythonScreens = Screens;
|
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>
|
/// <summary>
|
||||||
/// A level of detail set in one go: what weighs on the graphics card. Every scale climbs in
|
/// 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
|
/// 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
|
/// levels. A level sets only what the standard mode shows, and only to what its sliders offer
|
||||||
/// matter of taste - motion blur, chromatic aberration - stay as they are, except at the
|
/// (<see cref="SliderRanges"/>, the old starter's ranges): never past the old starter. The screen
|
||||||
/// two ends of the scale, which have <see cref="Extras"/>.
|
/// (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>
|
/// </summary>
|
||||||
/// <param name="NameKey">Its name's translation key.</param>
|
/// <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="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="AntiAliasing">multisampling.</param>
|
||||||
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second.</param>
|
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second, one of the old starter's steps.</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="DrawRangeFactor">gfx.drawrange.factor.max: how far the regulator may stretch the draw range.</param>
|
/// <param name="DrawRangeFactor">gfx.drawrange.factor.max: how far the regulator may stretch the draw range.</param>
|
||||||
public sealed record GraphicsPreset(
|
public sealed record GraphicsPreset(
|
||||||
string NameKey,
|
string NameKey,
|
||||||
@@ -228,122 +93,73 @@ public sealed record GraphicsPreset(
|
|||||||
double ReflectionsRate,
|
double ReflectionsRate,
|
||||||
bool ExtraEffects,
|
bool ExtraEffects,
|
||||||
int SplineFidelity,
|
int SplineFidelity,
|
||||||
double DrawRange,
|
|
||||||
double DistanceFactor,
|
|
||||||
int BufferScale,
|
|
||||||
double SleeperDistance,
|
|
||||||
double DrawRangeFactor,
|
double DrawRangeFactor,
|
||||||
double ReflectedInstances,
|
|
||||||
double ReflectedVehicles,
|
|
||||||
int CabShadowsRange,
|
int CabShadowsRange,
|
||||||
GraphicsNewRenderer NewRenderer,
|
|
||||||
GraphicsExtras? Extras = null,
|
GraphicsExtras? Extras = null,
|
||||||
GraphicsTop? Top = 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>
|
/// <summary>The eu07.ini keys a level sets.</summary>
|
||||||
public static readonly IReadOnlyList<string> Keys = new[]
|
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.smoke.fidelity", "shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff",
|
||||||
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.extraeffects",
|
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.extraeffects",
|
||||||
"splinefidelity", DrawRangeKey, DistanceFactorKey, "starter.bufferscale", "gfx.buffer.percent", SleeperKey,
|
"splinefidelity", "gfx.drawrange.factor.max", "gfx.shadows.cab.range"
|
||||||
"gfx.drawrange.factor.max", ReflectedInstancesKey, ReflectedVehiclesKey, "gfx.shadows.cab.range"
|
};
|
||||||
}.Concat(GraphicsNewRenderer.Keys).ToList();
|
|
||||||
|
|
||||||
/// <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(
|
public static readonly GraphicsPreset Minimal = new(
|
||||||
"PresetMinimal", TextureSize: 512, CabTextureSize: 512, Anisotropy: 1, AntiAliasing: AntiAliasingMode.Off,
|
"PresetMinimal", TextureSize: 512, CabTextureSize: 512, Anisotropy: 1, AntiAliasing: AntiAliasingMode.Off,
|
||||||
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 512, ShadowRange: 75, ShadowRank: 1,
|
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 1024, ShadowRange: 75, ShadowRank: 1,
|
||||||
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1 / 300.0, ExtraEffects: false,
|
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: false,
|
||||||
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.6, BufferScale: 70,
|
SplineFidelity: 1, DrawRangeFactor: 1, CabShadowsRange: 0,
|
||||||
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),
|
|
||||||
Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800));
|
Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800));
|
||||||
|
|
||||||
public static readonly GraphicsPreset Low = new(
|
public static readonly GraphicsPreset Low = new(
|
||||||
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 2, AntiAliasing: AntiAliasingMode.Off,
|
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 2, AntiAliasing: AntiAliasingMode.Off,
|
||||||
DynamicLights: 3, SmokeFidelity: 1, Shadows: true, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 2,
|
DynamicLights: 3, SmokeFidelity: 1, Shadows: true, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 2,
|
||||||
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1 / 60.0, ExtraEffects: true,
|
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: true,
|
||||||
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.7, BufferScale: 80,
|
SplineFidelity: 2, DrawRangeFactor: 1, CabShadowsRange: 0);
|
||||||
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));
|
|
||||||
|
|
||||||
public static readonly GraphicsPreset Medium = new(
|
public static readonly GraphicsPreset Medium = new(
|
||||||
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 4, AntiAliasing: AntiAliasingMode.Msaa2,
|
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 4, AntiAliasing: AntiAliasingMode.Msaa2,
|
||||||
DynamicLights: 5, SmokeFidelity: 2, Shadows: true, ShadowMap: 1024, ShadowRange: 175, ShadowRank: 2,
|
DynamicLights: 5, SmokeFidelity: 2, Shadows: true, ShadowMap: 1024, ShadowRange: 175, ShadowRank: 2,
|
||||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1 / 30.0, ExtraEffects: true,
|
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1, ExtraEffects: true,
|
||||||
SplineFidelity: 2, DrawRange: 2250, DistanceFactor: 0.85, BufferScale: 90,
|
SplineFidelity: 2, DrawRangeFactor: 2, CabShadowsRange: 20);
|
||||||
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));
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Where a player with no settings of their own starts. The simulator's own values (Globals.h),
|
/// 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
|
/// 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>
|
/// </summary>
|
||||||
public static readonly GraphicsPreset High = new(
|
public static readonly GraphicsPreset High = new(
|
||||||
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa4,
|
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa4,
|
||||||
DynamicLights: 7, SmokeFidelity: 2, Shadows: true, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
|
DynamicLights: 7, SmokeFidelity: 2, Shadows: true, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
|
||||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 0.1, ExtraEffects: true,
|
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 3, ExtraEffects: true,
|
||||||
SplineFidelity: 2, DrawRange: 2500, DistanceFactor: 1, BufferScale: 100,
|
SplineFidelity: 2, DrawRangeFactor: 3, CabShadowsRange: 30);
|
||||||
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));
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Every value at the top of what the screen offers. Not the best picture throughout: a map
|
/// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.
|
||||||
/// of 8192 stretches the cascades fourfold, so shadows reach 2400 m but are coarser up close
|
/// Filtering stays as High's, so the textures tell this level from Ultra.
|
||||||
/// than at <see cref="VeryHigh"/>.
|
/// </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>
|
/// </summary>
|
||||||
public static readonly GraphicsPreset Ultra = new(
|
public static readonly GraphicsPreset Ultra = new(
|
||||||
"PresetUltra", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
|
"PresetUltra", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
|
||||||
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 600, ShadowRank: 3,
|
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 400, ShadowRank: 3,
|
||||||
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 60, ExtraEffects: true,
|
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 60, ExtraEffects: true,
|
||||||
SplineFidelity: 4, DrawRange: 10000, DistanceFactor: 3, BufferScale: 200,
|
SplineFidelity: 4, DrawRangeFactor: 3, CabShadowsRange: 100,
|
||||||
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),
|
|
||||||
Extras: new GraphicsExtras(MotionBlur: true, ChromaticAberration: true, Smoke: true, PythonUpdateMs: 200),
|
Extras: new GraphicsExtras(MotionBlur: true, ChromaticAberration: true, Smoke: true, PythonUpdateMs: 200),
|
||||||
Top: new GraphicsTop(ShadowAngleLimit: 0.2, TargetFps: 0, ScreenWindowFps: 200, TextureRelease: 0,
|
Top: new GraphicsTop(ShadowAngleLimit: 0.2, Screens: true));
|
||||||
Screens: true, ScreenMipmaps: true, CompressTextures: false, SkipDecor: false,
|
|
||||||
Sky: true, Cab: true, AirCouplers: true, SmoothTraction: true));
|
|
||||||
|
|
||||||
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra };
|
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra };
|
||||||
|
|
||||||
@@ -352,8 +168,7 @@ public sealed record GraphicsPreset(
|
|||||||
s.MaxTextureSize = TextureSize;
|
s.MaxTextureSize = TextureSize;
|
||||||
s.MaxCabTextureSize = CabTextureSize;
|
s.MaxCabTextureSize = CabTextureSize;
|
||||||
s.TextureFiltering = Anisotropy;
|
s.TextureFiltering = Anisotropy;
|
||||||
if (!GraphicsRules.IsDlss(s.AntiAliasing))
|
s.AntiAliasing = AntiAliasing;
|
||||||
s.AntiAliasing = AntiAliasing;
|
|
||||||
s.CabShadowsRange = CabShadowsRange;
|
s.CabShadowsRange = CabShadowsRange;
|
||||||
s.DynamicLights = DynamicLights;
|
s.DynamicLights = DynamicLights;
|
||||||
s.SmokeFidelity = SmokeFidelity;
|
s.SmokeFidelity = SmokeFidelity;
|
||||||
@@ -366,14 +181,7 @@ public sealed record GraphicsPreset(
|
|||||||
s.ReflectionsFramerate = ReflectionsRate;
|
s.ReflectionsFramerate = ReflectionsRate;
|
||||||
s.ExtraEffects = ExtraEffects;
|
s.ExtraEffects = ExtraEffects;
|
||||||
s.SplineFidelity = SplineFidelity;
|
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.DrawRangeFactor = DrawRangeFactor;
|
||||||
s.Extra[ReflectedInstancesKey] = ReflectedInstances.ToString(CultureInfo.InvariantCulture);
|
|
||||||
s.Extra[ReflectedVehiclesKey] = ReflectedVehicles.ToString(CultureInfo.InvariantCulture);
|
|
||||||
NewRenderer.ApplyTo(s);
|
|
||||||
Extras?.ApplyTo(s);
|
Extras?.ApplyTo(s);
|
||||||
Top?.ApplyTo(s);
|
Top?.ApplyTo(s);
|
||||||
}
|
}
|
||||||
@@ -381,20 +189,14 @@ public sealed record GraphicsPreset(
|
|||||||
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
|
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
|
||||||
public bool Matches(SimulatorSettings s) =>
|
public bool Matches(SimulatorSettings s) =>
|
||||||
s.MaxTextureSize == TextureSize && s.MaxCabTextureSize == CabTextureSize &&
|
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.DynamicLights == DynamicLights && s.SmokeFidelity == SmokeFidelity &&
|
||||||
s.RenderShadows == Shadows && s.ShadowMapResolution == ShadowMap &&
|
s.RenderShadows == Shadows && s.ShadowMapResolution == ShadowMap &&
|
||||||
s.ShadowProjectionRange == ShadowRange && s.ShadowRankCutoff == ShadowRank &&
|
s.ShadowProjectionRange == ShadowRange && s.ShadowRankCutoff == ShadowRank &&
|
||||||
s.EnvMap == EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
|
s.EnvMap == EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
|
||||||
Near(s.ReflectionsFramerate, ReflectionsRate) && s.ExtraEffects == ExtraEffects &&
|
Near(s.ReflectionsFramerate, ReflectionsRate) && s.ExtraEffects == ExtraEffects &&
|
||||||
s.SplineFidelity == SplineFidelity && Near(NumberOf(s, DrawRangeKey), DrawRange) &&
|
s.SplineFidelity == SplineFidelity && Near(s.DrawRangeFactor, DrawRangeFactor) &&
|
||||||
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.CabShadowsRange == CabShadowsRange &&
|
s.CabShadowsRange == CabShadowsRange &&
|
||||||
GraphicsNewRenderer.Of(s) == NewRenderer.For(s) &&
|
|
||||||
(Extras is null || GraphicsExtras.Of(s) == Extras) &&
|
(Extras is null || GraphicsExtras.Of(s) == Extras) &&
|
||||||
(Top is null || GraphicsTop.Of(s) == Top);
|
(Top is null || GraphicsTop.Of(s) == Top);
|
||||||
|
|
||||||
@@ -407,31 +209,23 @@ public sealed record GraphicsPreset(
|
|||||||
return key.ParseNumber(key.RawIn(s));
|
return key.ParseNumber(key.RawIn(s));
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool ToggleOf(SimulatorSettings s, string name) =>
|
// As the file rounds it.
|
||||||
SimulatorKey.ParseToggle(SimulatorKeys.Named(name).RawIn(s));
|
|
||||||
|
|
||||||
// As the file rounds it: 1/300 comes back as 0.003333.
|
|
||||||
private static bool Near(double value, double target) =>
|
private static bool Near(double value, double target) =>
|
||||||
Math.Abs(value - target) <= Math.Abs(target) * 2e-4 + 1e-9;
|
Math.Abs(value - target) <= Math.Abs(target) * 2e-4 + 1e-9;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A part of the picture with a level of its own, as its section on the screen has it. The rest
|
/// 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>
|
/// </summary>
|
||||||
/// <param name="Keys">The eu07.ini keys it sets.</param>
|
/// <param name="Keys">The eu07.ini keys it sets.</param>
|
||||||
public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
|
public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
|
||||||
{
|
{
|
||||||
public static readonly GraphicsGroup DrawRange = new(new[]
|
public static readonly GraphicsGroup DrawRange = new(new[] { "splinefidelity", "gfx.drawrange.factor.max" });
|
||||||
{
|
|
||||||
GraphicsPreset.DrawRangeKey, GraphicsPreset.DistanceFactorKey, "splinefidelity",
|
|
||||||
GraphicsPreset.SleeperKey, "gfx.drawrange.factor.max"
|
|
||||||
});
|
|
||||||
|
|
||||||
public static readonly GraphicsGroup Textures = new(new[]
|
public static readonly GraphicsGroup Textures = new(new[]
|
||||||
{
|
{
|
||||||
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering",
|
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering"
|
||||||
"compresstex", GraphicsTop.TextureReleaseKey
|
|
||||||
});
|
});
|
||||||
|
|
||||||
public static readonly GraphicsGroup Shadows = new(new[]
|
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"
|
"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[]
|
public static readonly GraphicsGroup Reflections = new(new[]
|
||||||
{
|
{
|
||||||
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate",
|
"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"
|
|
||||||
});
|
});
|
||||||
|
|
||||||
public static readonly IReadOnlyList<GraphicsGroup> All = new[]
|
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>
|
/// <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>
|
/// <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>
|
/// <summary>
|
||||||
/// Remembers what was there before an end of the scale, which comes back with any level
|
/// 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);
|
comingTop?.ApplyTo(settings);
|
||||||
preset.ApplyTo(settings);
|
preset.ApplyTo(settings);
|
||||||
|
|
||||||
var rows = new List<string>(GraphicsPreset.RowKeys);
|
|
||||||
var chosen = new List<string>(GraphicsPreset.Keys);
|
var chosen = new List<string>(GraphicsPreset.Keys);
|
||||||
if (preset.Extras is not null || coming is not null)
|
if (preset.Extras is not null || coming is not null)
|
||||||
chosen.AddRange(GraphicsExtras.Keys);
|
chosen.AddRange(GraphicsExtras.Keys);
|
||||||
if (preset.Top is not null || comingTop is not null)
|
if (preset.Top is not null || comingTop is not null)
|
||||||
{
|
|
||||||
chosen.AddRange(GraphicsTop.Keys);
|
chosen.AddRange(GraphicsTop.Keys);
|
||||||
rows.AddRange(GraphicsTop.RowKeys);
|
return new PresetApplied(chosen);
|
||||||
}
|
|
||||||
return new PresetApplied(rows, chosen);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,115 +1,32 @@
|
|||||||
namespace StarterNG.Domain.Settings;
|
namespace StarterNG.Domain.Settings;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What the simulator does with combinations of graphics settings, mirrored here so
|
/// What the simulator does with graphics values, mirrored here so the starter writes
|
||||||
/// the starter only offers what takes effect and writes eu07.ini the way the
|
/// eu07.ini the way the simulator will run it (utilities/Globals.cpp), and how far the
|
||||||
/// simulator will run it (utilities/Globals.cpp, rendering/vulkan14, rendering/opengl46).
|
/// starter lets them go: no further than the old starter did (MaSzyna-EU07/Starter).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class GraphicsRules
|
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);
|
/// <summary>The projection range of shadowtune: the old starter's list ended at 400.</summary>
|
||||||
|
public const int MaxShadowRange = 400;
|
||||||
public static bool IsVulkan(SimulatorSettings s) => s.Backend == GraphicsBackend.Vulkan;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// DLSS is the Vulkan renderer's only (the OpenGL one takes TAA instead), and the
|
/// The frame buffer, in percent of the window. The old starter's choice of buffer
|
||||||
/// DLSS SDK has no macOS libraries.
|
/// (gfx.framebuffer.fidelity) is not read by the simulator, so it always had the window's size.
|
||||||
/// </summary>
|
/// </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) =>
|
/// <summary>Brings the values within the ranges the simulator clamps them to, and the starter's caps.</summary>
|
||||||
DlssAllowed(s, dlssPlatform) && IsDlss(s.AntiAliasing);
|
public static void Normalize(SimulatorSettings s)
|
||||||
|
|
||||||
/// <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)
|
|
||||||
{
|
{
|
||||||
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.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.ShadowMapResolution = PowerOfTwo(s.ShadowMapResolution, 512, 8192);
|
||||||
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, 200);
|
s.ShadowProjectionRange = s.ShadowProjectionRange > MaxShadowRange ? MaxShadowRange : s.ShadowProjectionRange;
|
||||||
s.LightShadows = Clamp(s.LightShadows, 0, 3);
|
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, MaxBufferScale);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
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
|
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 General = "general";
|
||||||
public const string Graphics = "graphics";
|
public const string Graphics = "graphics";
|
||||||
public const string Sound = "sound";
|
public const string Sound = "sound";
|
||||||
@@ -94,13 +100,12 @@ public static class SimulatorKeys
|
|||||||
Toggle("loadinglog", false, General, "IniSectionInterface"),
|
Toggle("loadinglog", false, General, "IniSectionInterface"),
|
||||||
Toggle("captureonstart", true, General, "IniSectionInterface"),
|
Toggle("captureonstart", true, General, "IniSectionInterface"),
|
||||||
Toggle("mousecontrol", true, General, "IniSectionInterface"),
|
Toggle("mousecontrol", true, General, "IniSectionInterface"),
|
||||||
Text("fullscreenmonitor", General, "IniSectionInterface"),
|
|
||||||
Text("screenshotsdir", General, "IniSectionInterface"),
|
Text("screenshotsdir", General, "IniSectionInterface"),
|
||||||
|
|
||||||
Number("basedrawrange", 2500, Graphics, "IniSectionRanges", 500, 10000, 250, " m"),
|
Number("basedrawrange", 2500, Graphics, "IniSectionRanges", 500, 10000, 250, " m"),
|
||||||
Number("heightbase", 1, Graphics, "IniSectionRanges", 0.5, 3, 0.05, "×"),
|
Number("heightbase", 1, Graphics, "IniSectionRanges", 0.5, 3, 0.05, "×"),
|
||||||
Number("targetfps", 0, Graphics, "IniSectionRanges", 0, 240, 5, " FPS", zeroIsOff: true),
|
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_instances", 750, Graphics, "IniSectionRanges", 0, 3000, 50, " m"),
|
||||||
Number("gfx.reflections.range_vehicles", 250, Graphics, "IniSectionRanges", 0, 2000, 50, " m"),
|
Number("gfx.reflections.range_vehicles", 250, Graphics, "IniSectionRanges", 0, 2000, 50, " m"),
|
||||||
Toggle("gfx.textures.streaming", false, Graphics, "IniSectionRanges"),
|
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 }
|
public enum ExeProblem { None, NotFound, NotExecutable, WrongPlatform, NotAProgram }
|
||||||
|
|
||||||
// gfxrenderer: the OpenGL renderer ("full", read by every build) or the Vulkan 1.4 one.
|
// multisampling: 0 off, then 2, 4 and 8 samples.
|
||||||
public enum GraphicsBackend { OpenGL = 0, Vulkan = 1 }
|
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8 }
|
||||||
|
|
||||||
// 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 }
|
|
||||||
|
|
||||||
public sealed class SimulatorSettings
|
public sealed class SimulatorSettings
|
||||||
{
|
{
|
||||||
@@ -34,7 +31,8 @@ public sealed class SimulatorSettings
|
|||||||
public bool InvertMouseHorizontal;
|
public bool InvertMouseHorizontal;
|
||||||
public bool InvertMouseVertical;
|
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 FeedbackMode = 1;
|
||||||
public int FeedbackPort = 888;
|
public int FeedbackPort = 888;
|
||||||
public bool UartEnabled;
|
public bool UartEnabled;
|
||||||
@@ -55,8 +53,6 @@ public sealed class SimulatorSettings
|
|||||||
public bool LogMissingVehicleFiles;
|
public bool LogMissingVehicleFiles;
|
||||||
|
|
||||||
public int RenderEngine;
|
public int RenderEngine;
|
||||||
public GraphicsBackend Backend => RenderEngine == VulkanEngine ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL;
|
|
||||||
public string VulkanDevice = "";
|
|
||||||
public int Width = 1280;
|
public int Width = 1280;
|
||||||
public int Height = 720;
|
public int Height = 720;
|
||||||
public int BufferScalePercent = 100;
|
public int BufferScalePercent = 100;
|
||||||
@@ -64,9 +60,6 @@ public sealed class SimulatorSettings
|
|||||||
public int MaxCabTextureSize = 4096;
|
public int MaxCabTextureSize = 4096;
|
||||||
public double TextureFiltering = 8;
|
public double TextureFiltering = 8;
|
||||||
public AntiAliasingMode AntiAliasing = AntiAliasingMode.Msaa4;
|
public AntiAliasingMode AntiAliasing = AntiAliasingMode.Msaa4;
|
||||||
public string DlssPreset = "default";
|
|
||||||
public int FrameGeneration = 1;
|
|
||||||
public int Reflex;
|
|
||||||
public int DynamicLights = 7;
|
public int DynamicLights = 7;
|
||||||
public double DrawRangeFactor = 3.0;
|
public double DrawRangeFactor = 3.0;
|
||||||
public bool VSync;
|
public bool VSync;
|
||||||
@@ -77,37 +70,8 @@ public sealed class SimulatorSettings
|
|||||||
public bool ExtraEffects = true;
|
public bool ExtraEffects = true;
|
||||||
public bool EnvMap = true;
|
public bool EnvMap = true;
|
||||||
public bool RenderShadows = 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.
|
// Only the legacy renderer, or only Windows builds, read these.
|
||||||
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.
|
|
||||||
public bool UseVbo = true;
|
public bool UseVbo = true;
|
||||||
public bool RenderAngleVulkan;
|
public bool RenderAngleVulkan;
|
||||||
public bool UseGLES;
|
public bool UseGLES;
|
||||||
@@ -127,12 +91,28 @@ public sealed class SimulatorSettings
|
|||||||
public double FpsLimit = 30;
|
public double FpsLimit = 30;
|
||||||
public double ShadowAngleLimit = 0.2;
|
public double ShadowAngleLimit = 0.2;
|
||||||
public bool FullscreenWindowed;
|
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 int SplineFidelity = 1;
|
||||||
public bool FullPhysics = true;
|
public bool FullPhysics = true;
|
||||||
public bool EnableTraction = true;
|
public bool EnableTraction = true;
|
||||||
public bool LiveTraction = true;
|
public bool LiveTraction = true;
|
||||||
public bool PhysicsLog;
|
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 DebugLog = true;
|
||||||
public bool MultipleLogs;
|
public bool MultipleLogs;
|
||||||
public bool DisplaySimulation = true;
|
public bool DisplaySimulation = true;
|
||||||
@@ -166,6 +146,18 @@ public sealed class SimulatorSettings
|
|||||||
public bool LargeThumbnails;
|
public bool LargeThumbnails;
|
||||||
public bool AutoExpandSceneryTree;
|
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>
|
/// <summary>Warn at start when the processor cannot run the official simulator builds.</summary>
|
||||||
public bool CpuNotice = true;
|
public bool CpuNotice = true;
|
||||||
|
|
||||||
@@ -198,25 +190,26 @@ public sealed class SimulatorSettings
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The gfxrenderer words the simulator tells apart (application.cpp): every
|
/// The gfxrenderer words the starter offers. "default" is the full renderer, the one to use
|
||||||
/// other word - the "simpleshader" and "off" older starters offered among them -
|
/// wherever it runs; the other two draw with the legacy one. The experimental renderer is
|
||||||
/// gets the legacy renderer. A simulator with the OpenGL 4.6 and Vulkan 1.4
|
/// not offered: the simulator a player has is built without it.
|
||||||
/// renderers runs everything but "vulkan" as the first, and "vulkan" too when
|
|
||||||
/// it was built without it or the card cannot run it.
|
|
||||||
/// </summary>
|
/// </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>
|
/// <summary>
|
||||||
public const int VulkanEngine = 4;
|
/// 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>
|
/// <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
|
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,
|
"simple" => 2,
|
||||||
"experimental" => 3,
|
_ => 0
|
||||||
"vulkan" or "vulkan14" => 4,
|
|
||||||
_ => 1
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -242,7 +235,12 @@ public sealed class SimulatorSettings
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal double MouseScaleXMagnitude { get; set; } = 2;
|
internal double MouseScaleXMagnitude { get; set; } = 2;
|
||||||
|
|
||||||
internal double MouseScaleYMagnitude { get; set; } = 0.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>
|
/// <summary>The numbers of shadowtune the simulator skips, kept as the file has them.</summary>
|
||||||
internal string[] ShadowTuneUnused { get; set; } = { "250", "300" };
|
internal string[] ShadowTuneUnused { get; set; } = { "250", "300" };
|
||||||
|
|||||||
34
StarterNG/Domain/Settings/SliderRanges.cs
Normal file
34
StarterNG/Domain/Settings/SliderRanges.cs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
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>The cursor's speed: its fastest was a mousescale of 3.2.</summary>
|
||||||
|
public const int MaxCursorSensitivity = 3;
|
||||||
|
|
||||||
|
/// <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
|
public sealed class HaslerTape
|
||||||
{
|
{
|
||||||
// Columns counted from the start; the security flag is counted from the end, past
|
// 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 TimeColumn = 0;
|
||||||
private const int VelocityColumn = 1;
|
private const int VelocityColumn = 1;
|
||||||
private const int BrakePressColumn = 8;
|
private const int BrakePressColumn = 8;
|
||||||
private const int PipePressColumn = 9;
|
private const int PipePressColumn = 9;
|
||||||
private const int MotorCurrentColumn = 10;
|
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;
|
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;
|
Samples = samples;
|
||||||
foreach (var s in samples)
|
foreach (var s in samples)
|
||||||
MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh);
|
MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh);
|
||||||
|
GapSeconds = gap;
|
||||||
for (int i = 1; i < samples.Count; i++)
|
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; }
|
public IReadOnlyList<TapeSample> Samples { get; }
|
||||||
@@ -60,50 +79,137 @@ public sealed class HaslerTape
|
|||||||
|
|
||||||
public double MaxSpeedKmh { get; }
|
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 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>
|
/// <summary>Mean speed while moving.</summary>
|
||||||
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
|
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
|
||||||
|
|
||||||
/// <summary>Mean speed over the whole recording, stops included - the commercial speed.</summary>
|
/// <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)
|
public static HaslerTape Parse(string text)
|
||||||
{
|
{
|
||||||
var samples = new List<TapeSample>();
|
var reader = new Reader();
|
||||||
double distance = 0;
|
reader.Feed(text);
|
||||||
TapeSample? previous = null;
|
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);
|
var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (columns.Length < MinimumColumns
|
if (columns.Length == 0)
|
||||||
|| !Number(columns[TimeColumn], out double time)
|
return;
|
||||||
|| !Number(columns[VelocityColumn], out double velocity))
|
if (!Number(columns[TimeColumn], out double time))
|
||||||
continue; // the header, or a line cut short by a simulator still writing
|
{
|
||||||
|
// 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[BrakePressColumn], out double brake);
|
||||||
Number(columns[PipePressColumn], out double pipe);
|
Number(columns[PipePressColumn], out double pipe);
|
||||||
Number(columns[MotorCurrentColumn], out double current);
|
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 (samples.Count > 0 && time < samples[^1].Time)
|
||||||
if (previous is { } p)
|
|
||||||
{
|
{
|
||||||
if (time < p.Time)
|
WentBack = true;
|
||||||
continue;
|
return;
|
||||||
distance += (p.SpeedKmh + speed) / 2 / 3.6 * (time - p.Time);
|
|
||||||
}
|
}
|
||||||
|
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>
|
/// <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)
|
VehicleTexture? current)
|
||||||
{
|
{
|
||||||
var result = new List<VehicleTexture>();
|
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) &&
|
if (!string.IsNullOrEmpty(owner) &&
|
||||||
!string.Equals(owner, t.Meta?.Operator, StringComparison.OrdinalIgnoreCase))
|
!string.Equals(owner, t.Meta?.Operator, StringComparison.OrdinalIgnoreCase))
|
||||||
continue;
|
continue;
|
||||||
@@ -236,6 +221,49 @@ public sealed class TexRandomizer
|
|||||||
return result;
|
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)
|
public static int? ParseRevisionYear(string? revision)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(revision)) return null;
|
if (string.IsNullOrWhiteSpace(revision)) return null;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ using StarterNG.Classes;
|
|||||||
using StarterNG.Domain.Sceneries;
|
using StarterNG.Domain.Sceneries;
|
||||||
using StarterNG.Domain.Vehicles;
|
using StarterNG.Domain.Vehicles;
|
||||||
using StarterNG.Application;
|
using StarterNG.Application;
|
||||||
|
using StarterNG.Domain.Settings;
|
||||||
|
|
||||||
namespace StarterNG.Domain;
|
namespace StarterNG.Domain;
|
||||||
|
|
||||||
@@ -30,10 +31,27 @@ public static class TrainsetDisplay
|
|||||||
!string.IsNullOrEmpty(trainset.Description) &&
|
!string.IsNullOrEmpty(trainset.Description) &&
|
||||||
trainset.Description.TrimStart().StartsWith("-", StringComparison.Ordinal);
|
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) =>
|
public static bool ListedIn(Trainset trainset, bool showAi, bool drivableOnly, Trainset? current) =>
|
||||||
(showAi || !IsAi(trainset)) && (!drivableOnly || ListedAsDrivable(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>
|
/// <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) =>
|
public static string ListLabel(Trainset trainset) =>
|
||||||
CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? "");
|
CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? "");
|
||||||
|
|||||||
55
StarterNG/Infrastructure/Adapters/FolderChanges.cs
Normal file
55
StarterNG/Infrastructure/Adapters/FolderChanges.cs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure.Adapters;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tells when anything in a folder or below it is written, made, removed or renamed, as
|
||||||
|
/// the system reports it. Only a hint that it is time to look: a save comes as several
|
||||||
|
/// reports, and on a network drive, under Wine or past the system's limit of watches it
|
||||||
|
/// may come as none, so whoever listens still looks now and then on its own.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class FolderChanges : IDisposable
|
||||||
|
{
|
||||||
|
private readonly FileSystemWatcher? _watcher;
|
||||||
|
|
||||||
|
/// <summary>Something changed, or the reports were lost and anything may have: on a thread of the pool.</summary>
|
||||||
|
public event Action? Changed;
|
||||||
|
|
||||||
|
/// <param name="folder">Watched with everything below it; a missing one is not watched.</param>
|
||||||
|
public FolderChanges(string folder)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(folder))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var watcher = new FileSystemWatcher(folder)
|
||||||
|
{
|
||||||
|
IncludeSubdirectories = true,
|
||||||
|
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
|
||||||
|
| NotifyFilters.LastWrite | NotifyFilters.Size,
|
||||||
|
// Unpacking an update changes hundreds of files at once.
|
||||||
|
InternalBufferSize = 64 * 1024
|
||||||
|
};
|
||||||
|
watcher.Changed += (_, _) => Changed?.Invoke();
|
||||||
|
watcher.Created += (_, _) => Changed?.Invoke();
|
||||||
|
watcher.Deleted += (_, _) => Changed?.Invoke();
|
||||||
|
watcher.Renamed += (_, _) => Changed?.Invoke();
|
||||||
|
// Too many at once for the buffer: which ones is lost, so all are looked at.
|
||||||
|
watcher.Error += (_, _) => Changed?.Invoke();
|
||||||
|
watcher.EnableRaisingEvents = true;
|
||||||
|
_watcher = watcher;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException
|
||||||
|
or PlatformNotSupportedException)
|
||||||
|
{
|
||||||
|
// Out of watches on Linux, or a drive that gives none: the slow look alone stays.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the system reports changes here at all.</summary>
|
||||||
|
public bool Watching => _watcher is not null;
|
||||||
|
|
||||||
|
public void Dispose() => _watcher?.Dispose();
|
||||||
|
}
|
||||||
@@ -10,6 +10,9 @@ public sealed class PhysicalFileSystem : IFileSystem
|
|||||||
{
|
{
|
||||||
public const string TempSuffix = ".starter.tmp";
|
public const string TempSuffix = ".starter.tmp";
|
||||||
|
|
||||||
|
// Their disks as they come; a Linux one tells case apart.
|
||||||
|
public bool IgnoresCase { get; } = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
|
||||||
|
|
||||||
public bool FileExists(string path) => File.Exists(path);
|
public bool FileExists(string path) => File.Exists(path);
|
||||||
|
|
||||||
public bool DirectoryExists(string path) => Directory.Exists(path);
|
public bool DirectoryExists(string path) => Directory.Exists(path);
|
||||||
@@ -88,8 +91,18 @@ public sealed class PhysicalFileSystem : IFileSystem
|
|||||||
public void CopyFile(string sourcePath, string destinationPath, bool overwrite) =>
|
public void CopyFile(string sourcePath, string destinationPath, bool overwrite) =>
|
||||||
File.Copy(sourcePath, destinationPath, overwrite);
|
File.Copy(sourcePath, destinationPath, overwrite);
|
||||||
|
|
||||||
|
// The pattern matches names in any letter case, as on Windows: the game's data,
|
||||||
|
// made there, has X.SCN as well as x.scn.
|
||||||
public IReadOnlyList<string> GetFiles(string path, string searchPattern = "*") =>
|
public IReadOnlyList<string> GetFiles(string path, string searchPattern = "*") =>
|
||||||
Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty<string>();
|
Directory.Exists(path)
|
||||||
|
? Directory.GetFiles(path, searchPattern, new EnumerationOptions
|
||||||
|
{
|
||||||
|
IgnoreInaccessible = false,
|
||||||
|
AttributesToSkip = 0,
|
||||||
|
MatchType = MatchType.Win32,
|
||||||
|
MatchCasing = MatchCasing.CaseInsensitive
|
||||||
|
})
|
||||||
|
: Array.Empty<string>();
|
||||||
|
|
||||||
// A folder it may not enter costs what is in it, not the whole listing.
|
// A folder it may not enter costs what is in it, not the whole listing.
|
||||||
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
|
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
|
||||||
@@ -99,7 +112,8 @@ public sealed class PhysicalFileSystem : IFileSystem
|
|||||||
RecurseSubdirectories = true,
|
RecurseSubdirectories = true,
|
||||||
IgnoreInaccessible = true,
|
IgnoreInaccessible = true,
|
||||||
AttributesToSkip = 0,
|
AttributesToSkip = 0,
|
||||||
MatchType = MatchType.Win32
|
MatchType = MatchType.Win32,
|
||||||
|
MatchCasing = MatchCasing.CaseInsensitive
|
||||||
})
|
})
|
||||||
: Array.Empty<string>();
|
: Array.Empty<string>();
|
||||||
|
|
||||||
|
|||||||
132
StarterNG/Infrastructure/CaseInsensitivePaths.cs
Normal file
132
StarterNG/Infrastructure/CaseInsensitivePaths.cs
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using StarterNG.Application.Abstractions;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Finds a file or folder of the game's data by a name whose letters may stand in
|
||||||
|
/// another case than on disk, as Windows, Wine and the simulator find it, and gives
|
||||||
|
/// the name as the disk has it. The data is made on Windows: its names and the
|
||||||
|
/// names written in it seldom agree letter for letter, which on Linux matters.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class CaseInsensitivePaths
|
||||||
|
{
|
||||||
|
private readonly IFileSystem _files;
|
||||||
|
private readonly Func<(string Folder, bool Files), ILookup<string, string>> _list;
|
||||||
|
|
||||||
|
/// <summary>Each folder's files and folders by name, listed once until <see cref="Forget"/>; null lists every time.</summary>
|
||||||
|
private readonly ConcurrentDictionary<(string Folder, bool Files), ILookup<string, string>>? _listings;
|
||||||
|
|
||||||
|
/// <param name="keepListings">
|
||||||
|
/// Lists each folder once, for many names looked up in data that stays as it is
|
||||||
|
/// meanwhile, until <see cref="Forget"/>.
|
||||||
|
/// </param>
|
||||||
|
public CaseInsensitivePaths(IFileSystem files, bool keepListings = false)
|
||||||
|
{
|
||||||
|
_files = files;
|
||||||
|
_list = List;
|
||||||
|
if (keepListings)
|
||||||
|
_listings = new ConcurrentDictionary<(string, bool), ILookup<string, string>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lets the next lookups list the folders again.</summary>
|
||||||
|
public void Forget() => _listings?.Clear();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file named so under <paramref name="folder"/> as it is named on disk, relative
|
||||||
|
/// to the folder with forward slashes; null when nothing there answers to it. A name
|
||||||
|
/// written with its letters as on disk wins over one differing only in their case;
|
||||||
|
/// a disk that does not tell case apart gives it back as written.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name">
|
||||||
|
/// A name under the folder, with either slash, joined to it as the simulator joins
|
||||||
|
/// it: a slash ahead of it counts for nothing.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="directory">Looks for a folder instead of a file.</param>
|
||||||
|
public string? Resolve(string folder, string name, bool directory = false)
|
||||||
|
{
|
||||||
|
string[] parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (parts.Length == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string exact = string.Join('/', parts);
|
||||||
|
string whole = Path.Combine(folder, exact);
|
||||||
|
if (directory ? _files.DirectoryExists(whole) : _files.FileExists(whole))
|
||||||
|
return exact;
|
||||||
|
// Where case does not matter, missed as written is missed in any case.
|
||||||
|
if (_files.IgnoresCase)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var found = new string[parts.Length];
|
||||||
|
return Walk(folder, parts, 0, directory, found) ? string.Join('/', found) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The full path of the file named so, its letters as on disk; null when there is
|
||||||
|
/// none. A name given in full is looked up from its own root, any other under
|
||||||
|
/// <paramref name="folder"/> as <see cref="Resolve"/> does.
|
||||||
|
/// </summary>
|
||||||
|
public string? Find(string folder, string name, bool directory = false)
|
||||||
|
{
|
||||||
|
if (Path.IsPathFullyQualified(name))
|
||||||
|
{
|
||||||
|
folder = Path.GetPathRoot(name)!;
|
||||||
|
name = name[folder.Length..];
|
||||||
|
}
|
||||||
|
|
||||||
|
return Resolve(folder, name, directory) is { } found
|
||||||
|
? Path.Combine(folder, found.Replace('/', Path.DirectorySeparatorChar))
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Finds the parts from <paramref name="at"/> on under <paramref name="current"/>. Of
|
||||||
|
/// folders named alike in other case - two copies of the data on Linux - each is
|
||||||
|
/// tried, the one written as on disk first.
|
||||||
|
/// </summary>
|
||||||
|
private bool Walk(string current, string[] parts, int at, bool directory, string[] found)
|
||||||
|
{
|
||||||
|
if (at == parts.Length)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
string part = parts[at];
|
||||||
|
if (part is "." or "..")
|
||||||
|
{
|
||||||
|
found[at] = part;
|
||||||
|
return Walk(Path.Combine(current, part), parts, at + 1, directory, found);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool last = at == parts.Length - 1;
|
||||||
|
var matches = Listing(current, files: last && !directory)[part]
|
||||||
|
.OrderBy(entry => string.Equals(Path.GetFileName(entry), part, StringComparison.Ordinal) ? 0 : 1);
|
||||||
|
foreach (string match in matches)
|
||||||
|
{
|
||||||
|
found[at] = Path.GetFileName(match);
|
||||||
|
if (Walk(match, parts, at + 1, directory, found))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ILookup<string, string> Listing(string folder, bool files) =>
|
||||||
|
_listings is null ? List((folder, files)) : _listings.GetOrAdd((folder, files), _list);
|
||||||
|
|
||||||
|
// A folder that cannot be listed holds nothing to be found.
|
||||||
|
private ILookup<string, string> List((string Folder, bool Files) key)
|
||||||
|
{
|
||||||
|
var entries = Array.Empty<string>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_files.DirectoryExists(key.Folder))
|
||||||
|
entries = (key.Files ? _files.GetFiles(key.Folder) : _files.GetDirectories(key.Folder)).ToArray();
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
// Nothing listed, nothing found.
|
||||||
|
}
|
||||||
|
return entries.ToLookup(entry => Path.GetFileName(entry), StringComparer.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
96
StarterNG/Infrastructure/FolderLooks.cs
Normal file
96
StarterNG/Infrastructure/FolderLooks.cs
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using StarterNG.Application;
|
||||||
|
using StarterNG.Infrastructure.Adapters;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks at a folder's files for a window, one look at a time on the UI thread: when the system
|
||||||
|
/// reports a change, once the burst a save makes has passed; when the window comes back to the
|
||||||
|
/// front; when asked; and now and then anyway, for the drives and systems where the reports do
|
||||||
|
/// not come - often where none come at all. From the window's opening to its closing.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class FolderLooks
|
||||||
|
{
|
||||||
|
/// <summary>How long the reports have to stop for: a save comes as several of them.</summary>
|
||||||
|
public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400);
|
||||||
|
|
||||||
|
/// <summary>How often it looks anyway where the system reports the changes.</summary>
|
||||||
|
public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
/// <summary>How often it looks where the system reports nothing.</summary>
|
||||||
|
public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2);
|
||||||
|
|
||||||
|
private readonly Func<string> _folder;
|
||||||
|
private readonly OneAtATime _look;
|
||||||
|
private readonly TimeProvider _time;
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private bool _closed;
|
||||||
|
private ITimer? _quiet;
|
||||||
|
private ITimer? _often;
|
||||||
|
private FolderChanges? _changes;
|
||||||
|
|
||||||
|
/// <param name="window">Looked for from its opening to its closing.</param>
|
||||||
|
/// <param name="folder">The folder, as it is when the window opens.</param>
|
||||||
|
/// <param name="look">The look itself; it knows when it is no time to look.</param>
|
||||||
|
/// <param name="time">The clock of the timers, the system's when not given.</param>
|
||||||
|
public FolderLooks(Window window, Func<string> folder, Func<Task> look, TimeProvider? time = null)
|
||||||
|
{
|
||||||
|
_folder = folder;
|
||||||
|
_look = new OneAtATime(look);
|
||||||
|
_time = time ?? TimeProvider.System;
|
||||||
|
window.Opened += (_, _) => Watch();
|
||||||
|
window.Activated += async (_, _) => await LookAsync();
|
||||||
|
window.Closed += (_, _) => Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the system reports the folder's changes; not before the window opens.</summary>
|
||||||
|
public bool Watching => _changes?.Watching == true;
|
||||||
|
|
||||||
|
/// <summary>Looks now, or once more after the look that runs.</summary>
|
||||||
|
public Task LookAsync() => _look.RunAsync();
|
||||||
|
|
||||||
|
private void Watch()
|
||||||
|
{
|
||||||
|
var changes = new FolderChanges(_folder());
|
||||||
|
var often = changes.Watching ? Watched : Unwatched;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_changes = changes;
|
||||||
|
_quiet = _time.CreateTimer(_ => LookLater(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||||
|
_often = _time.CreateTimer(_ => LookLater(), null, often, often);
|
||||||
|
}
|
||||||
|
changes.Changed += PutOff;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each report puts the look off again, so a save of many files is one look after it. The
|
||||||
|
// reports come on threads of the pool, and may come still as the window closes.
|
||||||
|
private void PutOff()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (!_closed)
|
||||||
|
_quiet?.Change(Quiet, Timeout.InfiniteTimeSpan);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The timers tick on threads of the pool; the look belongs on the UI thread.
|
||||||
|
private void LookLater() => Dispatcher.UIThread.Post(() => _ = LookAsync());
|
||||||
|
|
||||||
|
private void Close()
|
||||||
|
{
|
||||||
|
FolderChanges? changes;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_closed = true;
|
||||||
|
_quiet?.Dispose();
|
||||||
|
_often?.Dispose();
|
||||||
|
changes = _changes;
|
||||||
|
}
|
||||||
|
changes?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,16 +5,21 @@ using System.Runtime.InteropServices;
|
|||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Media.Imaging;
|
using Avalonia.Media.Imaging;
|
||||||
using Avalonia.Platform;
|
using Avalonia.Platform;
|
||||||
|
using StarterNG.Application.Abstractions;
|
||||||
|
using StarterNG.Infrastructure.Adapters;
|
||||||
|
|
||||||
namespace StarterNG.Infrastructure;
|
namespace StarterNG.Infrastructure;
|
||||||
|
|
||||||
public static class LoadingScreen
|
public static class LoadingScreen
|
||||||
{
|
{
|
||||||
|
private static readonly string[] Extensions = { ".bmp", ".jpg", ".jpeg", ".png" };
|
||||||
|
|
||||||
public static void Prepare(string? logoKey, string? sceneryName = null)
|
public static void Prepare(string? logoKey, string? sceneryName = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string? src = ResolveSource(logoKey) ?? ResolveSource(sceneryName) ?? PickRandom();
|
string? src = FindSource(new PhysicalFileSystem(), Directory.GetCurrentDirectory(), logoKey, sceneryName,
|
||||||
|
Random.Shared);
|
||||||
if (src is null) return;
|
if (src is null) return;
|
||||||
|
|
||||||
string destDir = Path.Combine(Directory.GetCurrentDirectory(), "textures");
|
string destDir = Path.Combine(Directory.GetCurrentDirectory(), "textures");
|
||||||
@@ -35,32 +40,36 @@ public static class LoadingScreen
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string? ResolveSource(string? key)
|
/// <summary>
|
||||||
|
/// The picture of textures/logo under <paramref name="root"/> to show: the trainset's,
|
||||||
|
/// else the scenery's, else one of logo*.* at random; its name and extension in any
|
||||||
|
/// letter case. Null when there is none.
|
||||||
|
/// </summary>
|
||||||
|
public static string? FindSource(IFileSystem files, string root, string? logoKey, string? sceneryName,
|
||||||
|
Random random)
|
||||||
|
{
|
||||||
|
var names = new CaseInsensitivePaths(files);
|
||||||
|
if (names.Find(root, "textures/logo", directory: true) is not { } dir)
|
||||||
|
return null;
|
||||||
|
return Named(names, dir, logoKey) ?? Named(names, dir, sceneryName) ?? PickRandom(files, dir, random);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Named(CaseInsensitivePaths names, string dir, string? key)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(key)) return null;
|
if (string.IsNullOrWhiteSpace(key)) return null;
|
||||||
key = Path.GetFileNameWithoutExtension(key.Trim());
|
key = Path.GetFileNameWithoutExtension(key.Trim());
|
||||||
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
|
if (key.Length == 0) return null;
|
||||||
foreach (string ext in new[] { ".bmp", ".jpg", ".jpeg", ".png" })
|
return Extensions.Select(ext => names.Find(dir, key + ext)).FirstOrDefault(path => path is not null);
|
||||||
{
|
|
||||||
string path = Path.Combine(dir, key + ext);
|
|
||||||
if (File.Exists(path)) return path;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string? PickRandom()
|
private static string? PickRandom(IFileSystem files, string dir, Random random)
|
||||||
{
|
{
|
||||||
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
|
var logos = files.GetFiles(dir, "logo*.*")
|
||||||
if (!Directory.Exists(dir)) return null;
|
.Where(f => Extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
|
||||||
var files = Directory.GetFiles(dir, "logo*.*")
|
.Order(StringComparer.Ordinal)
|
||||||
.Where(f =>
|
|
||||||
{
|
|
||||||
string e = Path.GetExtension(f).ToLowerInvariant();
|
|
||||||
return e is ".bmp" or ".jpg" or ".jpeg" or ".png";
|
|
||||||
})
|
|
||||||
.ToArray();
|
.ToArray();
|
||||||
if (files.Length == 0) return null;
|
if (logos.Length == 0) return null;
|
||||||
return files[Random.Shared.Next(files.Length)];
|
return logos[random.Next(logos.Length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void WriteBmp(string sourcePath, string destPath)
|
private static void WriteBmp(string sourcePath, string destPath)
|
||||||
|
|||||||
195
StarterNG/Infrastructure/Monitors.cs
Normal file
195
StarterNG/Infrastructure/Monitors.cs
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
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 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 ──
|
||||||
|
|
||||||
|
private static readonly Regex Output = new(
|
||||||
|
@"^(\S+) connected (primary )?(\d+)x(\d+)\+(\d+)\+(\d+)", RegexOptions.CultureInvariant);
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
|
||||||
|
private static IReadOnlyList<DisplayMonitor> FromXrandr()
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
24
StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs
Normal file
24
StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
using StarterNG.Application.Abstractions;
|
||||||
|
using StarterNG.Domain.Sceneries;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure.Sceneries;
|
||||||
|
|
||||||
|
/// <summary>Where the file a scenery attaches (<c>//$f</c>) is on disk.</summary>
|
||||||
|
public sealed class AttachmentLocator
|
||||||
|
{
|
||||||
|
private readonly IGamePaths _paths;
|
||||||
|
private readonly CaseInsensitivePaths _names;
|
||||||
|
|
||||||
|
public AttachmentLocator(IFileSystem files, IGamePaths paths)
|
||||||
|
{
|
||||||
|
_paths = paths;
|
||||||
|
_names = new CaseInsensitivePaths(files);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The attachment's file, named from the game's folder or in full, with its letters
|
||||||
|
/// as on disk; null when it is not there.
|
||||||
|
/// </summary>
|
||||||
|
public string? Resolve(SceneryAttachment attachment) =>
|
||||||
|
string.IsNullOrWhiteSpace(attachment.FilePath) ? null : _names.Find(_paths.Root, attachment.FilePath.Trim());
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using StarterNG.Application.Abstractions;
|
using StarterNG.Application.Abstractions;
|
||||||
using StarterNG.Domain.Sceneries;
|
using StarterNG.Domain.Sceneries;
|
||||||
|
|
||||||
@@ -8,11 +9,13 @@ namespace StarterNG.Infrastructure.Sceneries;
|
|||||||
public sealed class SceneryImageLocator
|
public sealed class SceneryImageLocator
|
||||||
{
|
{
|
||||||
private readonly IFileSystem _files;
|
private readonly IFileSystem _files;
|
||||||
|
private readonly CaseInsensitivePaths _names;
|
||||||
private readonly Dictionary<string, string?> _cache = new();
|
private readonly Dictionary<string, string?> _cache = new();
|
||||||
|
|
||||||
public SceneryImageLocator(IFileSystem files)
|
public SceneryImageLocator(IFileSystem files)
|
||||||
{
|
{
|
||||||
_files = files;
|
_files = files;
|
||||||
|
_names = new CaseInsensitivePaths(files);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string? Resolve(Scenery scenery)
|
public string? Resolve(Scenery scenery)
|
||||||
@@ -34,22 +37,23 @@ public sealed class SceneryImageLocator
|
|||||||
return null;
|
return null;
|
||||||
|
|
||||||
string name = scenery.ImageName.Replace('\\', '/').Trim();
|
string name = scenery.ImageName.Replace('\\', '/').Trim();
|
||||||
|
if (Path.IsPathFullyQualified(name))
|
||||||
|
return _names.Find("", name);
|
||||||
|
if (_files.FileExists(name))
|
||||||
|
return name;
|
||||||
|
|
||||||
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
|
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
|
||||||
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
|
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
|
||||||
|
|
||||||
string[] candidates =
|
(string Folder, string Name)[] candidates =
|
||||||
{
|
{
|
||||||
name,
|
(root, name),
|
||||||
Path.Combine(root, name),
|
(sceneryDir, name),
|
||||||
Path.Combine(sceneryDir, name),
|
(sceneryDir, "images/" + name),
|
||||||
Path.Combine(sceneryDir, "images", name),
|
(root, "scenery/images/" + name)
|
||||||
Path.Combine(root, "scenery", "images", name)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
foreach (string candidate in candidates)
|
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
|
||||||
if (_files.FileExists(candidate))
|
.FirstOrDefault(found => found is not null);
|
||||||
return candidate;
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,11 +20,16 @@ public sealed class SceneryParser
|
|||||||
_random = random;
|
_random = random;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <param name="findInclude">
|
/// <param name="opensInclude">
|
||||||
/// What the simulator makes of an include, as the include names it; null leaves
|
/// Whether the simulator opens an include, as the include names it; null leaves
|
||||||
/// includes unchecked.
|
/// includes unchecked.
|
||||||
/// </param>
|
/// </param>
|
||||||
public Scenery Parse(string path, string content, Func<string, IncludeLookup>? findInclude = 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;
|
string original = content;
|
||||||
|
|
||||||
@@ -38,7 +43,7 @@ public sealed class SceneryParser
|
|||||||
|
|
||||||
// Read from the text with its optional includes blanked, which keeps every
|
// 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.
|
// place where it was, so a fault's line is the line in the file.
|
||||||
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), findInclude);
|
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude, loadsVehicle);
|
||||||
var faults = syntax.Faults.ToList();
|
var faults = syntax.Faults.ToList();
|
||||||
var inlined = SceneryIncludes.Ranges(content);
|
var inlined = SceneryIncludes.Ranges(content);
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
private readonly SceneryParser _parser;
|
private readonly SceneryParser _parser;
|
||||||
|
|
||||||
/// <summary>The scenery folders' files and folders, listed once per load of them all.</summary>
|
/// <summary>The scenery folders' files and folders, listed once per load of them all.</summary>
|
||||||
private readonly ConcurrentDictionary<(string, bool), IReadOnlyList<string>> _listings = new();
|
private readonly CaseInsensitivePaths _names;
|
||||||
|
|
||||||
public SceneryRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, SceneryParser parser)
|
public SceneryRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, SceneryParser parser)
|
||||||
{
|
{
|
||||||
@@ -31,11 +31,12 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
_paths = paths;
|
_paths = paths;
|
||||||
_log = log;
|
_log = log;
|
||||||
_parser = parser;
|
_parser = parser;
|
||||||
|
_names = new CaseInsensitivePaths(files, keepListings: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public IReadOnlyList<Scenery> LoadAll(IProgress<SceneryLoadProgress>? progress = null)
|
public IReadOnlyList<Scenery> LoadAll(IProgress<SceneryLoadProgress>? progress = null)
|
||||||
{
|
{
|
||||||
_listings.Clear();
|
_names.Forget();
|
||||||
var files = SceneryFiles().ToList();
|
var files = SceneryFiles().ToList();
|
||||||
var loaded = new ConcurrentBag<Scenery>();
|
var loaded = new ConcurrentBag<Scenery>();
|
||||||
int total = Math.Max(1, files.Count);
|
int total = Math.Max(1, files.Count);
|
||||||
@@ -58,7 +59,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
|
|
||||||
public Scenery? Load(string path)
|
public Scenery? Load(string path)
|
||||||
{
|
{
|
||||||
_listings.Clear();
|
_names.Forget();
|
||||||
return LoadOne(path);
|
return LoadOne(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,10 +80,8 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
// With its own .sbt the scenery's terrain comes from it, and the simulator
|
// With its own .sbt the scenery's terrain comes from it, and the simulator
|
||||||
// passes its terrain includes over without opening them.
|
// passes its terrain includes over without opening them.
|
||||||
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
|
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
|
||||||
IncludeLookup FindInclude(string name) =>
|
bool OpensInclude(string name) =>
|
||||||
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"))
|
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));
|
||||||
? new IncludeLookup(true)
|
|
||||||
: new IncludeLookup(false, ResolveInclude(name));
|
|
||||||
|
|
||||||
(string File, string Text)? ReadInclude(string name)
|
(string File, string Text)? ReadInclude(string name)
|
||||||
{
|
{
|
||||||
@@ -99,7 +98,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
|
|
||||||
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
|
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
|
||||||
string text = SceneryIncludes.Inline(own, ReadInclude);
|
string text = SceneryIncludes.Inline(own, ReadInclude);
|
||||||
var scenery = _parser.Parse(path, text, FindInclude);
|
var scenery = _parser.Parse(path, text, OpensInclude, LoadsVehicle);
|
||||||
scenery.HasCompanionTimetable = binaryTerrain;
|
scenery.HasCompanionTimetable = binaryTerrain;
|
||||||
scenery.Sources = sources;
|
scenery.Sources = sources;
|
||||||
scenery.TextEncoding = ownEncoding;
|
scenery.TextEncoding = ownEncoding;
|
||||||
@@ -114,11 +113,20 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Whether the simulator opens a file of the scenery folder named so: by the
|
/// Whether the simulator opens a file of the scenery folder named so: whatever the
|
||||||
/// name in lower case, which on Linux has to be how it is named on disk.
|
/// case of its letters, on Linux too. A shade more lenient than eu07 there, which
|
||||||
|
/// folds only the letters A to Z and of two folders named alike takes the first.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private bool Opens(string name) =>
|
private bool Opens(string name) => ResolveInclude(name) is not null;
|
||||||
_files.FileExists(Path.Combine(_paths.Scenery, SimulatorNames.Lower(name.Replace('\\', '/'))));
|
|
||||||
|
/// <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>
|
/// <summary>
|
||||||
/// An include's file as it is named on disk, from the scenery folder, whatever
|
/// An include's file as it is named on disk, from the scenery folder, whatever
|
||||||
@@ -126,44 +134,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
/// copy written for a start carries in place of the include, so they come along
|
/// copy written for a start carries in place of the include, so they come along
|
||||||
/// on Linux too.
|
/// on Linux too.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private string? ResolveInclude(string name)
|
private string? ResolveInclude(string name) => _names.Resolve(_paths.Scenery, name);
|
||||||
{
|
|
||||||
string relative = name.Replace('\\', '/');
|
|
||||||
if (_files.FileExists(Path.Combine(_paths.Scenery, relative)))
|
|
||||||
return relative;
|
|
||||||
|
|
||||||
string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
string directory = _paths.Scenery;
|
|
||||||
var found = new List<string>();
|
|
||||||
for (int i = 0; i < parts.Length; i++)
|
|
||||||
{
|
|
||||||
if (parts[i] is "." or "..")
|
|
||||||
{
|
|
||||||
directory = Path.Combine(directory, parts[i]);
|
|
||||||
found.Add(parts[i]);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool last = i == parts.Length - 1;
|
|
||||||
string? match = Listing(directory, last)
|
|
||||||
.FirstOrDefault(entry => string.Equals(Path.GetFileName(entry), parts[i],
|
|
||||||
StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (match is null)
|
|
||||||
return null;
|
|
||||||
directory = match;
|
|
||||||
found.Add(Path.GetFileName(match));
|
|
||||||
}
|
|
||||||
|
|
||||||
return string.Join('/', found);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IReadOnlyList<string> Listing(string directory, bool files) =>
|
|
||||||
_listings.GetOrAdd((directory, files), key =>
|
|
||||||
{
|
|
||||||
if (!_files.DirectoryExists(key.Item1))
|
|
||||||
return Array.Empty<string>();
|
|
||||||
return key.Item2 ? _files.GetFiles(key.Item1) : _files.GetDirectories(key.Item1);
|
|
||||||
});
|
|
||||||
|
|
||||||
private IEnumerable<string> SceneryFiles() =>
|
private IEnumerable<string> SceneryFiles() =>
|
||||||
_files.GetFiles(_paths.Scenery, "*.scn")
|
_files.GetFiles(_paths.Scenery, "*.scn")
|
||||||
|
|||||||
@@ -14,12 +14,14 @@ public sealed class SceneryTranslations : ISceneryTranslations
|
|||||||
private const string BaseLanguage = "en";
|
private const string BaseLanguage = "en";
|
||||||
|
|
||||||
private readonly IFileSystem _files;
|
private readonly IFileSystem _files;
|
||||||
|
private readonly CaseInsensitivePaths _names;
|
||||||
private readonly IDiagnosticsLog _log;
|
private readonly IDiagnosticsLog _log;
|
||||||
private readonly Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
public SceneryTranslations(IFileSystem files, IDiagnosticsLog log)
|
public SceneryTranslations(IFileSystem files, IDiagnosticsLog log)
|
||||||
{
|
{
|
||||||
_files = files;
|
_files = files;
|
||||||
|
_names = new CaseInsensitivePaths(files);
|
||||||
_log = log;
|
_log = log;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,12 +31,11 @@ public sealed class SceneryTranslations : ISceneryTranslations
|
|||||||
|
|
||||||
string sceneryDir = Path.GetDirectoryName(Path.GetFullPath(scenery.Path)) ?? "scenery";
|
string sceneryDir = Path.GetDirectoryName(Path.GetFullPath(scenery.Path)) ?? "scenery";
|
||||||
string id = Path.GetFileNameWithoutExtension(scenery.Path);
|
string id = Path.GetFileNameWithoutExtension(scenery.Path);
|
||||||
string i18nDir = Path.Combine(sceneryDir, "i18n");
|
|
||||||
string language = NormalizeLanguage(langCode);
|
string language = NormalizeLanguage(langCode);
|
||||||
|
|
||||||
TryLoad(Path.Combine(i18nDir, $"{id}_{BaseLanguage}.json"));
|
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{BaseLanguage}.json"));
|
||||||
if (!string.Equals(language, BaseLanguage, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(language, BaseLanguage, StringComparison.OrdinalIgnoreCase))
|
||||||
TryLoad(Path.Combine(i18nDir, $"{id}_{language}.json"));
|
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{language}.json"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public string Translate(string? text)
|
public string Translate(string? text)
|
||||||
@@ -50,9 +51,9 @@ public sealed class SceneryTranslations : ISceneryTranslations
|
|||||||
return _map.TryGetValue(key, out string? translated) ? translated : text;
|
return _map.TryGetValue(key, out string? translated) ? translated : text;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void TryLoad(string path)
|
private void TryLoad(string? path)
|
||||||
{
|
{
|
||||||
if (!_files.FileExists(path))
|
if (path is null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -17,10 +17,12 @@ public sealed class TimetableLocator
|
|||||||
RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
private readonly IFileSystem _files;
|
private readonly IFileSystem _files;
|
||||||
|
private readonly CaseInsensitivePaths _names;
|
||||||
|
|
||||||
public TimetableLocator(IFileSystem files)
|
public TimetableLocator(IFileSystem files)
|
||||||
{
|
{
|
||||||
_files = files;
|
_files = files;
|
||||||
|
_names = new CaseInsensitivePaths(files);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string? Resolve(Scenery scenery, string? name)
|
public string? Resolve(Scenery scenery, string? name)
|
||||||
@@ -30,17 +32,19 @@ public sealed class TimetableLocator
|
|||||||
|
|
||||||
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
|
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
|
||||||
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
|
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
|
||||||
|
name = name.Replace('\\', '/');
|
||||||
|
|
||||||
string[] candidates =
|
(string Folder, string Name)[] candidates =
|
||||||
{
|
{
|
||||||
Path.Combine(root, "timetables", name + ".txt"),
|
(root, "timetables/" + name + ".txt"),
|
||||||
Path.Combine(sceneryDir, name + ".txt"),
|
(sceneryDir, name + ".txt"),
|
||||||
Path.Combine(root, "scenario", name + ".txt"),
|
(root, "scenario/" + name + ".txt"),
|
||||||
Path.Combine(root, "timetables", name),
|
(root, "timetables/" + name),
|
||||||
Path.Combine(sceneryDir, name)
|
(sceneryDir, name)
|
||||||
};
|
};
|
||||||
|
|
||||||
return candidates.FirstOrDefault(_files.FileExists);
|
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
|
||||||
|
.FirstOrDefault(found => found is not null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The number the timetable gives its train; null with no timetable or no such heading in it.</summary>
|
/// <summary>The number the timetable gives its train; null with no timetable or no such heading in it.</summary>
|
||||||
|
|||||||
@@ -22,15 +22,37 @@ public sealed class ExecutableLocator
|
|||||||
private string? _wine;
|
private string? _wine;
|
||||||
private bool _wineLookedUp;
|
private bool _wineLookedUp;
|
||||||
private string? _missingPickLogged;
|
private string? _missingPickLogged;
|
||||||
|
private readonly bool _lacksAvx2;
|
||||||
|
|
||||||
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log)
|
/// <param name="lacksAvx2">Whether this processor runs no AVX2; asked of it when left out.</param>
|
||||||
|
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log,
|
||||||
|
bool? lacksAvx2 = null)
|
||||||
{
|
{
|
||||||
_files = files;
|
_files = files;
|
||||||
_paths = paths;
|
_paths = paths;
|
||||||
_environment = environment;
|
_environment = environment;
|
||||||
_log = log;
|
_log = log;
|
||||||
|
_lacksAvx2 = lacksAvx2 ?? CpuFeatures.LacksAvx2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The end of the name of a simulator built without AVX2, last before any extension:
|
||||||
|
/// eu07-x64_2026-11-15_abc1234_noavx2.exe, eu07_noavx2. It runs on any x86-64 processor.
|
||||||
|
/// </summary>
|
||||||
|
public const string NoAvx2Suffix = "_noavx2";
|
||||||
|
|
||||||
|
public static bool IsNoAvx2(string path) =>
|
||||||
|
Path.GetFileNameWithoutExtension(path).EndsWith(NoAvx2Suffix, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether <paramref name="executable"/> stops at its first instruction here: a build
|
||||||
|
/// with AVX2 on a processor without it. Such a processor is told so before a start.
|
||||||
|
/// </summary>
|
||||||
|
public bool WillNotRunHere(string executable) => _lacksAvx2 && !IsNoAvx2(executable);
|
||||||
|
|
||||||
|
/// <summary>The newest build without AVX2 in the installation, or null where there is none.</summary>
|
||||||
|
public string? NewestNoAvx2() => ListCandidates().FirstOrDefault(IsNoAvx2);
|
||||||
|
|
||||||
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
|
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -71,7 +93,8 @@ public sealed class ExecutableLocator
|
|||||||
{
|
{
|
||||||
var candidates = _files.GetFiles(_paths.Root, "eu07*")
|
var candidates = _files.GetFiles(_paths.Root, "eu07*")
|
||||||
.Where(IsCandidate)
|
.Where(IsCandidate)
|
||||||
.OrderBy(path => IsExeOnLinux(path) ? 1 : 0)
|
.OrderBy(Rank)
|
||||||
|
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
|
||||||
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
|
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
|
||||||
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
||||||
.ThenBy(path => Path.GetFileName(path).Length);
|
.ThenBy(path => Path.GetFileName(path).Length);
|
||||||
@@ -101,6 +124,18 @@ public sealed class ExecutableLocator
|
|||||||
return CanonicalName;
|
return CanonicalName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The order of the search. Without AVX2 a build without it comes first, the newest of
|
||||||
|
/// them, even through Wine: the others stop at once. With AVX2 one is the last resort,
|
||||||
|
/// as the build made for the processor runs faster; native before Wine either way.
|
||||||
|
/// </summary>
|
||||||
|
private int Rank(string path)
|
||||||
|
{
|
||||||
|
int wine = IsExeOnLinux(path) ? 1 : 0;
|
||||||
|
int noAvx2 = IsNoAvx2(path) ? 1 : 0;
|
||||||
|
return _lacksAvx2 ? (1 - noAvx2) * 2 + wine : wine * 2 + noAvx2;
|
||||||
|
}
|
||||||
|
|
||||||
public List<string> ListCandidates(string? directory = null)
|
public List<string> ListCandidates(string? directory = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -267,33 +302,6 @@ public sealed class ExecutableLocator
|
|||||||
return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage";
|
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>
|
/// <summary>A path as <see cref="Resolve"/> gives it, which may be relative to the installation, made whole.</summary>
|
||||||
public string FullPath(string path) =>
|
public string FullPath(string path) =>
|
||||||
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);
|
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -9,16 +10,21 @@ namespace StarterNG.Infrastructure.Settings;
|
|||||||
|
|
||||||
public sealed class SettingsSerializer
|
public sealed class SettingsSerializer
|
||||||
{
|
{
|
||||||
private readonly bool _dlssPlatform;
|
/// <summary>
|
||||||
|
/// An ini of before the tapes of the trains, its recording turned on ("blackbox yes", with the physics log of every
|
||||||
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
|
/// vehicle, hundreds of files on a big scenery): moved to the tapes of the trains, the log of every vehicle off.
|
||||||
public SettingsSerializer(bool dlssPlatform = true)
|
/// 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)
|
public void Read(SimulatorSettings s, ConfigFile c)
|
||||||
{
|
{
|
||||||
s.LanguageWasSet = c.Has("lang");
|
s.LanguageWasSet = c.Has("lang");
|
||||||
@@ -30,20 +36,21 @@ public sealed class SettingsSerializer
|
|||||||
s.FpsAverage = c.GetDouble("fpsaverage", 0);
|
s.FpsAverage = c.GetDouble("fpsaverage", 0);
|
||||||
s.PauseOnStart = c.GetBool("pause", false);
|
s.PauseOnStart = c.GetBool("pause", false);
|
||||||
|
|
||||||
|
// A zero (or NaN/Infinity) scale locks that axis in the simulator: the
|
||||||
|
// camera then turns only one way. Nothing in the starter writes such a
|
||||||
|
// number on purpose, so X takes the default. Of Y only the sign is read:
|
||||||
|
// it is written 0.5 or -0.5, as the old starter always wrote it.
|
||||||
var mouse = c.GetTokens("mousescale");
|
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.InvertMouseHorizontal = mx < 0;
|
||||||
s.MouseScaleXMagnitude = Math.Abs(mx);
|
s.MouseScaleXMagnitude = Math.Abs(mx);
|
||||||
s.CursorSensitivity = SensitivityStep(mx);
|
s.CursorSensitivity = SensitivityStep(mx);
|
||||||
}
|
}
|
||||||
if (mouse.Length >= 2 && double.TryParse(mouse[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double my))
|
if (mouse.Length >= 1)
|
||||||
{
|
s.InvertMouseVertical = mouse.Length >= 2 && TryParseMouseScale(mouse[1], out double my) && my < 0;
|
||||||
s.InvertMouseVertical = my < 0;
|
|
||||||
s.MouseScaleYMagnitude = Math.Abs(my);
|
|
||||||
}
|
|
||||||
|
|
||||||
s.IgnoreGamepad = !c.GetBool("input.gamepad", true);
|
s.IgnoreGamepad = !c.GetBool("input.gamepad", false);
|
||||||
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
|
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
|
||||||
s.FeedbackPort = c.GetInt("feedbackport", 888);
|
s.FeedbackPort = c.GetInt("feedbackport", 888);
|
||||||
s.UartEnabled = c.Has("uart");
|
s.UartEnabled = c.Has("uart");
|
||||||
@@ -76,8 +83,7 @@ public sealed class SettingsSerializer
|
|||||||
s.VirtualShunting = c.GetBool("ai.trainman", true);
|
s.VirtualShunting = c.GetBool("ai.trainman", true);
|
||||||
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
|
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
|
||||||
|
|
||||||
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "full"));
|
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default"));
|
||||||
s.VulkanDevice = c.GetString("gfx.vulkan.device", "");
|
|
||||||
s.Width = c.GetInt("width", 1280);
|
s.Width = c.GetInt("width", 1280);
|
||||||
s.Height = c.GetInt("height", 720);
|
s.Height = c.GetInt("height", 720);
|
||||||
s.BufferScalePercent = ReadBufferScale(c);
|
s.BufferScalePercent = ReadBufferScale(c);
|
||||||
@@ -85,9 +91,6 @@ public sealed class SettingsSerializer
|
|||||||
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
|
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
|
||||||
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
|
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
|
||||||
s.AntiAliasing = ReadAntiAliasing(c);
|
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.DynamicLights = Clamp(c.GetInt("dynamiclights", 7), 0, 7);
|
||||||
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
|
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
|
||||||
s.VSync = c.GetBool("vsync", false);
|
s.VSync = c.GetBool("vsync", false);
|
||||||
@@ -99,34 +102,6 @@ public sealed class SettingsSerializer
|
|||||||
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
|
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
|
||||||
s.UseVbo = c.GetBool("usevbo", true);
|
s.UseVbo = c.GetBool("usevbo", true);
|
||||||
s.RenderShadows = c.GetBool("shadows", 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.
|
// A negative rate counts as its size; none at all, as never.
|
||||||
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
|
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
|
||||||
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
|
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
|
||||||
@@ -150,6 +125,7 @@ public sealed class SettingsSerializer
|
|||||||
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
|
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
|
||||||
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
|
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
|
||||||
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
|
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
|
||||||
|
s.FullscreenMonitor = c.GetString("fullscreenmonitor", "").Trim();
|
||||||
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
|
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4);
|
s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4);
|
||||||
@@ -157,6 +133,11 @@ public sealed class SettingsSerializer
|
|||||||
s.EnableTraction = c.GetBool("enabletraction", true);
|
s.EnableTraction = c.GetBool("enabletraction", true);
|
||||||
s.LiveTraction = c.GetBool("livetraction", true);
|
s.LiveTraction = c.GetBool("livetraction", true);
|
||||||
s.PhysicsLog = c.GetBool("physicslog", false);
|
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);
|
int debugLog = c.GetInt("debuglog", 3);
|
||||||
s.DebugLog = (debugLog & 1) != 0;
|
s.DebugLog = (debugLog & 1) != 0;
|
||||||
s.DebugLogVisible = (debugLog & 2) != 0;
|
s.DebugLogVisible = (debugLog & 2) != 0;
|
||||||
@@ -193,6 +174,8 @@ public sealed class SettingsSerializer
|
|||||||
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
|
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
|
||||||
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
|
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
|
||||||
s.AutoExpandSceneryTree = c.GetBool("starter.expandtree", 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.CpuNotice = c.GetBool("starter.cpunotice", true);
|
||||||
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
|
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
|
||||||
? GpuPreference.System
|
? GpuPreference.System
|
||||||
@@ -217,7 +200,7 @@ public sealed class SettingsSerializer
|
|||||||
if (c.Has(key.Key))
|
if (c.Has(key.Key))
|
||||||
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
|
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
|
||||||
|
|
||||||
GraphicsRules.Normalize(s, _dlssPlatform);
|
GraphicsRules.Normalize(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -228,13 +211,20 @@ public sealed class SettingsSerializer
|
|||||||
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
|
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
|
||||||
|
|
||||||
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
|
/// <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>
|
/// <summary>Keys no simulator reads any more, taken out of the file on a save.</summary>
|
||||||
public static readonly string[] ObsoleteKeys =
|
public static readonly string[] ObsoleteKeys =
|
||||||
{
|
{
|
||||||
"gfx.postfx.tonemapping",
|
"gfx.postfx.tonemapping",
|
||||||
"starter.developertools",
|
"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>
|
/// <summary>
|
||||||
@@ -244,7 +234,7 @@ public sealed class SettingsSerializer
|
|||||||
public void Write(SimulatorSettings settings, ConfigFile c)
|
public void Write(SimulatorSettings settings, ConfigFile c)
|
||||||
{
|
{
|
||||||
var s = settings.Copy();
|
var s = settings.Copy();
|
||||||
GraphicsRules.Normalize(s, _dlssPlatform);
|
GraphicsRules.Normalize(s);
|
||||||
|
|
||||||
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
|
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
|
||||||
? "en"
|
? "en"
|
||||||
@@ -257,7 +247,7 @@ public sealed class SettingsSerializer
|
|||||||
? s.MouseScaleXMagnitude
|
? s.MouseScaleXMagnitude
|
||||||
: s.CursorSensitivity;
|
: s.CursorSensitivity;
|
||||||
double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1);
|
double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1);
|
||||||
double my = s.MouseScaleYMagnitude * (s.InvertMouseVertical ? -1 : 1);
|
double my = SimulatorSettings.MouseScaleY * (s.InvertMouseVertical ? -1 : 1);
|
||||||
c.Set("mousescale",
|
c.Set("mousescale",
|
||||||
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
|
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
|
||||||
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
|
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
|
||||||
@@ -292,26 +282,16 @@ public sealed class SettingsSerializer
|
|||||||
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
|
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
|
||||||
|
|
||||||
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
|
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("width", s.Width);
|
||||||
c.SetInt("height", s.Height);
|
c.SetInt("height", s.Height);
|
||||||
c.SetInt("starter.bufferscale", s.BufferScalePercent);
|
c.SetInt("starter.bufferscale", s.BufferScalePercent);
|
||||||
int fbw = (int)Math.Round(s.Width * s.BufferScalePercent / 100.0);
|
// The simulator draws into a buffer of this size and stretches it to the window.
|
||||||
int fbh = (int)Math.Round(s.Height * s.BufferScalePercent / 100.0);
|
c.SetInt("gfx.framebuffer.width", (int)Math.Round(s.Width * 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.height", (int)Math.Round(s.Height * s.BufferScalePercent / 100.0));
|
||||||
c.SetInt("gfx.framebuffer.width", fbw);
|
|
||||||
c.SetInt("gfx.framebuffer.height", fbh);
|
|
||||||
c.SetInt("gfx.buffer.percent", s.BufferScalePercent);
|
|
||||||
c.SetInt("maxtexturesize", s.MaxTextureSize);
|
c.SetInt("maxtexturesize", s.MaxTextureSize);
|
||||||
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
|
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
|
||||||
c.SetDouble("anisotropicfiltering", s.TextureFiltering);
|
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.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.SetInt("dynamiclights", s.DynamicLights);
|
||||||
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
|
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
|
||||||
c.SetBool("vsync", s.VSync);
|
c.SetBool("vsync", s.VSync);
|
||||||
@@ -324,32 +304,6 @@ public sealed class SettingsSerializer
|
|||||||
c.SetBool("usevbo", s.UseVbo);
|
c.SetBool("usevbo", s.UseVbo);
|
||||||
c.SetBool("shadows", s.RenderShadows);
|
c.SetBool("shadows", s.RenderShadows);
|
||||||
c.SetBool("gfx.shadowmap.enabled", 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("gfx.reflections.framerate", s.ReflectionsFramerate.ToString("0.######", CultureInfo.InvariantCulture));
|
||||||
c.Set("shadowtune",
|
c.Set("shadowtune",
|
||||||
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
|
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
|
||||||
@@ -363,6 +317,7 @@ public sealed class SettingsSerializer
|
|||||||
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
|
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
|
||||||
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
|
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
|
||||||
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
|
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
|
||||||
|
if (!string.IsNullOrWhiteSpace(s.FullscreenMonitor)) c.Set("fullscreenmonitor", s.FullscreenMonitor.Trim());
|
||||||
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
|
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
|
||||||
|
|
||||||
c.SetInt("splinefidelity", s.SplineFidelity);
|
c.SetInt("splinefidelity", s.SplineFidelity);
|
||||||
@@ -370,6 +325,13 @@ public sealed class SettingsSerializer
|
|||||||
c.SetBool("enabletraction", s.EnableTraction);
|
c.SetBool("enabletraction", s.EnableTraction);
|
||||||
c.SetBool("livetraction", s.LiveTraction);
|
c.SetBool("livetraction", s.LiveTraction);
|
||||||
c.SetBool("physicslog", s.PhysicsLog);
|
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",
|
c.SetInt("debuglog",
|
||||||
(s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits);
|
(s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits);
|
||||||
c.SetBool("multiplelogs", s.MultipleLogs);
|
c.SetBool("multiplelogs", s.MultipleLogs);
|
||||||
@@ -402,6 +364,8 @@ public sealed class SettingsSerializer
|
|||||||
c.SetBool("starter.autoclose", s.AutoCloseStarter);
|
c.SetBool("starter.autoclose", s.AutoCloseStarter);
|
||||||
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
|
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
|
||||||
c.SetBool("starter.expandtree", s.AutoExpandSceneryTree);
|
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.SetBool("starter.cpunotice", s.CpuNotice);
|
||||||
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
|
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
|
||||||
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
|
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
|
||||||
@@ -420,60 +384,42 @@ public sealed class SettingsSerializer
|
|||||||
c.Set(key.Key, value.Trim());
|
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) =>
|
||||||
private static int ReadBufferScale(ConfigFile c)
|
Clamp(BufferScaleIn(c), 25, GraphicsRules.MaxBufferScale);
|
||||||
{
|
|
||||||
if (!c.Has("gfx.buffer.percent"))
|
|
||||||
return Clamp(c.GetInt("starter.bufferscale", 100), 25, 200);
|
|
||||||
|
|
||||||
double value = c.GetDouble("gfx.buffer.percent", 100);
|
// The starter's own percent, or the framebuffer the file sets against its window.
|
||||||
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
|
private static int BufferScaleIn(ConfigFile c)
|
||||||
|
{
|
||||||
|
if (c.Has("starter.bufferscale"))
|
||||||
|
return c.GetInt("starter.bufferscale", 100);
|
||||||
|
int width = c.GetInt("width", 0);
|
||||||
|
int framebuffer = c.GetInt("gfx.framebuffer.width", 0);
|
||||||
|
return width > 0 && framebuffer > 0 ? (int)Math.Round(framebuffer * 100.0 / width) : 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string FirstToken(ConfigFile c, string key)
|
/// <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 tokens = c.GetTokens(key);
|
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
return tokens.Length > 0 ? tokens[0].ToLowerInvariant() : string.Empty;
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The names the simulator takes for Vulkan; every other word is OpenGL to the screen, and stays in the file until changed.
|
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c) => c.GetInt("multisampling", 2) switch
|
||||||
// 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)
|
|
||||||
{
|
{
|
||||||
var fromMultisampling = c.GetInt("multisampling", 2) switch
|
<= 0 => AntiAliasingMode.Off,
|
||||||
{
|
1 => AntiAliasingMode.Msaa2,
|
||||||
<= 0 => AntiAliasingMode.Off,
|
2 => AntiAliasingMode.Msaa4,
|
||||||
1 => AntiAliasingMode.Msaa2,
|
_ => AntiAliasingMode.Msaa8
|
||||||
2 => AntiAliasingMode.Msaa4,
|
|
||||||
_ => AntiAliasingMode.Msaa8
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!c.Has("gfx.antialiasing") ||
|
|
||||||
(c.Has("multisampling") && c.LineOf("multisampling") > c.LineOf("gfx.antialiasing")))
|
|
||||||
return fromMultisampling;
|
|
||||||
|
|
||||||
return FirstToken(c, "gfx.antialiasing") switch
|
|
||||||
{
|
|
||||||
"off" or "no" or "none" or "0" => AntiAliasingMode.Off,
|
|
||||||
"msaax2" => AntiAliasingMode.Msaa2,
|
|
||||||
"msaax4" => AntiAliasingMode.Msaa4,
|
|
||||||
"msaax8" or "msaax16" => AntiAliasingMode.Msaa8,
|
|
||||||
"taa" => AntiAliasingMode.Taa,
|
|
||||||
"dlss" => AntiAliasingMode.Dlss,
|
|
||||||
"dlaa" => AntiAliasingMode.Dlaa,
|
|
||||||
_ => fromMultisampling
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
private static int MultisamplingLevel(AntiAliasingMode mode) => mode switch
|
||||||
@@ -484,79 +430,28 @@ public sealed class SettingsSerializer
|
|||||||
_ => 0
|
_ => 0
|
||||||
};
|
};
|
||||||
|
|
||||||
private static int ParseFrameGeneration(string value) => value switch
|
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
||||||
{
|
|
||||||
"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
|
/// <summary>
|
||||||
|
/// Whether the file's own mousescale can stay as it is: a first number neither
|
||||||
|
/// zero nor NaN/Infinity, and 0.5 or -0.5 after it. Otherwise a save writes the
|
||||||
|
/// one the starter holds.
|
||||||
|
/// </summary>
|
||||||
|
public static bool MouseScaleStands(string? raw)
|
||||||
{
|
{
|
||||||
"on" or "yes" or "1" => 1,
|
string[] tokens = (raw ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||||
"boost" or "2" => 2,
|
return tokens.Length >= 2 &&
|
||||||
_ => 0
|
TryParseMouseScale(tokens[0], out _) &&
|
||||||
};
|
TryParseMouseScale(tokens[1], out double y) &&
|
||||||
|
Math.Abs(y) == SimulatorSettings.MouseScaleY;
|
||||||
// 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
|
private static bool TryParseMouseScale(string token, out double scale) =>
|
||||||
{
|
double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale) &&
|
||||||
1 => "low",
|
double.IsFinite(scale) && scale != 0;
|
||||||
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) =>
|
private static int SensitivityStep(double mouseScale) =>
|
||||||
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
|
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
|
||||||
|
|
||||||
private static double ParseDouble(string s, double fallback) =>
|
private static double ParseDouble(string s, double fallback) =>
|
||||||
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback;
|
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback;
|
||||||
|
|
||||||
|
|||||||
32
StarterNG/Infrastructure/SoftwareRender.cs
Normal file
32
StarterNG/Infrastructure/SoftwareRender.cs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Avalonia;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drawn by the processor instead of the graphics card, for a machine on which the
|
||||||
|
/// window comes up empty. Each platform reads only its own options, so both are given.
|
||||||
|
/// </summary>
|
||||||
|
public static class SoftwareRender
|
||||||
|
{
|
||||||
|
public const string Switch = "--software-render";
|
||||||
|
|
||||||
|
public static bool AskedIn(IEnumerable<string> args) =>
|
||||||
|
args.Any(a => string.Equals(a, Switch, StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
|
public static Win32PlatformOptions Win32Options => new()
|
||||||
|
{
|
||||||
|
RenderingMode = new[] { Win32RenderingMode.Software },
|
||||||
|
CompositionMode = new[] { Win32CompositionMode.RedirectionSurface }
|
||||||
|
};
|
||||||
|
|
||||||
|
public static X11PlatformOptions X11Options => new()
|
||||||
|
{
|
||||||
|
RenderingMode = new[] { X11RenderingMode.Software }
|
||||||
|
};
|
||||||
|
|
||||||
|
public static AppBuilder ApplyTo(AppBuilder builder) =>
|
||||||
|
builder.With(Win32Options).With(X11Options);
|
||||||
|
}
|
||||||
90
StarterNG/Infrastructure/SystemGraphicsLibraries.cs
Normal file
90
StarterNG/Infrastructure/SystemGraphicsLibraries.cs
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace StarterNG.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The starter sits in the simulator's folder, and so do the graphics wrappers a player
|
||||||
|
/// puts there for the simulator - ReShade and the like, named after the system library
|
||||||
|
/// they stand in for. Windows looks in the program's own folder first, so the starter's
|
||||||
|
/// window drew through them too, and with some of them it drew nothing at all.
|
||||||
|
/// Loaded from System32 by full path before anything asks for them, these names are
|
||||||
|
/// taken: a native library that asks by name gets the system one. .NET looks beside the
|
||||||
|
/// program by full path before it asks by name, so the window code's own imports are
|
||||||
|
/// handed the same libraries. The simulator is a process of its own and still finds its
|
||||||
|
/// wrappers.
|
||||||
|
/// Elsewhere there is nothing of the kind to keep out. Under Wine or Proton the system
|
||||||
|
/// folder is the prefix's, so what is taken there is what would have been taken anyway.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SystemGraphicsLibraries
|
||||||
|
{
|
||||||
|
public delegate bool Loader(string path, out IntPtr handle);
|
||||||
|
|
||||||
|
// dxgi ahead of d3d11, which asks for it.
|
||||||
|
public static readonly IReadOnlyList<string> Names = new[] { "dxgi", "d3d11", "d3d9", "opengl32" };
|
||||||
|
|
||||||
|
private readonly Dictionary<string, IntPtr> _loaded = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private readonly List<string> _shadowed = new();
|
||||||
|
|
||||||
|
private SystemGraphicsLibraries()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The files of these names that lay beside the starter.</summary>
|
||||||
|
public IReadOnlyList<string> Shadowed => _shadowed;
|
||||||
|
|
||||||
|
/// <summary>What goes to the log about them, or null when none lay there.</summary>
|
||||||
|
public string? Note => _shadowed.Count > 0
|
||||||
|
? $"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", _shadowed)}"
|
||||||
|
: null;
|
||||||
|
|
||||||
|
/// <summary>The libraries of this Windows, or null on any other system.</summary>
|
||||||
|
public static SystemGraphicsLibraries? TakeOnWindows() =>
|
||||||
|
OperatingSystem.IsWindows()
|
||||||
|
? Take(Environment.SystemDirectory, AppContext.BaseDirectory, File.Exists, NativeLibrary.TryLoad)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
public static SystemGraphicsLibraries Take(string systemDirectory, string ownDirectory,
|
||||||
|
Func<string, bool> exists, Loader load)
|
||||||
|
{
|
||||||
|
var taken = new SystemGraphicsLibraries();
|
||||||
|
foreach (string name in Names)
|
||||||
|
{
|
||||||
|
string file = name + ".dll";
|
||||||
|
if (exists(Path.Combine(ownDirectory, file)))
|
||||||
|
taken._shadowed.Add(file);
|
||||||
|
if (load(Path.Combine(systemDirectory, file), out IntPtr handle))
|
||||||
|
taken._loaded[name] = handle;
|
||||||
|
}
|
||||||
|
return taken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The system library for an import of one of these names; zero leaves it to the usual search.</summary>
|
||||||
|
public IntPtr Resolve(string libraryName)
|
||||||
|
{
|
||||||
|
string name = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? libraryName[..^4]
|
||||||
|
: libraryName;
|
||||||
|
return _loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The assembly's imports of these names get the system libraries. False when it
|
||||||
|
/// has a resolver of its own already; that one decides.
|
||||||
|
/// </summary>
|
||||||
|
public bool ServeTo(Assembly importer)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
NativeLibrary.SetDllImportResolver(importer, (name, _, _) => Resolve(name));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user