mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-22 00:04:57 +01:00
Compare commits
46 Commits
v1.6.260
...
feat/setti
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93f914c868 | ||
|
|
de943cf461 | ||
|
|
e63aa71bf8 | ||
|
|
ecf3067d85 | ||
| c07ed2fb4d | |||
| cfea240243 | |||
|
|
f0fa2d1768 | ||
|
|
2a85ca384a | ||
|
|
fa8ae760e1 | ||
|
|
100bbea83e | ||
|
|
195f358e55 | ||
|
|
be7b9c5679 | ||
|
|
c370d1509e | ||
| 3c9b578e6b | |||
| 952618be13 | |||
| 156af3fdd1 | |||
| 49b76aa66c | |||
|
|
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 |
@@ -30,7 +30,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.",
|
||||
["Follow"] = "Follow the train",
|
||||
["Fit"] = "Whole map",
|
||||
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
|
||||
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.",
|
||||
["Unreadable"] = "Can't read {0}: {1}",
|
||||
["Reading"] = "Reading {0}…",
|
||||
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
|
||||
@@ -185,8 +185,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["EventHornMissed"] = "W6: NO HORN",
|
||||
["EventCab"] = "Cab {0} of {1}",
|
||||
["EventSecurityBraking"] = "BRAKING BY {0}",
|
||||
["EventSecurityAlarm"] = "{0} buzzer",
|
||||
["EventSecurityAlarmAcknowledged"] = "{0} buzzer, acknowledged after {1:0.0} s",
|
||||
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
|
||||
["EventTimetable"] = "Timetable {0}, {1}",
|
||||
["CabSpeed"] = "Speed",
|
||||
["CabWheels"] = "wheels {0:0}",
|
||||
["CabAiTarget"] = "AI {0:0} km/h",
|
||||
["CabAcceleration"] = "Along",
|
||||
["CabLateral"] = "Lateral",
|
||||
@@ -305,7 +309,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
|
||||
["Follow"] = "Śledź pociąg",
|
||||
["Fit"] = "Cała mapa",
|
||||
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",
|
||||
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.",
|
||||
["Unreadable"] = "Nie można odczytać {0}: {1}",
|
||||
["Reading"] = "Czytanie {0}…",
|
||||
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
|
||||
@@ -460,8 +464,12 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
|
||||
["EventCab"] = "Kabina {0} w {1}",
|
||||
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
|
||||
["EventSecurityAlarm"] = "Brzęczyk {0}",
|
||||
["EventSecurityAlarmAcknowledged"] = "Brzęczyk {0}, potwierdzony po {1:0.0} s",
|
||||
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
|
||||
["EventTimetable"] = "Rozkład {0}, {1}",
|
||||
["CabSpeed"] = "Prędkość",
|
||||
["CabWheels"] = "koła {0:0}",
|
||||
["CabAiTarget"] = "AI {0:0} km/h",
|
||||
["CabAcceleration"] = "Wzdłużne",
|
||||
["CabLateral"] = "Boczne",
|
||||
@@ -564,7 +572,11 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
["FileFilter"] = "Czarna skrzynka"
|
||||
};
|
||||
|
||||
/// <summary>The key of the text of a simulator's command: <see cref="CommandPrefix"/> and its name.</summary>
|
||||
public const string CommandPrefix = "Cmd.";
|
||||
|
||||
private readonly Dictionary<string, string> _texts;
|
||||
private readonly string _languageCode;
|
||||
|
||||
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
|
||||
{
|
||||
@@ -577,11 +589,15 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
||||
/// <summary>Polish for "pl", English for any other language.</summary>
|
||||
public DefaultBlackBoxStrings(string languageCode)
|
||||
{
|
||||
_languageCode = languageCode;
|
||||
_texts = languageCode == "pl" ? Polish : English;
|
||||
}
|
||||
|
||||
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
|
||||
public static IEnumerable<string> Keys => English.Keys;
|
||||
|
||||
public string this[string key] => _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
||||
/// <summary>A key of <see cref="CommandPrefix"/> gives what the command does (<see cref="CommandTexts"/>).</summary>
|
||||
public string this[string key] =>
|
||||
key.StartsWith(CommandPrefix, System.StringComparison.Ordinal) ? CommandTexts.Of(key[CommandPrefix.Length..], _languageCode)
|
||||
: _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ public sealed class CabPanel : Control
|
||||
private const double LampRow = 14;
|
||||
private const int DoorColumns = 2;
|
||||
private const double DriveRow = 34;
|
||||
private const double WheelsApartKmh = 1.0; // the wheels shown when they turn this much faster or slower
|
||||
|
||||
private Recording? _recording;
|
||||
private double _time;
|
||||
@@ -174,8 +175,19 @@ public sealed class CabPanel : Control
|
||||
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
|
||||
context.DrawText(speed, new Point(Pad, 24));
|
||||
Say($"{kmh} km/h");
|
||||
context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
|
||||
var unit = MapView.Text("km/h", Palette.DimText, 12);
|
||||
context.DrawText(unit, new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
|
||||
double gaugeX = Pad + Math.Max(150, width * 0.42);
|
||||
// the wheels, when they turn otherwise: slipping, or locked in a skid. Signed both, so wheels slipping ahead
|
||||
// of a train rolling back show too. Kept off the gauges at the right, as the AI's line is.
|
||||
if (s.WheelSpeedKmh is { } wheels && Math.Abs(wheels - s.SpeedKmh) >= WheelsApartKmh)
|
||||
{
|
||||
double wheelsX = Pad + speed.Width + 4 + unit.Width + 8;
|
||||
string wheelsText = string.Format(culture, Strings["CabWheels"], Math.Abs(wheels));
|
||||
using (context.PushClip(new Rect(wheelsX, 24, Math.Max(0, gaugeX - 8 - wheelsX), 40)))
|
||||
context.DrawText(MapView.Text(wheelsText, Palette.Warn, 12), new Point(wheelsX, 24 + speed.Height - 21));
|
||||
Say(wheelsText);
|
||||
}
|
||||
if (s.AiValid)
|
||||
{
|
||||
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
|
||||
@@ -337,7 +349,7 @@ public sealed class CabPanel : Control
|
||||
{
|
||||
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
|
||||
Say(Strings["CabGroupDoors"]);
|
||||
var doors = Doors(s);
|
||||
var doors = Doors(s.AsTheCabSees);
|
||||
double doorColumn = width / DoorColumns;
|
||||
for (int i = 0; i < doors.Length; i++)
|
||||
{
|
||||
@@ -660,12 +672,12 @@ public sealed class CabPanel : Control
|
||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||
{
|
||||
// A recording which tells them apart.
|
||||
safety.Add((Strings["DevVigilance"], Security(SecurityFlags.VigilanceBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
||||
safety.Add((Strings["DevCabSignal"], Security(SecurityFlags.CabSignalBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
||||
safety.Add((Strings["DevSecurityBraking"], Security(SecurityFlags.Braking, Palette.LampAlarm)));
|
||||
safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
||||
safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
||||
safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null));
|
||||
}
|
||||
else
|
||||
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
||||
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
|
||||
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
|
||||
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
|
||||
|
||||
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 events = new List<BlackBoxEvent>();
|
||||
foreach (var c in recording.UserCommands())
|
||||
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], c.Name), Palette.Command, false));
|
||||
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"],
|
||||
strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]),
|
||||
Palette.Command, false));
|
||||
foreach (var d in recording.DriverChanges)
|
||||
{
|
||||
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
|
||||
@@ -176,14 +178,7 @@ public sealed class EventList : ListBox
|
||||
foreach (var horn in recording.UserHornChecks())
|
||||
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
|
||||
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
|
||||
foreach (var span in recording.SecurityBrakings())
|
||||
{
|
||||
// Which of them was not acknowledged: the lamps blinking when it braked.
|
||||
string who = recording.CabAt(span.Start) is { } s
|
||||
? s.Has(SecurityFlags.CabSignal) && s.Has(SecurityFlags.Vigilance) ? "CA/SHP" : s.Has(SecurityFlags.CabSignal) ? "SHP" : "CA"
|
||||
: "CA";
|
||||
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"], who), Palette.Bad, true));
|
||||
}
|
||||
AddSecurity(recording, strings, events, culture);
|
||||
AddCameras(recording, strings, events, culture);
|
||||
AddCouplings(recording, strings, events, culture);
|
||||
AddCabChanges(recording, strings, events, culture);
|
||||
@@ -196,6 +191,45 @@ public sealed class EventList : ListBox
|
||||
return events.OrderBy(e => e.Time).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The train protection: its buzzer, acknowledged or not, and the braking apart. A lamp acknowledged before the
|
||||
/// buzzer is the driving as usual, not told.
|
||||
/// </summary>
|
||||
private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
||||
{
|
||||
var brakings = recording.SecurityBrakings();
|
||||
foreach (var span in recording.SecurityAlarms())
|
||||
{
|
||||
// The lamps of all its buzzing samples: one buzzer for both, the other may join it before it's acknowledged.
|
||||
var lamps = recording.Cab.Where(c => c.Time >= span.Start && c.Time <= span.End && (c.VigilanceBuzzer || c.CabSignalBuzzer))
|
||||
.Aggregate(SecurityFlags.None, (all, c) => all | c.Security);
|
||||
string who = ProtectionName(lamps);
|
||||
var before = recording.CabAt(span.Start);
|
||||
string text = brakings.Any(b => b.Start >= span.Start && b.Start <= span.End)
|
||||
? string.Format(culture, strings["EventSecurityAlarmMissed"], who)
|
||||
// Acknowledged when the sample it ended at buzzes no more and doesn't brake, in the same vehicle: not
|
||||
// the end of the recording or a gap in it, nor the power cut or the protection switched off.
|
||||
: recording.CabAt(span.End) is { } after && !after.VigilanceBuzzer && !after.CabSignalBuzzer
|
||||
&& !after.Has(SecurityFlags.Braking) && after.Vehicle == before?.Vehicle
|
||||
? string.Format(culture, strings["EventSecurityAlarmAcknowledged"], who, span.End - span.Start)
|
||||
: string.Format(culture, strings["EventSecurityAlarm"], who);
|
||||
events.Add(new BlackBoxEvent(span.Start, text, Palette.Buzzer, false));
|
||||
}
|
||||
foreach (var span in brakings)
|
||||
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"],
|
||||
ProtectionName(recording.CabAt(span.Start)?.Security ?? SecurityFlags.None)),
|
||||
Palette.Bad, true));
|
||||
}
|
||||
|
||||
/// <summary>Which of them it was: the lamps blinking.</summary>
|
||||
private static string ProtectionName(SecurityFlags lamps) =>
|
||||
(lamps & (SecurityFlags.CabSignal | SecurityFlags.Vigilance)) switch
|
||||
{
|
||||
SecurityFlags.CabSignal | SecurityFlags.Vigilance => "CA/SHP",
|
||||
SecurityFlags.CabSignal => "SHP",
|
||||
_ => "CA"
|
||||
};
|
||||
|
||||
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
||||
{
|
||||
UserVehicleChange? before = null;
|
||||
@@ -282,6 +316,8 @@ public sealed class EventList : ListBox
|
||||
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
||||
];
|
||||
|
||||
private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight;
|
||||
|
||||
/// <summary>
|
||||
/// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the
|
||||
/// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the
|
||||
@@ -291,7 +327,8 @@ public sealed class EventList : ListBox
|
||||
{
|
||||
CabSample? last = null;
|
||||
bool movingOpen = false;
|
||||
foreach (var s in recording.Cab)
|
||||
// the doors' sides as the driver has them, from the cab the driver is in (CabSample.AsTheCabSees)
|
||||
foreach (var s in recording.Cab.Select(sample => sample.AsTheCabSees))
|
||||
{
|
||||
if (last is not { } b || b.Vehicle != s.Vehicle)
|
||||
{
|
||||
@@ -299,8 +336,10 @@ public sealed class EventList : ListBox
|
||||
movingOpen = false;
|
||||
continue;
|
||||
}
|
||||
bool Came(CabDevices device) => !b.Has(device) && s.Has(device);
|
||||
bool Went(CabDevices device) => b.Has(device) && !s.Has(device);
|
||||
// the other end swaps the sides, and tells nothing of the doors; no cab (0) sees them as the front one does
|
||||
bool sameCab = (b.CabEnd < 0) == (s.CabEnd < 0);
|
||||
bool Came(CabDevices device) => !b.Has(device) && s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
||||
bool Went(CabDevices device) => b.Has(device) && !s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
||||
foreach (var (device, key) in Switched)
|
||||
{
|
||||
if (Came(device))
|
||||
|
||||
@@ -25,8 +25,12 @@ public sealed class MapView : Control
|
||||
private Recording? _recording;
|
||||
private int _builtRevision = -1;
|
||||
private int _builtTracks = -1;
|
||||
private StreamGeometry? _tracks;
|
||||
private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new();
|
||||
private TrackLayer? _tracks;
|
||||
private readonly List<(int Index, int Branch, IReadOnlyList<System.Numerics.Vector3> Points)> _switchWays = new();
|
||||
// The switches as they lay when last drawn, and their ways in two geometries: not taken, taken.
|
||||
private int[] _switchStates = Array.Empty<int>();
|
||||
private StreamGeometry? _waysOff, _waysOn;
|
||||
private string? _hoverShown;
|
||||
private readonly StreamGeometry?[] _trail = new StreamGeometry?[5];
|
||||
private Rect _world;
|
||||
|
||||
@@ -135,33 +139,24 @@ public sealed class MapView : Control
|
||||
{
|
||||
_builtTracks = recording.Tracks.Count;
|
||||
_switchWays.Clear();
|
||||
var tracks = new StreamGeometry();
|
||||
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
|
||||
using (var g = tracks.Open())
|
||||
foreach (var track in recording.Tracks)
|
||||
{
|
||||
foreach (var track in recording.Tracks)
|
||||
if (track.Points.Count < 2)
|
||||
continue;
|
||||
foreach (var p in track.Points)
|
||||
{
|
||||
if (track.Points.Count < 2)
|
||||
continue;
|
||||
foreach (var p in track.Points)
|
||||
{
|
||||
left = Math.Min(left, -p.X);
|
||||
right = Math.Max(right, -p.X);
|
||||
top = Math.Min(top, -p.Z);
|
||||
bottom = Math.Max(bottom, -p.Z);
|
||||
}
|
||||
if (track.Kind == TrackKind.SwitchBranch)
|
||||
{
|
||||
var way = new StreamGeometry();
|
||||
using (var w = way.Open())
|
||||
Polyline(w, track.Points);
|
||||
_switchWays.Add((track.Index, track.Branch, way));
|
||||
}
|
||||
else
|
||||
Polyline(g, track.Points);
|
||||
left = Math.Min(left, -p.X);
|
||||
right = Math.Max(right, -p.X);
|
||||
top = Math.Min(top, -p.Z);
|
||||
bottom = Math.Max(bottom, -p.Z);
|
||||
}
|
||||
if (track.Kind == TrackKind.SwitchBranch)
|
||||
_switchWays.Add((track.Index, track.Branch, track.Points));
|
||||
}
|
||||
_tracks = tracks;
|
||||
_tracks = new TrackLayer(recording.Tracks);
|
||||
_switchStates = Array.Empty<int>();
|
||||
_waysOff = _waysOn = null;
|
||||
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
|
||||
}
|
||||
BuildTrail(recording);
|
||||
@@ -247,29 +242,26 @@ public sealed class MapView : Control
|
||||
double pixel = 1 / _scale;
|
||||
using (context.PushTransform(toScreen))
|
||||
{
|
||||
// The tracks on a dark casing, so they stand out where they cross and run close.
|
||||
// The tracks on a dark casing, so they stand out where they cross and run close. Only the
|
||||
// cells in view, at the detail a pixel can show.
|
||||
var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round);
|
||||
if (_tracks is not null)
|
||||
context.DrawGeometry(null, casing, _tracks);
|
||||
foreach (var (_, _, way) in _switchWays)
|
||||
context.DrawGeometry(null, casing, way);
|
||||
if (_tracks is not null)
|
||||
context.DrawGeometry(null, new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round), _tracks);
|
||||
var off = new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round);
|
||||
var on = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
|
||||
// The ways not taken under those taken.
|
||||
foreach (var (index, branch, way) in _switchWays)
|
||||
var fill = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
|
||||
if (_tracks is { } layer)
|
||||
{
|
||||
int state = recording.SwitchAt(index, _time);
|
||||
if (state >= 0 && state != branch)
|
||||
context.DrawGeometry(null, off, way);
|
||||
}
|
||||
foreach (var (index, branch, way) in _switchWays)
|
||||
{
|
||||
int state = recording.SwitchAt(index, _time);
|
||||
if (state < 0 || state == branch)
|
||||
context.DrawGeometry(null, on, way);
|
||||
var view = PlaneInView(size, 6 * pixel);
|
||||
int level = TrackLayer.LevelFor(_scale);
|
||||
foreach (var cell in layer.CellsIn(view, level))
|
||||
context.DrawGeometry(null, casing, cell.Casing);
|
||||
foreach (var cell in layer.CellsIn(view, level))
|
||||
if (cell.Fill is { } tracks)
|
||||
context.DrawGeometry(null, fill, tracks);
|
||||
}
|
||||
// The ways not taken under those taken, each set one geometry, made again only when a switch moves.
|
||||
UpdateSwitchWays(recording);
|
||||
if (_waysOff is not null)
|
||||
context.DrawGeometry(null, new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round), _waysOff);
|
||||
if (_waysOn is not null)
|
||||
context.DrawGeometry(null, fill, _waysOn);
|
||||
// The way the train went, in the colour of the judgement.
|
||||
for (int kind = 0; kind < _trail.Length; kind++)
|
||||
if (_trail[kind] is { } trail)
|
||||
@@ -280,12 +272,67 @@ public sealed class MapView : Control
|
||||
DrawHornPoints(context, recording);
|
||||
DrawSignals(context, recording);
|
||||
DrawPassings(context, recording);
|
||||
DrawVehicles(context, recording);
|
||||
// Once a frame: the vehicles and the hover both go by them.
|
||||
var vehicles = recording.VehiclesAt(_time);
|
||||
DrawVehicles(context, recording, vehicles);
|
||||
DrawUserTrain(context, recording);
|
||||
DrawCamera(context, recording);
|
||||
DrawScale(context, size);
|
||||
DrawLegend(context, size);
|
||||
DrawHover(context, recording);
|
||||
DrawHover(context, recording, vehicles);
|
||||
}
|
||||
|
||||
/// <summary>The part of the map's plane on screen, with a margin in plane units.</summary>
|
||||
private Rect PlaneInView(Size size, double margin)
|
||||
{
|
||||
double halfWidth = size.Width / 2 / _scale, halfHeight = size.Height / 2 / _scale;
|
||||
return new Rect(-_centerX - halfWidth - margin, -_centerZ - halfHeight - margin,
|
||||
2 * (halfWidth + margin), 2 * (halfHeight + margin));
|
||||
}
|
||||
|
||||
private void UpdateSwitchWays(Recording recording)
|
||||
{
|
||||
bool changed = _switchStates.Length != _switchWays.Count;
|
||||
if (changed)
|
||||
_switchStates = new int[_switchWays.Count];
|
||||
for (int i = 0; i < _switchWays.Count; i++)
|
||||
{
|
||||
int state = recording.SwitchAt(_switchWays[i].Index, _time);
|
||||
if (state != _switchStates[i] || changed)
|
||||
{
|
||||
_switchStates[i] = state;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed && (_waysOff is not null || _waysOn is not null || _switchWays.Count == 0))
|
||||
return;
|
||||
|
||||
var off = new StreamGeometry();
|
||||
var on = new StreamGeometry();
|
||||
bool anyOff = false, anyOn = false;
|
||||
using (var gOff = off.Open())
|
||||
using (var gOn = on.Open())
|
||||
{
|
||||
for (int i = 0; i < _switchWays.Count; i++)
|
||||
{
|
||||
var (_, branch, points) = _switchWays[i];
|
||||
if (points.Count < 2)
|
||||
continue;
|
||||
int state = _switchStates[i];
|
||||
if (state >= 0 && state != branch)
|
||||
{
|
||||
Polyline(gOff, points);
|
||||
anyOff = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Polyline(gOn, points);
|
||||
anyOn = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
_waysOff = anyOff ? off : null;
|
||||
_waysOn = anyOn ? on : null;
|
||||
}
|
||||
|
||||
private bool Visible(Point p, double margin = 20) =>
|
||||
@@ -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;
|
||||
foreach (var state in recording.VehiclesAt(_time))
|
||||
foreach (var state in vehicles)
|
||||
{
|
||||
var info = recording.Vehicle(state.Id);
|
||||
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>
|
||||
private void DrawHover(DrawingContext context, Recording recording)
|
||||
private void DrawHover(DrawingContext context, Recording recording, IReadOnlyList<VehicleState> vehicles)
|
||||
{
|
||||
if (_pointer is not { } pointer || _dragFrom is not null)
|
||||
_hoverShown = _pointer is { } at && _dragFrom is null ? HoverLabel(recording, at, vehicles) : null;
|
||||
if (_hoverShown is not { } label || _pointer is not { } pointer)
|
||||
return;
|
||||
var text = Text(label, Palette.Text, 12);
|
||||
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
|
||||
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
|
||||
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
|
||||
}
|
||||
|
||||
private string? HoverLabel(Recording recording, Point pointer, IReadOnlyList<VehicleState> vehicles)
|
||||
{
|
||||
string? label = null;
|
||||
double best = 10;
|
||||
foreach (var signal in recording.Signals)
|
||||
@@ -646,7 +702,7 @@ public sealed class MapView : Control
|
||||
label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration);
|
||||
}
|
||||
}
|
||||
foreach (var state in recording.VehiclesAt(_time))
|
||||
foreach (var state in vehicles)
|
||||
{
|
||||
double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer);
|
||||
if (d < best && recording.Vehicle(state.Id) is { } info)
|
||||
@@ -657,12 +713,7 @@ public sealed class MapView : Control
|
||||
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
|
||||
}
|
||||
}
|
||||
if (label is null)
|
||||
return;
|
||||
var text = Text(label, Palette.Text, 12);
|
||||
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
|
||||
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
|
||||
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
|
||||
return label;
|
||||
}
|
||||
|
||||
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
|
||||
@@ -724,8 +775,13 @@ public sealed class MapView : Control
|
||||
_centerX = _dragCenter.X + moved.X / _scale;
|
||||
_centerZ = _dragCenter.Z + moved.Y / _scale;
|
||||
}
|
||||
InvalidateVisual();
|
||||
return;
|
||||
}
|
||||
InvalidateVisual();
|
||||
// Not dragged, the map is the same: drawn again only for a label to show, follow the pointer or go.
|
||||
if (_hoverShown is not null ||
|
||||
(_recording is { } recording && HoverLabel(recording, position, recording.VehiclesAt(_time)) is not null))
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
protected override void OnPointerReleased(PointerReleasedEventArgs e)
|
||||
|
||||
@@ -81,6 +81,8 @@ public static class Palette
|
||||
public static readonly IBrush LampOn = Brush("#4cc46e");
|
||||
public static readonly IBrush LampWarning = Brush("#e8c547");
|
||||
public static readonly IBrush LampAlarm = Brush("#f0584a");
|
||||
/// <summary>The train protection's buzzer: still to be acknowledged, not braking yet.</summary>
|
||||
public static readonly IBrush Buzzer = Brush("#c77dff");
|
||||
public static readonly IBrush LightWhite = Brush("#fff6d8");
|
||||
public static readonly IBrush LightRed = Brush("#ff3b30");
|
||||
public static readonly IBrush Command = Brush("#8b96a3");
|
||||
|
||||
@@ -309,16 +309,16 @@ public sealed class TimelineView : Control
|
||||
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
|
||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||
{
|
||||
// The alerter and the cab signalling apart, red when not acknowledged in time.
|
||||
rows[3].Add(x0, x1, s.Has(SecurityFlags.VigilanceBeeping) ? Palette.LampAlarm
|
||||
// The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked.
|
||||
rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer
|
||||
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
|
||||
rows[4].Add(x0, x1, s.Has(SecurityFlags.CabSignalBeeping) ? Palette.LampAlarm
|
||||
rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer
|
||||
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
|
||||
if (s.Has(SecurityFlags.Braking))
|
||||
if (s.ProtectionBraking)
|
||||
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
|
||||
}
|
||||
else
|
||||
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
||||
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
|
||||
// Where the user looked from: the samples go on in time, and so does the camera.
|
||||
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
|
||||
@@ -590,7 +590,8 @@ public sealed class TimelineView : Control
|
||||
foreach (var d in recording.DriverChanges)
|
||||
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
|
||||
foreach (var c in recording.UserCommands())
|
||||
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], c.Name));
|
||||
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"],
|
||||
Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
184
Eu07.BlackBox.Views/TrackLayer.cs
Normal file
184
Eu07.BlackBox.Views/TrackLayer.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using Avalonia;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace Eu07.BlackBox.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The rails of a scenery made ready to draw fast: cut into square cells so that only those in
|
||||
/// view are drawn, and kept at a few levels of detail so that from afar a track is drawn with
|
||||
/// fewer points than there are pixels it covers. The casing takes the switches' ways too, which
|
||||
/// it is drawn under in one colour; the fill is the plain tracks alone.
|
||||
/// </summary>
|
||||
public sealed class TrackLayer
|
||||
{
|
||||
/// <summary>The side of a cell in metres.</summary>
|
||||
public const double CellSize = 500;
|
||||
|
||||
/// <summary>The points of a track closer than this to the last kept are left out, by level.</summary>
|
||||
public static readonly double[] Tolerances = { 0, 2, 8, 32, 128 };
|
||||
|
||||
/// <summary>A part of the map: what is drawn of it, and where it lies in the map's plane.</summary>
|
||||
public sealed record Cell(Rect Bounds, StreamGeometry Casing, StreamGeometry? Fill);
|
||||
|
||||
private readonly List<Cell>[] _levels;
|
||||
|
||||
public TrackLayer(IReadOnlyList<MapTrack> tracks)
|
||||
{
|
||||
_levels = new List<Cell>[Tolerances.Length];
|
||||
for (int level = 0; level < Tolerances.Length; level++)
|
||||
_levels[level] = BuildLevel(tracks, Tolerances[level]);
|
||||
}
|
||||
|
||||
/// <summary>The level whose left-out points stay within <paramref name="pixels"/> on screen at this scale.</summary>
|
||||
public static int LevelFor(double scale, double pixels = 0.75)
|
||||
{
|
||||
int level = 0;
|
||||
for (int i = 1; i < Tolerances.Length; i++)
|
||||
if (Tolerances[i] * scale <= pixels)
|
||||
level = i;
|
||||
return level;
|
||||
}
|
||||
|
||||
/// <summary>The cells of the level that reach into <paramref name="view"/>, a rectangle of the map's plane.</summary>
|
||||
public IEnumerable<Cell> CellsIn(Rect view, int level)
|
||||
{
|
||||
foreach (var cell in _levels[Math.Clamp(level, 0, _levels.Length - 1)])
|
||||
if (cell.Bounds.Intersects(view))
|
||||
yield return cell;
|
||||
}
|
||||
|
||||
public int CellCount(int level) => _levels[level].Count;
|
||||
|
||||
/// <summary>The points of a track with those nearer than <paramref name="tolerance"/> to the last kept left out; its ends stay.</summary>
|
||||
public static List<Vector3> Simplified(IReadOnlyList<Vector3> points, double tolerance)
|
||||
{
|
||||
var kept = new List<Vector3>(points.Count);
|
||||
if (points.Count == 0)
|
||||
return kept;
|
||||
kept.Add(points[0]);
|
||||
double square = tolerance * tolerance;
|
||||
for (int i = 1; i < points.Count - 1; i++)
|
||||
{
|
||||
var last = kept[^1];
|
||||
double dx = points[i].X - last.X, dz = points[i].Z - last.Z;
|
||||
if (dx * dx + dz * dz >= square)
|
||||
kept.Add(points[i]);
|
||||
}
|
||||
if (points.Count > 1)
|
||||
kept.Add(points[^1]);
|
||||
return kept;
|
||||
}
|
||||
|
||||
private sealed class Builder
|
||||
{
|
||||
public readonly List<List<Point>> Casing = new();
|
||||
public readonly List<List<Point>> Fill = new();
|
||||
public double Left = double.MaxValue, Top = double.MaxValue, Right = double.MinValue, Bottom = double.MinValue;
|
||||
|
||||
public void Grow(Point p)
|
||||
{
|
||||
Left = Math.Min(Left, p.X);
|
||||
Right = Math.Max(Right, p.X);
|
||||
Top = Math.Min(Top, p.Y);
|
||||
Bottom = Math.Max(Bottom, p.Y);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Cell> BuildLevel(IReadOnlyList<MapTrack> tracks, double tolerance)
|
||||
{
|
||||
var cells = new Dictionary<(long, long), Builder>();
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
if (track.Points.Count < 2)
|
||||
continue;
|
||||
bool fill = track.Kind != TrackKind.SwitchBranch;
|
||||
var points = tolerance > 0 ? Simplified(track.Points, tolerance) : (IReadOnlyList<Vector3>)track.Points;
|
||||
|
||||
// A run of the track's points in one cell; a segment over a border goes with the cell it ends in,
|
||||
// which starts from the point before, so its bounds cover the whole segment.
|
||||
List<Point>? casingRun = null, fillRun = null;
|
||||
(long, long) current = default;
|
||||
for (int i = 0; i < points.Count; i++)
|
||||
{
|
||||
var p = Plane(points[i]);
|
||||
var key = ((long)Math.Floor(p.X / CellSize), (long)Math.Floor(p.Y / CellSize));
|
||||
if (casingRun is null || key != current)
|
||||
{
|
||||
var builder = Of(cells, key);
|
||||
var start = casingRun is null ? (Point?)null : casingRun[^1];
|
||||
casingRun = new List<Point>();
|
||||
builder.Casing.Add(casingRun);
|
||||
fillRun = null;
|
||||
if (fill)
|
||||
{
|
||||
fillRun = new List<Point>();
|
||||
builder.Fill.Add(fillRun);
|
||||
}
|
||||
if (start is { } joined)
|
||||
{
|
||||
// The segment from the last cell starts there, so the line has no gap at the border.
|
||||
casingRun.Add(joined);
|
||||
fillRun?.Add(joined);
|
||||
builder.Grow(joined);
|
||||
}
|
||||
current = key;
|
||||
}
|
||||
casingRun.Add(p);
|
||||
fillRun?.Add(p);
|
||||
Of(cells, key).Grow(p);
|
||||
}
|
||||
}
|
||||
|
||||
var result = new List<Cell>(cells.Count);
|
||||
foreach (var builder in cells.Values)
|
||||
{
|
||||
var casing = Geometry(builder.Casing);
|
||||
if (casing is null)
|
||||
continue;
|
||||
var bounds = new Rect(new Point(builder.Left, builder.Top), new Point(builder.Right, builder.Bottom));
|
||||
result.Add(new Cell(bounds, casing, Geometry(builder.Fill)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Builder Of(Dictionary<(long, long), Builder> cells, (long, long) key)
|
||||
{
|
||||
if (!cells.TryGetValue(key, out var builder))
|
||||
cells[key] = builder = new Builder();
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static StreamGeometry? Geometry(List<List<Point>> runs)
|
||||
{
|
||||
StreamGeometry? geometry = null;
|
||||
StreamGeometryContext? g = null;
|
||||
try
|
||||
{
|
||||
foreach (var run in runs)
|
||||
{
|
||||
if (run.Count < 2)
|
||||
continue;
|
||||
if (geometry is null)
|
||||
{
|
||||
geometry = new StreamGeometry();
|
||||
g = geometry.Open();
|
||||
}
|
||||
g!.BeginFigure(run[0], false);
|
||||
for (int i = 1; i < run.Count; i++)
|
||||
g.LineTo(run[i]);
|
||||
g.EndFigure(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
g?.Dispose();
|
||||
}
|
||||
return geometry;
|
||||
}
|
||||
|
||||
// As MapView draws the plane: x to the left, z up the screen.
|
||||
private static Point Plane(Vector3 p) => new(-p.X, -p.Z);
|
||||
}
|
||||
@@ -172,6 +172,9 @@ public sealed class BlackBoxReader
|
||||
Extra = new CabExtra((EngineKind)r.U8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(),
|
||||
r.F32(), r.F32(), r.F32(), r.I8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32())
|
||||
};
|
||||
// The speed of the wheels, later again.
|
||||
if (sample.Extra is not null && r.Remaining >= 4)
|
||||
sample = sample with { WheelSpeedKmh = r.F32() };
|
||||
rec.AddCab(sample);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -520,7 +520,13 @@ public sealed class Recording
|
||||
}
|
||||
|
||||
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
|
||||
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.Has(SecurityFlags.Braking));
|
||||
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.ProtectionBraking);
|
||||
|
||||
/// <summary>
|
||||
/// When the train protection's buzzer sounded in the user's cab: a lamp not acknowledged in time, the braking to
|
||||
/// follow unless acknowledged on. Until it ends, braking included.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TimeSpanRange> SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer);
|
||||
|
||||
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
|
||||
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
|
||||
|
||||
@@ -366,11 +366,50 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit
|
||||
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
||||
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
||||
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
|
||||
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null)
|
||||
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null,
|
||||
float? WheelSpeedKmh = null)
|
||||
{
|
||||
// WheelSpeedKmh: the speed of the wheels as they turn, which the speedometer shows, signed as SpeedKmh; apart
|
||||
// from it while they slip, 0 while they are locked in a skid. None in a recording made before it.
|
||||
|
||||
public bool Has(CabDevices device) => (Devices & device) == device;
|
||||
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
||||
|
||||
/// <summary>
|
||||
/// The alerter's buzzer: its lamp not acknowledged in time. A protection with one acknowledgement for both tells
|
||||
/// the cab signalling's buzzer as the alerter's too, so the alerter's lamp has to blink with it.
|
||||
/// </summary>
|
||||
public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance);
|
||||
|
||||
/// <summary>The cab signalling's buzzer: its lamp not acknowledged in time.</summary>
|
||||
public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping);
|
||||
|
||||
/// <summary>
|
||||
/// The train protection braking for an alarm not acknowledged, its lamp blinking. Braking with no lamp is the
|
||||
/// protection with no power (TSecuritySystem::is_braking), a cab not started or a power cut: no driver's fault.
|
||||
/// </summary>
|
||||
public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal));
|
||||
|
||||
private const CabDevices LeftDoors = CabDevices.DoorsLeft | CabDevices.DoorPermitLeft;
|
||||
private const CabDevices RightDoors = CabDevices.DoorsRight | CabDevices.DoorPermitRight;
|
||||
|
||||
/// <summary>
|
||||
/// The doors as the driver has them: the recording holds the left and right of the vehicle, and from its rear
|
||||
/// cab the driver's left is the vehicle's right, as the simulator works the doors from it. Out of a cab, the
|
||||
/// vehicle's.
|
||||
/// </summary>
|
||||
public CabSample AsTheCabSees =>
|
||||
CabEnd >= 0
|
||||
? this
|
||||
: this with
|
||||
{
|
||||
Devices = (Devices & ~(LeftDoors | RightDoors))
|
||||
| ((Devices & CabDevices.DoorsLeft) != 0 ? CabDevices.DoorsRight : 0)
|
||||
| ((Devices & CabDevices.DoorsRight) != 0 ? CabDevices.DoorsLeft : 0)
|
||||
| ((Devices & CabDevices.DoorPermitLeft) != 0 ? CabDevices.DoorPermitRight : 0)
|
||||
| ((Devices & CabDevices.DoorPermitRight) != 0 ? CabDevices.DoorPermitLeft : 0)
|
||||
};
|
||||
|
||||
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
|
||||
public bool InCab => (Flags & CabFlags.InCab) != 0;
|
||||
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
|
||||
|
||||
@@ -109,7 +109,7 @@ internal sealed class BlackBoxFile
|
||||
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
|
||||
float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null,
|
||||
short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null,
|
||||
byte? engine = null, float oilTemperature = 70) =>
|
||||
byte? engine = null, float oilTemperature = 70, float? wheelSpeed = null) =>
|
||||
Record(0x20, w =>
|
||||
{
|
||||
w.Write(time);
|
||||
@@ -181,6 +181,9 @@ internal sealed class BlackBoxFile
|
||||
w.Write(1.0f); // clutch
|
||||
w.Write(0.0f); // torque converter
|
||||
w.Write(2.5f); // the highest brake cylinder of the train
|
||||
// the speed of the wheels: a recording made before it ends above
|
||||
if (wheelSpeed is { } wheels)
|
||||
w.Write(wheels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,13 +60,15 @@ public class BlackBoxListingTests
|
||||
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
|
||||
{
|
||||
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
// named in the local time they started at, whatever the zone the tests run in
|
||||
string first = Box("td", early.AddHours(-1)), second = Box("td", early.AddMinutes(30));
|
||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||
.WithFile(Log("a.dat"), "t")
|
||||
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
|
||||
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
|
||||
.WithFile(Log(first), "b")
|
||||
.WithFile(Log(second), "b")
|
||||
.WrittenAt(Log("a.dat"), early)
|
||||
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
|
||||
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
|
||||
.WrittenAt(Log(first), early.AddSeconds(2))
|
||||
.WrittenAt(Log(second), early.AddHours(1)));
|
||||
|
||||
var sessions = installation.Tapes.Sessions();
|
||||
|
||||
@@ -74,12 +76,59 @@ public class BlackBoxListingTests
|
||||
Assert.All(sessions, session => Assert.Null(session.Launch));
|
||||
// Newest first: the black box on its own, then the run with the tape.
|
||||
Assert.Empty(sessions[0].Tapes);
|
||||
Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path);
|
||||
Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path);
|
||||
Assert.Single(sessions[1].Tapes);
|
||||
Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path);
|
||||
Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path);
|
||||
Assert.Equal(early, sessions[1].StartedUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_tape_of_a_vehicle_left_early_in_a_run_with_no_launch_goes_with_its_black_box()
|
||||
{
|
||||
// The black box writes the tapes as it goes: that of the vehicle the player left after ten minutes ends
|
||||
// twenty minutes before the run, that of the next one with it.
|
||||
var started = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
string box = Box("td", started);
|
||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||
.WithFile(Log("first.dat"), "t")
|
||||
.WithFile(Log("second.dat"), "t")
|
||||
.WithFile(Log(box), "b")
|
||||
.WrittenAt(Log("first.dat"), started.AddMinutes(10))
|
||||
.WrittenAt(Log(box), started.AddMinutes(30))
|
||||
.WrittenAt(Log("second.dat"), started.AddMinutes(30).AddSeconds(1)));
|
||||
|
||||
var session = Assert.Single(installation.Tapes.Sessions());
|
||||
|
||||
Assert.Null(session.Launch);
|
||||
Assert.Equal(new[] { "first", "second" }, session.Tapes.Select(tape => tape.Vehicle).Order());
|
||||
Assert.EndsWith(box, Assert.Single(session.BlackBoxes).Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_black_box_downloaded_later_takes_in_no_tapes_of_the_runs_after_it()
|
||||
{
|
||||
// Shared and downloaded two weeks later, so last written then; a run of its own with no launch noted since.
|
||||
var shared = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
var later = shared.AddDays(7);
|
||||
string old = Box("td", shared), own = Box("td", later);
|
||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||
.WithFile(Log(old), "b").WrittenAt(Log(old), shared.AddDays(14))
|
||||
.WithFile(Log(own), "b").WrittenAt(Log(own), later.AddMinutes(30))
|
||||
.WithFile(Log("ra.dat"), "t").WrittenAt(Log("ra.dat"), later.AddMinutes(30).AddSeconds(1))
|
||||
.WithFile(Log("left.dat"), "t").WrittenAt(Log("left.dat"), later.AddMinutes(10)));
|
||||
|
||||
var recordings = StarterNG.Application.HaslerTapes.Recordings(new[]
|
||||
{
|
||||
new StarterNG.Application.BlackBoxRecording(Log(old), shared.AddDays(14), 1),
|
||||
new StarterNG.Application.BlackBoxRecording(Log(own), later.AddMinutes(30), 1),
|
||||
});
|
||||
Assert.EndsWith(own, StarterNG.Application.HaslerTapes.RecordingAt(later.AddMinutes(10), recordings)!.Path);
|
||||
|
||||
var mine = Assert.Single(installation.Tapes.Sessions(), session => session.Tapes.Count > 0);
|
||||
Assert.Equal(new[] { "left", "ra" }, mine.Tapes.Select(tape => tape.Vehicle).Order());
|
||||
Assert.EndsWith(own, Assert.Single(mine.BlackBoxes).Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
|
||||
{
|
||||
|
||||
@@ -125,6 +125,20 @@ public class HeadCodeTests
|
||||
Assert.Null(cab[1].Extra);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_speed_of_the_wheels_is_read_when_written()
|
||||
{
|
||||
var f = new BlackBoxFile().Info();
|
||||
// the wheels slipping at 40 km/h
|
||||
f.Cab(0, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1, wheelSpeed: 55.5f);
|
||||
f.Cab(0.5, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1);
|
||||
var cab = BlackBoxReader.Read(f.End(1).Stream()).Cab;
|
||||
Assert.Equal(55.5f, cab[0].WheelSpeedKmh);
|
||||
Assert.Equal(40f, cab[0].SpeedKmh);
|
||||
// an older sample has none
|
||||
Assert.Null(cab[1].WheelSpeedKmh);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_vehicle_with_no_lamps_is_not_judged()
|
||||
{
|
||||
|
||||
@@ -222,6 +222,34 @@ public class BlackBoxViewsTests
|
||||
Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wheels_turning_apart_from_the_train_are_said_beside_its_speed()
|
||||
{
|
||||
var f = new BlackBoxFile().Info()
|
||||
.Vehicle(Head, "EU07-005", "ROJ1")
|
||||
.User(0, Head, true, 1);
|
||||
// slipping for the first ten seconds, then the wheels as fast as the train, give or take the rounding
|
||||
for (double t = 0; t <= 20; t += 0.5)
|
||||
f.Cab(t, Head, 1150 + t * 10, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1,
|
||||
wheelSpeed: t < 10 ? 55.4f : 40.3f);
|
||||
var cab = new CabPanel
|
||||
{
|
||||
Recording = BlackBoxReader.Read(f.End(20).Stream()),
|
||||
Strings = new DefaultBlackBoxStrings("en"),
|
||||
Time = 5
|
||||
};
|
||||
Controls.Lay(cab, 600, 900);
|
||||
|
||||
Controls.Draw(cab);
|
||||
Assert.Contains("40 km/h", cab.Said);
|
||||
Assert.Contains("wheels 55", cab.Said);
|
||||
|
||||
cab.Time = 15;
|
||||
Controls.Draw(cab);
|
||||
Assert.Contains("40 km/h", cab.Said);
|
||||
Assert.DoesNotContain("wheels", cab.Said);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
|
||||
{
|
||||
|
||||
49
StarterNG.Tests/BlackBox/CabDoorsTests.cs
Normal file
49
StarterNG.Tests/BlackBox/CabDoorsTests.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using Eu07.BlackBox;
|
||||
using Eu07.BlackBox.Views;
|
||||
|
||||
namespace StarterNG.Tests.BlackBox;
|
||||
|
||||
// The events are coloured with the views' brushes.
|
||||
[Collection(AvaloniaControls.Name)]
|
||||
public class CabDoorsTests
|
||||
{
|
||||
private static CabSample Sample(sbyte cab, CabDevices devices) =>
|
||||
default(CabSample) with { CabEnd = cab, Devices = devices | CabDevices.Radio };
|
||||
|
||||
[Fact]
|
||||
public void From_the_rear_cab_the_vehicles_right_doors_are_the_drivers_left()
|
||||
{
|
||||
var seen = Sample(-1, CabDevices.DoorsRight | CabDevices.DoorPermitRight).AsTheCabSees;
|
||||
|
||||
Assert.True(seen.Has(CabDevices.DoorsLeft));
|
||||
Assert.True(seen.Has(CabDevices.DoorPermitLeft));
|
||||
Assert.False(seen.Has(CabDevices.DoorsRight));
|
||||
Assert.False(seen.Has(CabDevices.DoorPermitRight));
|
||||
Assert.True(seen.Has(CabDevices.Radio));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(0)]
|
||||
public void From_the_front_cab_or_out_of_one_the_sides_are_the_vehicles(sbyte cab)
|
||||
{
|
||||
var sample = Sample(cab, CabDevices.DoorsLeft | CabDevices.DoorPermitRight);
|
||||
|
||||
Assert.Equal(sample, sample.AsTheCabSees);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Going_to_the_other_cab_tells_nothing_of_the_doors_and_still_tells_the_switches()
|
||||
{
|
||||
var f = new BlackBoxFile().Info().Vehicle(1, "EN57-1001").User(0, 1, true);
|
||||
// the left doors permitted from the front cab; in the rear one the permit is still on, and the radio turned off
|
||||
f.Cab(0, 1, 1000, 0, cabEnd: 1, devices: 0x0007 | (uint)(CabDevices.DoorPermitLeft | CabDevices.Radio));
|
||||
f.Cab(1, 1, 1000, 0, cabEnd: -1, devices: 0x0007 | (uint)CabDevices.DoorPermitLeft);
|
||||
|
||||
var events = EventList.Collect(BlackBoxReader.Read(f.End(1).Stream()), new DefaultBlackBoxStrings("en"))
|
||||
.Select(e => e.Text).ToList();
|
||||
|
||||
Assert.Contains("Radio: off", events);
|
||||
Assert.DoesNotContain(events, e => e.Contains("doors permitted"));
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
55
StarterNG.Tests/ColumnLineTests.cs
Normal file
55
StarterNG.Tests/ColumnLineTests.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using Avalonia;
|
||||
using StarterNG.Views.Tapes;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
/// <summary>The line of a tape, drawn a column of pixels at a time and broken off at a gap.</summary>
|
||||
public class ColumnLineTests
|
||||
{
|
||||
private readonly List<string> _drawn = [];
|
||||
|
||||
private ColumnLine Line() =>
|
||||
new(p => _drawn.Add($"begin {p.X} {p.Y}"), p => _drawn.Add($"line {p.X} {p.Y}"), () => _drawn.Add("end"));
|
||||
|
||||
[Fact]
|
||||
public void A_column_is_entered_where_it_started_and_left_where_it_ended_through_its_lowest_and_highest()
|
||||
{
|
||||
var line = Line();
|
||||
|
||||
// Falling within the column: from its first through its highest and its lowest to its last.
|
||||
foreach (double v in new[] { 3.0, 1.0, 4.0, 2.0 })
|
||||
line.Add(5, v);
|
||||
// Rising: through its lowest first.
|
||||
foreach (double v in new[] { 2.0, 4.0, 1.0, 3.0 })
|
||||
line.Add(6, v);
|
||||
line.Break();
|
||||
|
||||
Assert.Equal(["begin 5 3", "line 5 4", "line 5 1", "line 5 2",
|
||||
"line 6 2", "line 6 1", "line 6 4", "line 6 3", "end"], _drawn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_break_ends_the_figure_and_the_next_point_begins_another()
|
||||
{
|
||||
var line = Line();
|
||||
|
||||
line.Add(0, 10);
|
||||
line.Break();
|
||||
line.Add(9, 20);
|
||||
line.Break();
|
||||
|
||||
Assert.Equal(["begin 0 10", "line 0 10", "line 0 10", "line 0 10", "end",
|
||||
"begin 9 20", "line 9 20", "line 9 20", "line 9 20", "end"], _drawn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_break_with_nothing_drawn_ends_nothing()
|
||||
{
|
||||
var line = Line();
|
||||
|
||||
line.Break();
|
||||
line.Break();
|
||||
|
||||
Assert.Empty(_drawn);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ using StarterNG.Tests.Fakes;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
// Puts in services of its own: not while the controls read theirs.
|
||||
[Collection(AvaloniaControls.Name)]
|
||||
public class ConsistOrientationTests
|
||||
{
|
||||
private readonly VehicleCatalog _catalog;
|
||||
|
||||
68
StarterNG.Tests/ConsistRunsTests.cs
Normal file
68
StarterNG.Tests/ConsistRunsTests.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using StarterNG.Classes;
|
||||
using StarterNG.Domain;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
public class ConsistRunsTests
|
||||
{
|
||||
private static List<Dynamic> Vehicles(params string[] skins) =>
|
||||
new Trainset(string.Concat(
|
||||
"trainset a tor 0 0\n",
|
||||
string.Concat(skins.Select((s, i) => $"node -1 0 v{i} dynamic d {s} m 0 nobody 3 0 enddynamic\n")),
|
||||
"endtrainset")).Vehicles;
|
||||
|
||||
private static List<(string Skin, int Count)> Runs(List<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf) =>
|
||||
ConsistRuns.Of(vehicles, keyOf).Select(r => (r.First.SkinFile!, r.Count)).ToList();
|
||||
|
||||
[Fact]
|
||||
public void Vehicles_alike_next_to_each_other_make_one_run()
|
||||
{
|
||||
var vehicles = Vehicles("eu07", "412w", "412w", "412w", "eaos", "eaos");
|
||||
|
||||
Assert.Equal(
|
||||
[("eu07", 1), ("412w", 3), ("eaos", 2)],
|
||||
Runs(vehicles, (v, _) => v.SkinFile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Vehicles_alike_apart_stay_apart()
|
||||
{
|
||||
var vehicles = Vehicles("412w", "eaos", "412w");
|
||||
|
||||
Assert.Equal(
|
||||
[("412w", 1), ("eaos", 1), ("412w", 1)],
|
||||
Runs(vehicles, (v, _) => v.SkinFile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Alike_goes_by_the_key_whatever_its_case()
|
||||
{
|
||||
var vehicles = Vehicles("412W", "412w");
|
||||
|
||||
Assert.Equal([("412W", 2)], Runs(vehicles, (v, _) => v.SkinFile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_vehicle_with_no_key_stands_alone()
|
||||
{
|
||||
var vehicles = Vehicles("x", "x", "x");
|
||||
|
||||
Assert.Equal(
|
||||
[("x", 1), ("x", 1), ("x", 1)],
|
||||
Runs(vehicles, (_, _) => null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_place_in_the_consist_can_set_a_vehicle_apart()
|
||||
{
|
||||
var vehicles = Vehicles("sm42", "sm42", "sm42");
|
||||
|
||||
Assert.Equal(
|
||||
[("sm42", 1), ("sm42", 2)],
|
||||
Runs(vehicles, (v, i) => i == 0 ? "head" : v.SkinFile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void No_vehicles_no_runs() =>
|
||||
Assert.Empty(ConsistRuns.Of([], (v, _) => v.SkinFile));
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
using StarterNG.Infrastructure;
|
||||
using StarterNG.Tests.Fakes;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
public class DisplaysTests
|
||||
{
|
||||
/// <summary>A 128-byte block with an 18-byte timing at 54, as a panel's base EDID has it.</summary>
|
||||
private static byte[] BaseBlock(int pixelClock10KHz, int hActive, int hBlank, int vActive, int vBlank,
|
||||
int extensions = 0)
|
||||
{
|
||||
var edid = new byte[128];
|
||||
new byte[] { 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }.CopyTo(edid, 0);
|
||||
edid[126] = (byte)extensions;
|
||||
int at = 54;
|
||||
edid[at] = (byte)pixelClock10KHz;
|
||||
edid[at + 1] = (byte)(pixelClock10KHz >> 8);
|
||||
edid[at + 2] = (byte)hActive;
|
||||
edid[at + 3] = (byte)hBlank;
|
||||
edid[at + 4] = (byte)((hActive >> 8) << 4 | hBlank >> 8);
|
||||
edid[at + 5] = (byte)vActive;
|
||||
edid[at + 6] = (byte)vBlank;
|
||||
edid[at + 7] = (byte)((vActive >> 8) << 4 | vBlank >> 8);
|
||||
return edid;
|
||||
}
|
||||
|
||||
/// <summary>A DisplayID 2.0 block with one type VII timing (kHz, sizes less one).</summary>
|
||||
private static byte[] DisplayIdBlock(int pixelClockKHz, int hActive, int hBlank, int vActive, int vBlank)
|
||||
{
|
||||
var block = new byte[128];
|
||||
block[0] = 0x70;
|
||||
block[1] = 0x20;
|
||||
block[2] = 23; // one data block: 3 bytes of header, 20 of timing
|
||||
block[3] = 2;
|
||||
int at = 5;
|
||||
block[at] = 0x22;
|
||||
block[at + 2] = 20;
|
||||
int t = at + 3, clock = pixelClockKHz - 1;
|
||||
block[t] = (byte)clock;
|
||||
block[t + 1] = (byte)(clock >> 8);
|
||||
block[t + 2] = (byte)(clock >> 16);
|
||||
void Put(int offset, int value)
|
||||
{
|
||||
block[t + offset] = (byte)(value - 1);
|
||||
block[t + offset + 1] = (byte)((value - 1) >> 8);
|
||||
}
|
||||
Put(4, hActive);
|
||||
Put(6, hBlank);
|
||||
Put(12, vActive);
|
||||
Put(14, vBlank);
|
||||
return block;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_plain_monitor_gives_its_preferred_timing()
|
||||
{
|
||||
// 1920x1080 at 148.5 MHz: the usual 60 Hz.
|
||||
Assert.Equal(60, Edid.HighestRefreshRate(BaseBlock(14850, 1920, 280, 1080, 45)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_fast_panel_found_only_in_displayid_is_read_there()
|
||||
{
|
||||
// As the eDP panel of a gaming laptop: 60 Hz in the base block, 165 Hz in DisplayID.
|
||||
var edid = BaseBlock(15394, 1920, 160, 1200, 35, extensions: 1)
|
||||
.Concat(DisplayIdBlock(423250, 1920, 160, 1200, 33)).ToArray();
|
||||
|
||||
Assert.Equal(165, Edid.HighestRefreshRate(edid));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Something_too_short_for_an_edid_has_no_rate()
|
||||
{
|
||||
Assert.Equal(0, Edid.HighestRefreshRate(new byte[] { 0, 0xFF }));
|
||||
Assert.Equal(0, Edid.HighestRefreshRate(new byte[128]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_connected_screens_are_listed_by_their_connector()
|
||||
{
|
||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||
.WithFile("/sys/class/drm/card1-eDP-1/status", "connected\n")
|
||||
.WithFile("/sys/class/drm/card1-HDMI-A-1/status", "disconnected\n")
|
||||
.WithFile("/sys/class/drm/card1/device/uevent", "DRIVER=amdgpu\n");
|
||||
files.WriteAllBytes("/sys/class/drm/card1-eDP-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
|
||||
files.WriteAllBytes("/sys/class/drm/card1-HDMI-A-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
|
||||
|
||||
var displays = new Displays(files, new FakeEnvironment()).List();
|
||||
|
||||
Assert.Equal(new[] { new Display("eDP-1", 60) }, displays);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Off_linux_without_windows_nothing_is_read()
|
||||
{
|
||||
var environment = new FakeEnvironment { IsLinux = false, IsMacOS = true };
|
||||
|
||||
Assert.Empty(new Displays(new InMemoryFileSystem(), environment).List());
|
||||
}
|
||||
}
|
||||
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 Dictionary<string, string> _links;
|
||||
private readonly HashSet<string> _unreadable;
|
||||
private readonly HashSet<string> _unseekable;
|
||||
private readonly HashSet<string> _unlistable;
|
||||
private readonly Dictionary<string, DateTime> _written;
|
||||
|
||||
@@ -32,6 +33,7 @@ public sealed class InMemoryFileSystem : IFileSystem
|
||||
_executable = new HashSet<string>(comparer);
|
||||
_links = new Dictionary<string, string>(comparer);
|
||||
_unreadable = new HashSet<string>(comparer);
|
||||
_unseekable = new HashSet<string>(comparer);
|
||||
_unlistable = new HashSet<string>(comparer);
|
||||
_written = new Dictionary<string, DateTime>(comparer);
|
||||
}
|
||||
@@ -51,6 +53,13 @@ public sealed class InMemoryFileSystem : IFileSystem
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>The file opens as a stream read only forward, as a pipe or some network shares give it.</summary>
|
||||
public InMemoryFileSystem OpenedForwardOnly(string path)
|
||||
{
|
||||
_unseekable.Add(Normalize(path));
|
||||
return this;
|
||||
}
|
||||
|
||||
public InMemoryFileSystem AllowReading(string path)
|
||||
{
|
||||
_unreadable.Remove(Normalize(path));
|
||||
@@ -115,7 +124,11 @@ public sealed class InMemoryFileSystem : IFileSystem
|
||||
|
||||
public byte[] ReadAllBytes(string path) => Bytes(path);
|
||||
|
||||
public Stream OpenRead(string path) => new MemoryStream(Bytes(path), writable: false);
|
||||
public Stream OpenRead(string path)
|
||||
{
|
||||
var stream = new MemoryStream(Bytes(path), writable: false);
|
||||
return _unseekable.Contains(Normalize(path)) ? new ForwardOnlyStream(stream) : stream;
|
||||
}
|
||||
|
||||
public void WriteAllText(string path, string contents) => WithFile(path, contents);
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ public sealed class TestInstallation
|
||||
{
|
||||
public const string Root = "game";
|
||||
|
||||
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
|
||||
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
|
||||
{
|
||||
Files = files ?? new InMemoryFileSystem();
|
||||
Paths = new GamePaths(Root);
|
||||
@@ -35,7 +35,8 @@ public sealed class TestInstallation
|
||||
SettingsPaths.VehicleCacheDirectory());
|
||||
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
|
||||
|
||||
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
|
||||
// The processor of the machine running the tests is not the one tested.
|
||||
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
|
||||
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
|
||||
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
|
||||
}
|
||||
|
||||
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 low = Defaults().Copy();
|
||||
var top = Defaults().Copy();
|
||||
// Ray tracing is one of them, and only Vulkan has it.
|
||||
low.RenderEngine = top.RenderEngine = SimulatorSettings.VulkanEngine;
|
||||
(GraphicsPreset.Minimal with { Extras = null }).ApplyTo(low);
|
||||
(GraphicsPreset.Ultra with { Extras = null, Top = null }).ApplyTo(top);
|
||||
|
||||
var lowKeys = store.Render(low);
|
||||
var topKeys = store.Render(top);
|
||||
var differing = lowKeys.Keys.Union(topKeys.Keys)
|
||||
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key))
|
||||
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal));
|
||||
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key));
|
||||
|
||||
Assert.Equal(GraphicsPreset.Keys.OrderBy(k => k), differing.OrderBy(k => k));
|
||||
}
|
||||
@@ -55,7 +52,7 @@ public class GraphicsPresetTests
|
||||
{
|
||||
// Sizes and filtering run out of steps above High.
|
||||
Climbs(p => p.TextureSize, 1);
|
||||
Climbs(p => p.CabTextureSize, 1);
|
||||
Climbs(p => p.CabTextureSize, 2);
|
||||
Climbs(p => p.Anisotropy, 1);
|
||||
|
||||
// Four steps or three for six levels.
|
||||
@@ -65,28 +62,23 @@ public class GraphicsPresetTests
|
||||
Climbs(p => p.ReflectionsFidelity, 3);
|
||||
Climbs(p => p.ShadowRank, 3);
|
||||
|
||||
// The simulator takes no more than its own 7 lights, and draws no less than 2 km.
|
||||
// The simulator takes no more than its own 7 lights.
|
||||
Climbs(p => p.DynamicLights, 2);
|
||||
Climbs(p => p.DrawRange, 1);
|
||||
Climbs(p => p.DrawRangeFactor, 2);
|
||||
Climbs(p => p.DrawRangeFactor, 3);
|
||||
Climbs(p => p.CabShadowsRange, 1);
|
||||
|
||||
Climbs(p => p.ShadowMap, 1);
|
||||
Climbs(p => p.ShadowRange, 0);
|
||||
Climbs(p => p.ReflectionsRate, 0);
|
||||
Climbs(p => p.DistanceFactor, 0);
|
||||
Climbs(p => p.BufferScale, 0);
|
||||
Climbs(p => p.SleeperDistance, 0);
|
||||
Climbs(p => p.ReflectedInstances, 0);
|
||||
Climbs(p => p.ReflectedVehicles, 0);
|
||||
Climbs(p => p.ShadowMap, 2);
|
||||
Climbs(p => p.ShadowRange, 1);
|
||||
// The old starter's steps begin at once a second: the lower levels share it.
|
||||
Climbs(p => p.ReflectionsRate, 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void No_step_up_a_scale_is_more_than_a_few_steps_of_its_slider()
|
||||
{
|
||||
// In steps of what the screen offers, so Ultra does not jump to the top from far below.
|
||||
var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(Steps.ReflectionUpdates, p.ReflectionsRate)).ToList();
|
||||
Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 1, 4));
|
||||
var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(SliderRanges.ReflectionUpdates, p.ReflectionsRate)).ToList();
|
||||
Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 0, 2));
|
||||
|
||||
foreach (Func<GraphicsPreset, int> fidelity in new Func<GraphicsPreset, int>[] { p => p.SmokeFidelity, p => p.SplineFidelity })
|
||||
{
|
||||
@@ -103,9 +95,7 @@ public class GraphicsPresetTests
|
||||
var high = store.Render(AtHigh());
|
||||
|
||||
var differing = own.Keys.Union(high.Keys)
|
||||
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key))
|
||||
.Where(key => !GraphicsPreset.RowKeys.Contains(key))
|
||||
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal) && key != "gfx.buffer.percent");
|
||||
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key));
|
||||
|
||||
Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range",
|
||||
"gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k));
|
||||
@@ -128,6 +118,8 @@ public class GraphicsPresetTests
|
||||
var again = new TestInstallation(installation.Files).SettingsStore;
|
||||
again.Load();
|
||||
Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(again.Settings));
|
||||
// Nothing of an older starter to bring into the standard mode.
|
||||
Assert.True(again.Settings.MovedToStandard);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -144,158 +136,102 @@ public class GraphicsPresetTests
|
||||
again.StartAtHighWithoutOwnSettings();
|
||||
|
||||
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(again.Settings));
|
||||
Assert.False(again.Settings.MovedToStandard);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void High_is_what_the_new_simulator_does_with_nothing_set()
|
||||
public void A_copy_of_the_file_is_kept_once_and_not_written_over()
|
||||
{
|
||||
Assert.Equal(GraphicsPreset.High.NewRenderer, GraphicsNewRenderer.Of(Defaults()));
|
||||
var installation = new TestInstallation();
|
||||
var store = installation.SettingsStore;
|
||||
store.Load();
|
||||
store.Settings.FieldOfView = 50;
|
||||
store.Save();
|
||||
string copy = store.SavePath + ".before-standard";
|
||||
|
||||
store.KeepCopy(".before-standard");
|
||||
string first = installation.Files.ReadAllText(copy);
|
||||
Assert.Equal(installation.Files.ReadAllText(store.SavePath), first);
|
||||
|
||||
store.Settings.FieldOfView = 60;
|
||||
store.Save();
|
||||
store.KeepCopy(".before-standard");
|
||||
Assert.Equal(first, installation.Files.ReadAllText(copy));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_new_renderers_scales_never_go_down()
|
||||
{
|
||||
void NeverDown(Func<GraphicsNewRenderer, double> value) => Climbs(p => value(p.NewRenderer), 5);
|
||||
|
||||
void TurnsOn(Func<GraphicsNewRenderer, bool> on)
|
||||
{
|
||||
var values = GraphicsPreset.All.Select(p => on(p.NewRenderer)).ToList();
|
||||
Assert.Equal(values.OrderBy(value => value), values);
|
||||
}
|
||||
|
||||
NeverDown(r => r.LampShadows);
|
||||
NeverDown(r => r.ContactShadows);
|
||||
NeverDown(r => r.Occlusion);
|
||||
NeverDown(r => r.OcclusionSlices);
|
||||
NeverDown(r => r.OcclusionSteps);
|
||||
NeverDown(r => r.CabProbe);
|
||||
NeverDown(r => r.ScreenReflections);
|
||||
NeverDown(r => r.FogQuality);
|
||||
NeverDown(r => r.Clouds);
|
||||
|
||||
TurnsOn(r => r.OcclusionLighting);
|
||||
TurnsOn(r => r.CabProbeReflections);
|
||||
TurnsOn(r => r.RayTracing);
|
||||
TurnsOn(r => r.VolumetricFog);
|
||||
TurnsOn(r => r.CloudShadows);
|
||||
TurnsOn(r => r.Grass);
|
||||
TurnsOn(r => r.Bloom);
|
||||
|
||||
Climbs(p => p.NewRenderer.GrassDistance, 0);
|
||||
Climbs(p => p.NewRenderer.GrassDensity, 0);
|
||||
Climbs(p => p.NewRenderer.Precipitation, 1);
|
||||
// Frames between refreshes, so the dearer the fewer.
|
||||
Climbs(p => -p.NewRenderer.CabProbeInterval, 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ultra_is_the_top_of_the_new_renderers_scales()
|
||||
{
|
||||
var ultra = GraphicsPreset.Ultra.NewRenderer;
|
||||
|
||||
Assert.Equal(3, ultra.LampShadows);
|
||||
Assert.Equal(3, ultra.ContactShadows);
|
||||
Assert.Equal(2, ultra.Occlusion);
|
||||
Assert.Equal((6, 8), (ultra.OcclusionSlices, ultra.OcclusionSteps));
|
||||
Assert.Equal(3, ultra.CabProbe);
|
||||
Assert.Equal(3, ultra.ScreenReflections);
|
||||
Assert.True(ultra.RayTracing && ultra.VolumetricFog);
|
||||
Assert.Equal(4, ultra.FogQuality);
|
||||
Assert.Equal(4, ultra.Clouds);
|
||||
Assert.Equal(300, ultra.GrassDistance);
|
||||
Assert.Equal(2.0, ultra.GrassDensity);
|
||||
Assert.Equal(262144, ultra.Precipitation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Grass_fades_out_beyond_where_it_is_drawn_in_full()
|
||||
{
|
||||
var store = new TestInstallation().SettingsStore;
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
preset.ApplyTo(settings);
|
||||
|
||||
Assert.True(int.Parse(store.Render(settings)["gfx.grass.fadedistance"]) > preset.NewRenderer.GrassDistance, preset.NameKey);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_level_set_in_the_new_renderers_rows_is_told_from_the_others()
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
GraphicsPreset.Medium.ApplyTo(settings);
|
||||
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
||||
|
||||
settings.FogQuality = 4;
|
||||
|
||||
Assert.Null(GraphicsPreset.Matching(settings));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void What_is_left_to_the_player_stays_through_a_level()
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
settings.RenderEngine = SimulatorSettings.VulkanEngine;
|
||||
settings.AntiAliasing = AntiAliasingMode.Dlss;
|
||||
settings.FrameGeneration = 2;
|
||||
settings.VulkanDevice = "RTX";
|
||||
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
preset.ApplyTo(settings);
|
||||
|
||||
Assert.Same(preset, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(AntiAliasingMode.Dlss, settings.AntiAliasing);
|
||||
Assert.Equal(2, settings.FrameGeneration);
|
||||
Assert.Equal("RTX", settings.VulkanDevice);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ultra_is_the_top_of_everything_the_screen_offers()
|
||||
public void Ultra_is_the_top_of_what_the_old_starter_offered()
|
||||
{
|
||||
var ultra = GraphicsPreset.Ultra;
|
||||
double Top(string key) => SimulatorKeys.Named(key).Maximum;
|
||||
|
||||
Assert.Equal(8192, ultra.TextureSize);
|
||||
Assert.Equal(8192, ultra.CabTextureSize);
|
||||
Assert.Equal(GraphicsRules.MaxCabTextureSize, ultra.CabTextureSize);
|
||||
Assert.Equal(8192, ultra.ShadowMap);
|
||||
Assert.Equal(600, ultra.ShadowRange);
|
||||
Assert.Equal(GraphicsRules.MaxShadowRange, ultra.ShadowRange);
|
||||
Assert.Equal(Steps.Anisotropy.Max(), ultra.Anisotropy);
|
||||
Assert.Equal(AntiAliasingMode.Msaa8, ultra.AntiAliasing);
|
||||
Assert.Equal(Steps.ReflectionUpdates.Max(), ultra.ReflectionsRate);
|
||||
Assert.Equal(SliderRanges.ReflectionUpdates.Max(), ultra.ReflectionsRate);
|
||||
Assert.Equal(4, ultra.SmokeFidelity);
|
||||
Assert.Equal(4, ultra.SplineFidelity);
|
||||
Assert.Equal(200, ultra.BufferScale);
|
||||
Assert.Equal(Top(GraphicsPreset.DrawRangeKey), ultra.DrawRange);
|
||||
Assert.Equal(Top(GraphicsPreset.DistanceFactorKey), ultra.DistanceFactor);
|
||||
Assert.Equal(Top(GraphicsPreset.SleeperKey), ultra.SleeperDistance);
|
||||
Assert.Equal(Steps.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
|
||||
Assert.Equal(Top(GraphicsPreset.ReflectedInstancesKey), ultra.ReflectedInstances);
|
||||
Assert.Equal(Top(GraphicsPreset.ReflectedVehiclesKey), ultra.ReflectedVehicles);
|
||||
Assert.Equal(SliderRanges.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
|
||||
Assert.Equal(100, ultra.CabShadowsRange);
|
||||
|
||||
var extras = ultra.Extras!;
|
||||
Assert.Equal(200, extras.PythonUpdateMs);
|
||||
Assert.True(extras.MotionBlur && extras.ChromaticAberration && extras.Smoke);
|
||||
|
||||
var top = ultra.Top!;
|
||||
Assert.Equal(Top(GraphicsTop.ScreenWindowFpsKey), top.ScreenWindowFps);
|
||||
Assert.True(top.Screens && top.ScreenMipmaps && top.Sky && top.Cab && top.AirCouplers && top.SmoothTraction);
|
||||
Assert.True(ultra.Top!.Screens);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void At_ultra_what_would_only_take_away_is_off()
|
||||
public void No_level_goes_past_what_the_old_starter_gave()
|
||||
{
|
||||
var top = GraphicsPreset.Ultra.Top!;
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
Assert.True(preset.ShadowRange <= GraphicsRules.MaxShadowRange, preset.NameKey);
|
||||
Assert.True(preset.CabTextureSize <= GraphicsRules.MaxCabTextureSize, preset.NameKey);
|
||||
}
|
||||
}
|
||||
|
||||
// The longest shadows, the bottom of that scale.
|
||||
Assert.Equal(0.2, top.ShadowAngleLimit);
|
||||
Assert.Equal(0, top.TargetFps);
|
||||
Assert.Equal(0, top.TextureRelease);
|
||||
Assert.False(top.CompressTextures);
|
||||
Assert.False(top.SkipDecor);
|
||||
[Fact]
|
||||
public void No_level_sets_what_only_the_advanced_mode_shows()
|
||||
{
|
||||
var set = GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys).ToList();
|
||||
|
||||
// The rows of keys by name, the buffer and the resources are all the advanced mode's.
|
||||
Assert.Empty(set.Intersect(SimulatorKeys.All.Select(key => key.Key)));
|
||||
Assert.Empty(set.Intersect(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height",
|
||||
"compresstex", "python.mipmaps", "gfx.skippipeline" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_level_leaves_what_only_the_advanced_mode_shows_as_it_is()
|
||||
{
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
settings.BufferScalePercent = 80;
|
||||
settings.CompressTextures = false;
|
||||
settings.ScreenMipmaps = false;
|
||||
settings.Extra["basedrawrange"] = "3000";
|
||||
settings.Extra["targetfps"] = "60";
|
||||
|
||||
preset.ApplyTo(settings);
|
||||
|
||||
Assert.Equal(80, settings.BufferScalePercent);
|
||||
Assert.False(settings.CompressTextures);
|
||||
Assert.False(settings.ScreenMipmaps);
|
||||
Assert.Equal("3000", settings.Extra["basedrawrange"]);
|
||||
Assert.Equal("60", settings.Extra["targetfps"]);
|
||||
Assert.Same(preset, GraphicsPreset.Matching(settings));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void At_ultra_the_shadows_are_longest()
|
||||
{
|
||||
// The bottom of that scale.
|
||||
Assert.Equal(0.2, GraphicsPreset.Ultra.Top!.ShadowAngleLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -304,16 +240,14 @@ public class GraphicsPresetTests
|
||||
var settings = Defaults().Copy();
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
settings.IgnoreIrrelevantTrains = true;
|
||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
||||
settings.Extra[GraphicsTop.TextureReleaseKey] = "2";
|
||||
settings.PythonScreens = false;
|
||||
|
||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||
|
||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(0.2, settings.ShadowAngleLimit);
|
||||
Assert.False(settings.IgnoreIrrelevantTrains);
|
||||
Assert.Equal("0", settings.Extra[GraphicsTop.TargetFpsKey]);
|
||||
Assert.Equal("0", settings.Extra[GraphicsTop.TextureReleaseKey]);
|
||||
Assert.True(settings.PythonScreens);
|
||||
Assert.True(settings.IgnoreIrrelevantTrains);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -335,12 +269,12 @@ public class GraphicsPresetTests
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
settings.IgnoreIrrelevantTrains = true;
|
||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
|
||||
preset.ApplyTo(settings);
|
||||
|
||||
Assert.True(settings.IgnoreIrrelevantTrains, preset.NameKey);
|
||||
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
|
||||
Assert.Equal(0.8, settings.ShadowAngleLimit);
|
||||
Assert.Same(preset, GraphicsPreset.Matching(settings));
|
||||
}
|
||||
}
|
||||
@@ -352,26 +286,11 @@ public class GraphicsPresetTests
|
||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
||||
|
||||
settings.Extra[GraphicsPreset.ReflectedVehiclesKey] = "250";
|
||||
settings.ReflectionsFramerate = 25;
|
||||
|
||||
Assert.Null(GraphicsPreset.Matching(settings));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void No_level_asks_for_a_range_the_renderer_would_raise_anyway()
|
||||
{
|
||||
Assert.All(GraphicsPreset.All, preset => Assert.True(preset.DrawRange >= 2000, preset.NameKey));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_view_only_shortens_going_down_the_levels()
|
||||
{
|
||||
var factors = GraphicsPreset.All.Select(preset => preset.DistanceFactor).ToList();
|
||||
|
||||
Assert.Equal(factors.OrderBy(factor => factor), factors);
|
||||
Assert.Equal(1, GraphicsPreset.High.DistanceFactor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Shadows_reach_further_with_every_level_that_has_them()
|
||||
{
|
||||
@@ -405,29 +324,17 @@ public class GraphicsPresetTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_level_sets_the_buffer_and_is_not_recognised_with_another()
|
||||
public void Every_level_is_within_what_the_sliders_offer()
|
||||
{
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
settings.BufferScalePercent = 120;
|
||||
|
||||
preset.ApplyTo(settings);
|
||||
Assert.Equal(preset.BufferScale, settings.BufferScalePercent);
|
||||
|
||||
settings.BufferScalePercent = 120;
|
||||
Assert.Null(GraphicsPreset.Matching(settings));
|
||||
Assert.True(preset.TextureSize >= SliderRanges.MinTextureSize, preset.NameKey);
|
||||
Assert.True(preset.ShadowMap >= SliderRanges.MinShadowMap, preset.NameKey);
|
||||
Assert.True(preset.DynamicLights >= SliderRanges.MinDynamicLights, preset.NameKey);
|
||||
Assert.Contains(preset.ReflectionsRate, SliderRanges.ReflectionUpdates);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_buffer_is_the_screen_at_high_and_climbs_through_it()
|
||||
{
|
||||
Assert.Equal(100, GraphicsPreset.High.BufferScale);
|
||||
Assert.Equal(200, GraphicsPreset.Ultra.BufferScale);
|
||||
Assert.InRange(GraphicsPreset.Minimal.BufferScale, 50, 100);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_lowest_level_is_not_recognised_with_one_of_its_extras_undone()
|
||||
{
|
||||
@@ -453,14 +360,13 @@ public class GraphicsPresetTests
|
||||
{
|
||||
var settings = Defaults().Copy();
|
||||
settings.MotionBlur = false;
|
||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
|
||||
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Medium, settings);
|
||||
|
||||
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
||||
Assert.False(settings.MotionBlur);
|
||||
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
|
||||
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
|
||||
Assert.Equal(0.8, settings.ShadowAngleLimit);
|
||||
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
||||
}
|
||||
|
||||
@@ -474,14 +380,12 @@ public class GraphicsPresetTests
|
||||
|
||||
var entering = memory.Apply(GraphicsPreset.Minimal, settings);
|
||||
Assert.Equal(GraphicsPreset.Minimal.Extras, GraphicsExtras.Of(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys, entering.RowKeys);
|
||||
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), entering.ChosenKeys);
|
||||
|
||||
var leaving = memory.Apply(GraphicsPreset.Medium, settings);
|
||||
|
||||
Assert.Equal(before, GraphicsExtras.Of(settings));
|
||||
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys, leaving.RowKeys);
|
||||
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), leaving.ChosenKeys);
|
||||
}
|
||||
|
||||
@@ -492,7 +396,6 @@ public class GraphicsPresetTests
|
||||
var settings = Defaults().Copy();
|
||||
settings.MotionBlur = false;
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
|
||||
var extras = GraphicsExtras.Of(settings);
|
||||
var top = GraphicsTop.Of(settings);
|
||||
|
||||
@@ -502,7 +405,6 @@ public class GraphicsPresetTests
|
||||
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
||||
Assert.Equal(top, GraphicsTop.Of(settings));
|
||||
Assert.Same(GraphicsPreset.VeryHigh, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
|
||||
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys), applied.ChosenKeys);
|
||||
}
|
||||
|
||||
@@ -512,12 +414,11 @@ public class GraphicsPresetTests
|
||||
var settings = Defaults().Copy();
|
||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||
|
||||
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings);
|
||||
new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings);
|
||||
|
||||
Assert.Equal(GraphicsExtras.None, GraphicsExtras.Of(settings));
|
||||
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(settings));
|
||||
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -526,19 +427,18 @@ public class GraphicsPresetTests
|
||||
var memory = new GraphicsPresetMemory();
|
||||
var settings = Defaults().Copy();
|
||||
settings.MotionBlur = false;
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
var extras = GraphicsExtras.Of(settings);
|
||||
var top = GraphicsTop.Of(settings);
|
||||
|
||||
memory.Apply(GraphicsPreset.Minimal, settings);
|
||||
var toUltra = memory.Apply(GraphicsPreset.Ultra, settings);
|
||||
memory.Apply(GraphicsPreset.Ultra, settings);
|
||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toUltra.RowKeys);
|
||||
|
||||
var toMinimal = memory.Apply(GraphicsPreset.Minimal, settings);
|
||||
memory.Apply(GraphicsPreset.Minimal, settings);
|
||||
Assert.Same(GraphicsPreset.Minimal, GraphicsPreset.Matching(settings));
|
||||
// Ultra's own values go, Minimal has no say over them.
|
||||
Assert.Equal(top, GraphicsTop.Of(settings));
|
||||
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toMinimal.RowKeys);
|
||||
|
||||
memory.Apply(GraphicsPreset.Medium, settings);
|
||||
Assert.Equal(extras, GraphicsExtras.Of(settings));
|
||||
@@ -560,7 +460,6 @@ public class GraphicsPresetTests
|
||||
var applied = memory.Apply(GraphicsPreset.High, settings);
|
||||
|
||||
Assert.True(settings.MotionBlur);
|
||||
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
|
||||
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
|
||||
}
|
||||
|
||||
@@ -596,33 +495,15 @@ public class GraphicsPresetTests
|
||||
[Fact]
|
||||
public void Every_level_sits_on_the_steps_the_screen_offers()
|
||||
{
|
||||
void OnSteps(double value, string name)
|
||||
{
|
||||
var key = SimulatorKeys.Named(name);
|
||||
Assert.InRange(value, key.Minimum, key.Maximum);
|
||||
double steps = value / key.Step;
|
||||
Assert.Equal(Math.Round(steps), steps, 6);
|
||||
}
|
||||
|
||||
foreach (var preset in GraphicsPreset.All)
|
||||
{
|
||||
OnSteps(preset.DistanceFactor, GraphicsPreset.DistanceFactorKey);
|
||||
OnSteps(preset.DrawRange, GraphicsPreset.DrawRangeKey);
|
||||
OnSteps(preset.SleeperDistance, GraphicsPreset.SleeperKey);
|
||||
OnSteps(preset.ReflectedInstances, GraphicsPreset.ReflectedInstancesKey);
|
||||
OnSteps(preset.ReflectedVehicles, GraphicsPreset.ReflectedVehiclesKey);
|
||||
Assert.InRange(preset.NewRenderer.CabProbeInterval, 1, 120);
|
||||
Assert.InRange(preset.NewRenderer.GrassDistance, 20, 300);
|
||||
Assert.Equal(0, preset.NewRenderer.GrassDistance % 10);
|
||||
Assert.Equal(0, preset.NewRenderer.GrassDensity % 0.25);
|
||||
Assert.Contains(preset.NewRenderer.Precipitation, new[] { 16384, 32768, 65536, 131072, 262144 });
|
||||
Assert.True(Steps.IndexOf(Steps.Anisotropy, preset.Anisotropy) >= 0, preset.NameKey);
|
||||
Assert.True(Steps.IndexOf(Steps.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
|
||||
Assert.True(Steps.IndexOf(Steps.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
|
||||
Assert.True(Steps.IndexOf(SliderRanges.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
|
||||
Assert.True(Steps.IndexOf(SliderRanges.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
|
||||
foreach (int size in new[] { preset.TextureSize, preset.CabTextureSize, preset.ShadowMap })
|
||||
Assert.True(size is >= 512 and <= 8192 && (size & (size - 1)) == 0, preset.NameKey);
|
||||
Assert.True(preset.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), preset.NameKey);
|
||||
Assert.Equal(0, preset.CabShadowsRange % 10);
|
||||
Assert.True(Steps.IndexOf(SliderRanges.CabShadowRanges, preset.CabShadowsRange) >= 0, preset.NameKey);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -637,7 +518,7 @@ public class GraphicsPresetTests
|
||||
|
||||
Assert.Equal(inGroups.Distinct(), inGroups);
|
||||
Assert.Empty(inGroups.Except(GraphicsPreset.Keys).Except(GraphicsExtras.Keys).Except(GraphicsTop.Keys));
|
||||
Assert.Equal(new[] { "gfx.antialiasing", "gfx.buffer.percent", "gfx.extraeffects", "gfx.postfx.bloom", "multisampling", "starter.bufferscale" },
|
||||
Assert.Equal(new[] { "dynamiclights", "gfx.extraeffects", "gfx.smoke.fidelity", "multisampling" },
|
||||
GraphicsPreset.Keys.Except(inGroups).OrderBy(key => key, StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
@@ -669,27 +550,22 @@ public class GraphicsPresetTests
|
||||
GraphicsPreset.Ultra.ApplyTo(settings);
|
||||
|
||||
Assert.All(Groups().LevelsOf(settings).Values, level => Assert.Same(GraphicsPreset.Ultra, level));
|
||||
|
||||
// The row of a key at the simulator's own value leaves it out of the file.
|
||||
settings.Extra.Remove(GraphicsTop.TextureReleaseKey);
|
||||
|
||||
Assert.Same(GraphicsPreset.Ultra, Groups().LevelsOf(settings)[GraphicsGroup.Textures]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_part_moved_by_hand_is_at_no_level_and_the_others_keep_theirs()
|
||||
{
|
||||
var settings = AtHigh();
|
||||
settings.DynamicLights = 6;
|
||||
settings.ReflectionsFidelity = 0;
|
||||
|
||||
var levels = Groups().LevelsOf(settings);
|
||||
|
||||
Assert.Null(levels[GraphicsGroup.Lights]);
|
||||
Assert.Null(levels[GraphicsGroup.Reflections]);
|
||||
Assert.Same(GraphicsPreset.High, levels[GraphicsGroup.Shadows]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_part_at_a_level_and_the_buffer_with_it_is_that_level()
|
||||
public void Every_part_at_a_level_and_the_rest_with_it_is_that_level()
|
||||
{
|
||||
var groups = Groups();
|
||||
foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null))
|
||||
@@ -697,8 +573,9 @@ public class GraphicsPresetTests
|
||||
var settings = Defaults().Copy();
|
||||
foreach (var group in GraphicsGroup.All)
|
||||
settings = groups.Apply(group, level, settings);
|
||||
settings.BufferScalePercent = level.BufferScale;
|
||||
settings.AntiAliasing = level.AntiAliasing;
|
||||
settings.DynamicLights = level.DynamicLights;
|
||||
settings.SmokeFidelity = level.SmokeFidelity;
|
||||
|
||||
Assert.Same(level, GraphicsPreset.Matching(settings));
|
||||
}
|
||||
@@ -718,14 +595,15 @@ public class GraphicsPresetTests
|
||||
{
|
||||
var groups = Groups();
|
||||
var settings = AtHigh();
|
||||
settings.ShadowAngleLimit = 0.8;
|
||||
|
||||
var ultra = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.Ultra, settings);
|
||||
Assert.False(ultra.CompressTextures);
|
||||
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Textures]);
|
||||
var ultra = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.Ultra, settings);
|
||||
Assert.Equal(0.2, ultra.ShadowAngleLimit);
|
||||
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Shadows]);
|
||||
|
||||
var back = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.High, ultra);
|
||||
Assert.Equal(GraphicsTop.None.CompressTextures, back.CompressTextures);
|
||||
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Textures]);
|
||||
var back = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.High, ultra);
|
||||
Assert.Equal(GraphicsTop.None.ShadowAngleLimit, back.ShadowAngleLimit);
|
||||
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Shadows]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -736,8 +614,9 @@ public class GraphicsPresetTests
|
||||
|
||||
settings.Smoke = false;
|
||||
|
||||
var nature = Groups().Apply(GraphicsGroup.Nature, GraphicsPreset.VeryHigh, settings);
|
||||
Assert.False(nature.Smoke);
|
||||
Assert.Equal(GraphicsPreset.VeryHigh.SmokeFidelity, nature.SmokeFidelity);
|
||||
var shadows = Groups().Apply(GraphicsGroup.Shadows, GraphicsPreset.VeryHigh, settings);
|
||||
Assert.False(shadows.Smoke);
|
||||
Assert.False(shadows.MotionBlur);
|
||||
Assert.Equal(GraphicsPreset.VeryHigh.ShadowMap, shadows.ShadowMapResolution);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,17 +17,17 @@ public class GraphicsSettingsTests
|
||||
return installation;
|
||||
}
|
||||
|
||||
private static SimulatorSettings Read(string text, bool dlssPlatform = true)
|
||||
private static SimulatorSettings Read(string text)
|
||||
{
|
||||
var s = new SimulatorSettings();
|
||||
new SettingsSerializer(dlssPlatform).Read(s, ConfigFile.Parse(text));
|
||||
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
|
||||
return s;
|
||||
}
|
||||
|
||||
private static string Write(SimulatorSettings s, string text = "", bool dlssPlatform = true)
|
||||
private static string Write(SimulatorSettings s, string text = "")
|
||||
{
|
||||
var c = ConfigFile.Parse(text);
|
||||
new SettingsSerializer(dlssPlatform).Write(s, c);
|
||||
new SettingsSerializer().Write(s, c);
|
||||
return c.ToText();
|
||||
}
|
||||
|
||||
@@ -37,63 +37,54 @@ public class GraphicsSettingsTests
|
||||
private static string? Line(string text, string key) =>
|
||||
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
|
||||
|
||||
// As application.cpp on master has them: a word it does not know gets the full renderer.
|
||||
[Theory]
|
||||
[InlineData("full", GraphicsBackend.OpenGL)]
|
||||
[InlineData("default", GraphicsBackend.OpenGL)]
|
||||
[InlineData("gl46", GraphicsBackend.OpenGL)]
|
||||
[InlineData("legacy", GraphicsBackend.OpenGL)]
|
||||
[InlineData("experimental", GraphicsBackend.OpenGL)]
|
||||
[InlineData("vulkan", GraphicsBackend.Vulkan)]
|
||||
[InlineData("vulkan14", GraphicsBackend.Vulkan)]
|
||||
public void The_renderer_is_read_with_the_aliases_the_simulator_takes(string value, GraphicsBackend expected)
|
||||
{
|
||||
Assert.Equal(expected, Read($"gfxrenderer {value}\n").Backend);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("full", "full")]
|
||||
[InlineData("gl46", "full")]
|
||||
[InlineData("default", "default")]
|
||||
[InlineData("full", "default")]
|
||||
[InlineData("gl46", "default")]
|
||||
[InlineData("vulkan", "default")]
|
||||
[InlineData("vulkan14", "default")]
|
||||
[InlineData("legacy", "legacy")]
|
||||
[InlineData("simpleshader", "legacy")]
|
||||
[InlineData("off", "legacy")]
|
||||
[InlineData("simple", "simple")]
|
||||
[InlineData("experimental", "experimental")]
|
||||
[InlineData("vulkan14", "vulkan")]
|
||||
public void A_renderer_is_written_by_its_name(string read, string written)
|
||||
[InlineData("experimental", "default")]
|
||||
public void A_renderer_is_written_by_the_name_master_knows(string read, string written)
|
||||
{
|
||||
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_a_renderer_in_the_file_the_full_one_is_chosen()
|
||||
{
|
||||
Assert.Equal(0, Read("").RenderEngine);
|
||||
Assert.Equal("gfxrenderer default", Line(Write(Read("")), "gfxrenderer"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_older_renderer_stays_chosen_and_can_be_chosen_again()
|
||||
{
|
||||
var installation = WithIni("gfxrenderer legacy\n");
|
||||
var store = installation.SettingsStore;
|
||||
|
||||
store.Settings.Clouds = 3;
|
||||
store.Settings.FieldOfView = 50;
|
||||
store.Save();
|
||||
Assert.Contains("gfxrenderer legacy", installation.Files.ReadAllText(UserIni));
|
||||
|
||||
store.Settings.RenderEngine = SimulatorSettings.VulkanEngine;
|
||||
store.Save();
|
||||
Assert.Contains("gfxrenderer vulkan", installation.Files.ReadAllText(UserIni));
|
||||
Assert.Equal(GraphicsBackend.Vulkan, store.Settings.Backend);
|
||||
|
||||
store.Settings.RenderEngine = SimulatorSettings.RenderEngineOf("simple");
|
||||
store.Save();
|
||||
Assert.Contains("gfxrenderer simple", installation.Files.ReadAllText(UserIni));
|
||||
Assert.Equal(GraphicsBackend.OpenGL, store.Settings.Backend);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Keys_only_an_older_simulator_reads_stay_in_the_file()
|
||||
public void Keys_only_the_legacy_renderer_or_windows_read_stay_in_the_file()
|
||||
{
|
||||
string[] old =
|
||||
{
|
||||
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes",
|
||||
"gfx.framebuffer.width 1920", "gfx.framebuffer.height 1080", "gfx.shadows.cab.range 20"
|
||||
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes", "gfx.shadows.cab.range 20"
|
||||
};
|
||||
var installation = WithIni(string.Join("\n", old) + "\n");
|
||||
installation.SettingsStore.Settings.Clouds = 3;
|
||||
installation.SettingsStore.Settings.FieldOfView = 50;
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
@@ -101,6 +92,24 @@ public class GraphicsSettingsTests
|
||||
Assert.All(old, line => Assert.Contains(line, saved));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Keys_of_the_vulkan_renderer_master_does_not_have_go_on_a_save()
|
||||
{
|
||||
string[] vulkan =
|
||||
{
|
||||
"gfx.antialiasing dlss", "gfx.dlss.preset k", "gfx.framegeneration x2", "gfx.reflex on",
|
||||
"gfx.raytracing yes", "gfx.ssr high", "gfx.postfx.ao gtao", "gfx.clouds ultra", "gfx.grass yes",
|
||||
"gfx.buffer.percent 0.67", "gfx.vulkan.device RTX", "gfx.fog yes", "gfx.cabprobe medium"
|
||||
};
|
||||
var installation = WithIni("calibratein 0 0 0 0\n" + string.Join("\n", vulkan) + "\n");
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
string saved = installation.Files.ReadAllText(UserIni);
|
||||
Assert.Contains("calibratein 0 0 0 0", saved);
|
||||
Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0])));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Levels_leave_the_switches_only_an_older_simulator_reads()
|
||||
{
|
||||
@@ -111,160 +120,26 @@ public class GraphicsSettingsTests
|
||||
Assert.Equal((false, true, true), (s.UseVbo, s.UseGLES, s.RenderAngleVulkan));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_new_graphics_keys_are_read()
|
||||
[Theory]
|
||||
[InlineData("multisampling 0\n", AntiAliasingMode.Off)]
|
||||
[InlineData("multisampling 1\n", AntiAliasingMode.Msaa2)]
|
||||
[InlineData("multisampling 2\n", AntiAliasingMode.Msaa4)]
|
||||
[InlineData("multisampling 3\n", AntiAliasingMode.Msaa8)]
|
||||
[InlineData("", AntiAliasingMode.Msaa4)]
|
||||
public void Multisampling_is_read_as_master_reads_it(string text, AntiAliasingMode expected)
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\n" +
|
||||
"gfx.antialiasing dlss\ngfx.dlss.preset K\ngfx.framegeneration x3\ngfx.reflex boost\n" +
|
||||
"gfx.raytracing yes\ngfx.raytracing.range 800\ngfx.ssr high\ngfx.postfx.ao ssao\ngfx.postfx.ao.quality 4 6\n" +
|
||||
"gfx.lights.shadows low\ngfx.contactshadows 3\ngfx.fog analytic\ngfx.fog.quality ultra\n" +
|
||||
"gfx.clouds ultra\ngfx.clouds.shadows no\ngfx.grass no\ngfx.grass.distance 120\ngfx.grass.density 1.5\n" +
|
||||
"gfx.buffer.percent 0.67\ngfx.vulkan.device RTX\n");
|
||||
|
||||
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
|
||||
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
|
||||
Assert.Equal("k", s.DlssPreset);
|
||||
Assert.Equal(3, s.FrameGeneration);
|
||||
Assert.Equal(2, s.Reflex);
|
||||
Assert.True(s.RayTracing);
|
||||
Assert.Equal(800, s.RayTracingRange);
|
||||
Assert.Equal(3, s.Ssr);
|
||||
Assert.Equal(1, s.AmbientOcclusion);
|
||||
Assert.Equal((4, 6), (s.AoSlices, s.AoSteps));
|
||||
Assert.Equal(1, s.LightShadows);
|
||||
Assert.Equal(3, s.ContactShadows);
|
||||
Assert.False(s.VolumetricFog);
|
||||
Assert.Equal(4, s.FogQuality);
|
||||
Assert.Equal(4, s.Clouds);
|
||||
Assert.False(s.CloudShadows);
|
||||
Assert.False(s.Grass);
|
||||
Assert.Equal(120, s.GrassDistance);
|
||||
Assert.Equal(1.5, s.GrassDensity);
|
||||
Assert.Equal(67, s.BufferScalePercent);
|
||||
Assert.Equal("RTX", s.VulkanDevice);
|
||||
Assert.Equal(expected, Read(text).AntiAliasing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_keys_take_the_simulators_defaults()
|
||||
{
|
||||
var s = Read("");
|
||||
|
||||
Assert.Equal(GraphicsBackend.OpenGL, s.Backend);
|
||||
Assert.Equal(AntiAliasingMode.Msaa4, s.AntiAliasing);
|
||||
Assert.Equal(2, s.Ssr);
|
||||
Assert.Equal(2, s.AmbientOcclusion);
|
||||
Assert.Equal(2, s.LightShadows);
|
||||
Assert.Equal(0, s.ContactShadows);
|
||||
Assert.True(s.VolumetricFog);
|
||||
Assert.Equal(2, s.FogQuality);
|
||||
Assert.Equal(2, s.Clouds);
|
||||
Assert.False(s.RayTracing);
|
||||
Assert.Equal(1, s.FrameGeneration);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_tokens_written_are_the_ones_the_simulator_parses()
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\n");
|
||||
s.AntiAliasing = AntiAliasingMode.Dlaa;
|
||||
s.FrameGeneration = 4;
|
||||
s.Reflex = 1;
|
||||
s.LightShadows = 3;
|
||||
s.ContactShadows = 0;
|
||||
s.Clouds = 4;
|
||||
s.VolumetricFog = false;
|
||||
s.FogQuality = 1;
|
||||
s.AmbientOcclusion = 1;
|
||||
s.Ssr = 2;
|
||||
s.RayTracing = true;
|
||||
|
||||
string text = Write(s);
|
||||
|
||||
Assert.Equal("gfx.antialiasing dlaa", Line(text, "gfx.antialiasing"));
|
||||
Assert.Equal("multisampling 0", Line(text, "multisampling"));
|
||||
Assert.Equal("gfx.framegeneration x4", Line(text, "gfx.framegeneration"));
|
||||
Assert.Equal("gfx.reflex on", Line(text, "gfx.reflex"));
|
||||
Assert.Equal("gfx.lights.shadows high", Line(text, "gfx.lights.shadows"));
|
||||
Assert.Equal("gfx.contactshadows no", Line(text, "gfx.contactshadows"));
|
||||
Assert.Equal("gfx.clouds ultra", Line(text, "gfx.clouds"));
|
||||
Assert.Equal("gfx.fog analytic", Line(text, "gfx.fog"));
|
||||
Assert.Equal("gfx.fog.quality low", Line(text, "gfx.fog.quality"));
|
||||
Assert.Equal("gfx.postfx.ao ssao", Line(text, "gfx.postfx.ao"));
|
||||
Assert.Equal("gfx.ssr medium", Line(text, "gfx.ssr"));
|
||||
Assert.Equal("gfx.raytracing yes", Line(text, "gfx.raytracing"));
|
||||
Assert.Equal("gfx.buffer.percent 100", Line(text, "gfx.buffer.percent"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Msaa_is_written_to_both_keys_for_older_simulators()
|
||||
public void Multisampling_is_written_to_its_own_key_only()
|
||||
{
|
||||
var s = Read("multisampling 1\n");
|
||||
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
|
||||
|
||||
string text = Write(s);
|
||||
|
||||
Assert.Equal("multisampling 1", Line(text, "multisampling"));
|
||||
Assert.Equal("gfx.antialiasing msaax2", Line(text, "gfx.antialiasing"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Of_the_two_anti_aliasing_keys_the_later_one_wins_as_in_the_simulator()
|
||||
{
|
||||
Assert.Equal(AntiAliasingMode.Taa, Read("multisampling 2\ngfx.antialiasing taa\n").AntiAliasing);
|
||||
Assert.Equal(AntiAliasingMode.Msaa4, Read("gfx.antialiasing taa\nmultisampling 2\n").AntiAliasing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void On_opengl_the_vulkan_only_features_are_written_off()
|
||||
{
|
||||
var s = Read("gfxrenderer full\ngfx.antialiasing dlss\ngfx.framegeneration x2\ngfx.reflex on\ngfx.raytracing yes\n");
|
||||
|
||||
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
|
||||
Assert.Equal(1, s.FrameGeneration);
|
||||
Assert.Equal(0, s.Reflex);
|
||||
Assert.False(s.RayTracing);
|
||||
|
||||
string text = Write(s);
|
||||
Assert.Equal("gfx.antialiasing taa", Line(text, "gfx.antialiasing"));
|
||||
Assert.Equal("gfx.framegeneration off", Line(text, "gfx.framegeneration"));
|
||||
Assert.Equal("gfx.reflex off", Line(text, "gfx.reflex"));
|
||||
Assert.Equal("gfx.raytracing no", Line(text, "gfx.raytracing"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Frame_generation_needs_dlss_even_on_vulkan()
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\ngfx.antialiasing taa\ngfx.framegeneration x2\ngfx.reflex on\n");
|
||||
|
||||
Assert.Equal(1, s.FrameGeneration);
|
||||
Assert.Equal(1, s.Reflex);
|
||||
Assert.False(GraphicsRules.ReflexForced(s, true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Frame_generation_turns_reflex_on()
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\ngfx.framegeneration x2\n");
|
||||
|
||||
Assert.True(GraphicsRules.ReflexForced(s, true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_a_dlss_platform_dlss_falls_back_to_taa()
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\n", dlssPlatform: false);
|
||||
|
||||
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dlaa_ignores_the_render_scale()
|
||||
{
|
||||
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlaa\n");
|
||||
Assert.False(GraphicsRules.BufferScaleUsed(s, true));
|
||||
|
||||
s.AntiAliasing = AntiAliasingMode.Dlss;
|
||||
Assert.True(GraphicsRules.BufferScaleUsed(s, true));
|
||||
Assert.Null(Line(text, "gfx.antialiasing"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -278,10 +153,23 @@ public class GraphicsSettingsTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_render_scale_reads_the_old_starter_key_when_the_new_one_is_missing()
|
||||
public void The_render_scale_is_the_starters_own_key_or_the_framebuffer_against_the_window()
|
||||
{
|
||||
Assert.Equal(75, Read("starter.bufferscale 75\n").BufferScalePercent);
|
||||
Assert.Equal(50, Read("starter.bufferscale 75\ngfx.buffer.percent 50\n").BufferScalePercent);
|
||||
Assert.Equal(50, Read("width 1920\ngfx.framebuffer.width 960\n").BufferScalePercent);
|
||||
Assert.Equal(100, Read("").BufferScalePercent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_render_scale_is_written_as_the_framebuffer_master_reads()
|
||||
{
|
||||
var s = Read("width 1920\nheight 1080\nstarter.bufferscale 50\n");
|
||||
|
||||
string text = Write(s);
|
||||
|
||||
Assert.Equal("gfx.framebuffer.width 960", Line(text, "gfx.framebuffer.width"));
|
||||
Assert.Equal("gfx.framebuffer.height 540", Line(text, "gfx.framebuffer.height"));
|
||||
Assert.Null(Line(text, "gfx.buffer.percent"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -312,7 +200,7 @@ public class GraphicsSettingsTests
|
||||
{
|
||||
var s = new SimulatorSettings();
|
||||
GraphicsPreset.High.ApplyTo(s);
|
||||
s.Clouds = 4;
|
||||
s.DynamicLights = 2;
|
||||
|
||||
Assert.Null(GraphicsPreset.Matching(s));
|
||||
}
|
||||
@@ -328,82 +216,62 @@ public class GraphicsSettingsTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ray_tracing_comes_with_ultra_on_vulkan_only()
|
||||
public void No_level_leaves_decorative_consists_out()
|
||||
{
|
||||
var vulkan = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine };
|
||||
var opengl = new SimulatorSettings();
|
||||
foreach (var level in GraphicsPreset.All)
|
||||
{
|
||||
var s = new SimulatorSettings { IgnoreIrrelevantTrains = false };
|
||||
level.ApplyTo(s);
|
||||
Assert.False(s.IgnoreIrrelevantTrains, level.NameKey);
|
||||
|
||||
GraphicsPreset.Ultra.ApplyTo(vulkan);
|
||||
GraphicsPreset.Ultra.ApplyTo(opengl);
|
||||
|
||||
Assert.True(vulkan.RayTracing);
|
||||
Assert.False(opengl.RayTracing);
|
||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(opengl));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_level_keeps_dlss_on_vulkan()
|
||||
{
|
||||
var s = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine, AntiAliasing = AntiAliasingMode.Dlss };
|
||||
|
||||
GraphicsPreset.Ultra.ApplyTo(s);
|
||||
|
||||
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
|
||||
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(s));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_level_replaces_taa_with_its_own_multisampling()
|
||||
{
|
||||
var s = new SimulatorSettings { AntiAliasing = AntiAliasingMode.Taa };
|
||||
|
||||
GraphicsPreset.Medium.ApplyTo(s);
|
||||
|
||||
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
|
||||
s.IgnoreIrrelevantTrains = true;
|
||||
level.ApplyTo(s);
|
||||
Assert.True(s.IgnoreIrrelevantTrains, level.NameKey);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_import_takes_the_settings_but_keeps_this_installations_simulator_and_the_unmanaged_lines()
|
||||
{
|
||||
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\ngfx.clouds low\n");
|
||||
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\ngfx.clouds ultra\ngfxrenderer vulkan\n");
|
||||
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\nfieldofview 45\n");
|
||||
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\nfieldofview 60\ngfxrenderer legacy\n");
|
||||
|
||||
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
|
||||
var s = installation.SettingsStore.Settings;
|
||||
Assert.Equal(4, s.Clouds);
|
||||
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
|
||||
Assert.Equal(60, s.FieldOfView);
|
||||
Assert.Equal(SimulatorSettings.RenderEngineOf("legacy"), s.RenderEngine);
|
||||
Assert.Equal("eu07_local.exe", s.ExecutablePath);
|
||||
|
||||
// Nothing is written until saved, and the save keeps the user's own lines.
|
||||
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
|
||||
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
|
||||
installation.SettingsStore.Save();
|
||||
string saved = installation.Files.ReadAllText(UserIni);
|
||||
Assert.Contains("calibratein 0 0 0 0", saved);
|
||||
Assert.Contains("gfx.clouds ultra", saved);
|
||||
Assert.Contains("fieldofview 60", saved);
|
||||
Assert.Contains("starter.exe.path eu07_local.exe", saved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_import_of_a_missing_file_changes_nothing()
|
||||
{
|
||||
var installation = WithIni("gfx.clouds low\n");
|
||||
var installation = WithIni("fieldofview 50\n");
|
||||
|
||||
Assert.False(installation.SettingsStore.ImportFrom("/nowhere/eu07.ini"));
|
||||
Assert.Equal(1, installation.SettingsStore.Settings.Clouds);
|
||||
Assert.Equal(50, installation.SettingsStore.Settings.FieldOfView);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_export_writes_a_complete_file_elsewhere_and_leaves_the_users_one_alone()
|
||||
{
|
||||
var installation = WithIni("calibratein 0 0 0 0\ngfx.clouds low\n");
|
||||
installation.SettingsStore.Settings.Clouds = 3;
|
||||
var installation = WithIni("calibratein 0 0 0 0\nfieldofview 45\n");
|
||||
installation.SettingsStore.Settings.FieldOfView = 60;
|
||||
|
||||
Assert.True(installation.SettingsStore.ExportTo("/export/eu07.ini"));
|
||||
|
||||
string exported = installation.Files.ReadAllText("/export/eu07.ini");
|
||||
Assert.Contains("calibratein 0 0 0 0", exported);
|
||||
Assert.Contains("gfx.clouds high", exported);
|
||||
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
|
||||
Assert.Contains("fieldofview 60", exported);
|
||||
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -417,30 +285,34 @@ public class GraphicsSettingsTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_dlss_libraries_are_looked_for_next_to_a_windows_build()
|
||||
public void The_gamepad_is_ignored_unless_the_file_turns_it_on()
|
||||
{
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithDirectory(TestInstallation.Root)
|
||||
.WithExecutable(TestInstallation.At("eu07.exe"), "MZ binary")
|
||||
.WithFile(TestInstallation.At("nvngx_dlss.dll"), "dll");
|
||||
var installation = new TestInstallation(files);
|
||||
|
||||
Assert.Equal((true, false), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
|
||||
|
||||
files.WithFile(TestInstallation.At("nvngx_dlssg.dll"), "dll");
|
||||
Assert.Equal((true, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
|
||||
Assert.True(Read("").IgnoreGamepad);
|
||||
Assert.Equal("input.gamepad no", Line(Write(Read("")), "input.gamepad"));
|
||||
Assert.False(Read("input.gamepad yes\n").IgnoreGamepad);
|
||||
Assert.True(Read("input.gamepad no\n").IgnoreGamepad);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_dlss_libraries_of_a_linux_build_are_the_shared_objects()
|
||||
public void The_standard_mode_is_where_a_player_starts_and_the_choice_is_kept()
|
||||
{
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithDirectory(TestInstallation.Root)
|
||||
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
|
||||
.WithFile(TestInstallation.At("libnvidia-ngx-dlssg.so.310.4.0"), "so");
|
||||
var installation = new TestInstallation(files);
|
||||
Assert.False(Read("").AdvancedSettings);
|
||||
Assert.True(Read("starter.settings.advanced yes\n").AdvancedSettings);
|
||||
|
||||
Assert.Equal((false, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07")));
|
||||
var s = Read("");
|
||||
s.AdvancedSettings = true;
|
||||
Assert.Equal("starter.settings.advanced yes", Line(Write(s), "starter.settings.advanced"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_move_to_the_standard_mode_is_marked_in_the_file()
|
||||
{
|
||||
Assert.False(Read("").MovedToStandard);
|
||||
Assert.True(Read("starter.settings.standard yes\n").MovedToStandard);
|
||||
|
||||
var s = Read("");
|
||||
s.MovedToStandard = true;
|
||||
Assert.Equal("starter.settings.standard yes", Line(Write(s), "starter.settings.standard"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -455,139 +327,4 @@ public class GraphicsSettingsTests
|
||||
c.Set("b", "9");
|
||||
Assert.Equal("b 9\nc 3\na 1\n", c.ToText().Replace("\r\n", "\n"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_ao_lighting_and_cab_probe_keys_survive_a_round_trip_in_the_simulators_form()
|
||||
{
|
||||
var s = Read("gfx.postfx.ao.lighting no\ngfx.cabprobe high\ngfx.cabprobe.interval 12\ngfx.cabprobe.bounce 2.5\ngfx.cabprobe.reflections no\n");
|
||||
|
||||
Assert.False(s.AoLighting);
|
||||
Assert.Equal(3, s.CabProbe);
|
||||
Assert.Equal(12, s.CabProbeInterval);
|
||||
Assert.Equal(2.5, s.CabProbeBounce);
|
||||
Assert.False(s.CabProbeReflections);
|
||||
|
||||
string text = Write(s);
|
||||
Assert.Equal("gfx.postfx.ao.lighting no", Line(text, "gfx.postfx.ao.lighting"));
|
||||
Assert.Equal("gfx.cabprobe high", Line(text, "gfx.cabprobe"));
|
||||
Assert.Equal("gfx.cabprobe.interval 12", Line(text, "gfx.cabprobe.interval"));
|
||||
Assert.Equal("gfx.cabprobe.bounce 2.5", Line(text, "gfx.cabprobe.bounce"));
|
||||
Assert.Equal("gfx.cabprobe.reflections no", Line(text, "gfx.cabprobe.reflections"));
|
||||
|
||||
var again = Read(text);
|
||||
Assert.Equal((s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections),
|
||||
(again.AoLighting, again.CabProbe, again.CabProbeInterval, again.CabProbeBounce, again.CabProbeReflections));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_ao_lighting_and_cab_probe_keys_take_the_simulators_defaults_and_are_written_like_its_export()
|
||||
{
|
||||
var s = Read("");
|
||||
|
||||
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
|
||||
|
||||
string text = Write(s);
|
||||
Assert.Equal("gfx.postfx.ao.lighting yes", Line(text, "gfx.postfx.ao.lighting"));
|
||||
Assert.Equal("gfx.cabprobe medium", Line(text, "gfx.cabprobe"));
|
||||
Assert.Equal("gfx.cabprobe.interval 4", Line(text, "gfx.cabprobe.interval"));
|
||||
Assert.Equal("gfx.cabprobe.bounce 1", Line(text, "gfx.cabprobe.bounce"));
|
||||
Assert.Equal("gfx.cabprobe.reflections yes", Line(text, "gfx.cabprobe.reflections"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unknown_ao_lighting_and_cab_probe_values_fall_back_to_the_simulators_defaults()
|
||||
{
|
||||
var s = Read("gfx.postfx.ao.lighting maybe\ngfx.cabprobe bogus\ngfx.cabprobe.interval abc\ngfx.cabprobe.bounce x\ngfx.cabprobe.reflections ?\n");
|
||||
|
||||
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("no", 0)]
|
||||
[InlineData("0", 0)]
|
||||
[InlineData("low", 1)]
|
||||
[InlineData("1", 1)]
|
||||
[InlineData("medium", 2)]
|
||||
[InlineData("yes", 2)]
|
||||
[InlineData("2", 2)]
|
||||
[InlineData("high", 3)]
|
||||
[InlineData("3", 3)]
|
||||
public void The_cab_probe_level_is_read_with_the_aliases_the_simulator_takes(string value, int expected)
|
||||
{
|
||||
Assert.Equal(expected, Read($"gfx.cabprobe {value}\n").CabProbe);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_cab_probe_numbers_are_kept_within_the_simulators_ranges()
|
||||
{
|
||||
var s = Read("gfx.cabprobe.interval 500\ngfx.cabprobe.bounce 9\n");
|
||||
Assert.Equal((120, 4.0), (s.CabProbeInterval, s.CabProbeBounce));
|
||||
|
||||
s = Read("gfx.cabprobe.interval 0\ngfx.cabprobe.bounce -1\n");
|
||||
Assert.Equal((1, 0.0), (s.CabProbeInterval, s.CabProbeBounce));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_ao_lighting_counts_with_gtao_only()
|
||||
{
|
||||
Assert.True(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao gtao\n")));
|
||||
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao ssao\n")));
|
||||
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao no\n")));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("gfx.ssr no\ngfx.contactshadows no\n", true)]
|
||||
[InlineData("gfx.ssr low\ngfx.contactshadows no\n", false)]
|
||||
[InlineData("gfx.ssr no\ngfx.contactshadows low\n", false)]
|
||||
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.depthprepass.scene yes\n", false)]
|
||||
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao.lighting no\n", false)]
|
||||
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao ssao\n", false)]
|
||||
public void The_ao_lighting_adds_the_depth_pass_only_when_nothing_else_draws_it(string text, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, GraphicsRules.AoLightingAddsDepthPrepass(Read(text)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("gfx.cabprobe medium\n", true, true)]
|
||||
[InlineData("gfx.cabprobe no\n", false, false)]
|
||||
[InlineData("gfx.cabprobe low\ngfx.lights.clustered no\n", true, false)]
|
||||
[InlineData("gfx.cabprobe high\ngfx.lights.cab no\n", true, false)]
|
||||
public void The_cab_probe_lights_the_cab_only_with_its_lamp_as_a_light(string text, bool used, bool lights)
|
||||
{
|
||||
var s = Read(text);
|
||||
|
||||
Assert.Equal(used, GraphicsRules.CabProbeUsed(s));
|
||||
Assert.Equal(lights, GraphicsRules.CabProbeLights(s));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, false, 0, 8, false)]
|
||||
[InlineData(1, false, 0, 8, false)]
|
||||
[InlineData(2, false, 1, 8, true)]
|
||||
[InlineData(3, true, 2, 4, true)]
|
||||
[InlineData(4, true, 3, 3, true)]
|
||||
[InlineData(5, true, 3, 2, true)]
|
||||
public void A_level_sets_the_ao_lighting_and_the_cab_probe(int place, bool aoLighting, int probe, int interval, bool reflections)
|
||||
{
|
||||
var level = GraphicsPreset.All[place];
|
||||
var s = new SimulatorSettings { CabProbeBounce = 2.5 };
|
||||
|
||||
level.ApplyTo(s);
|
||||
|
||||
Assert.Equal((aoLighting, probe, interval, reflections), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeReflections));
|
||||
Assert.Equal(2.5, s.CabProbeBounce);
|
||||
Assert.Same(level, GraphicsPreset.Matching(s));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_import_keeps_the_lamp_switch_of_the_users_own_file()
|
||||
{
|
||||
var installation = WithIni("gfx.lights.cab no\n");
|
||||
installation.Files.WithFile("/backup/eu07.ini", "gfx.lights.cab yes\ngfx.cabprobe high\n");
|
||||
|
||||
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
|
||||
|
||||
Assert.False(installation.SettingsStore.Settings.CabLampLight);
|
||||
Assert.Equal(3, installation.SettingsStore.Settings.CabProbe);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ namespace StarterNG.Tests;
|
||||
|
||||
public class HaslerTapeTests
|
||||
{
|
||||
private const string Header =
|
||||
internal const string Header =
|
||||
"Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " +
|
||||
"BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " +
|
||||
"Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n";
|
||||
|
||||
private static string Line(double t, double v, double brake, double current, string command = "none",
|
||||
internal static string Line(double t, double v, double brake, double current, string command = "none",
|
||||
int security = 0) =>
|
||||
string.Create(CultureInfo.InvariantCulture,
|
||||
$"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") +
|
||||
@@ -68,6 +68,197 @@ public class HaslerTapeTests
|
||||
Assert.Equal(5, tape.DistanceM, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end()
|
||||
{
|
||||
// the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures
|
||||
string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n");
|
||||
static string WithSpeed(string line, double kmh) =>
|
||||
line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n"));
|
||||
// the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter
|
||||
string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n",
|
||||
" 0 1 0.0000 0.0000 0.0000 0.0000\r\n");
|
||||
|
||||
var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36));
|
||||
|
||||
Assert.Equal(2, tape.Samples.Count);
|
||||
Assert.False(tape.Samples[0].SecurityAlarm);
|
||||
Assert.True(tape.Samples[1].SecurityAlarm);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header()
|
||||
{
|
||||
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1));
|
||||
|
||||
Assert.Equal(2, tape.Samples.Count);
|
||||
Assert.False(tape.Samples[0].SecurityAlarm);
|
||||
Assert.True(tape.Samples[1].SecurityAlarm);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance()
|
||||
{
|
||||
// the player in another vehicle for ten minutes, then back in this one
|
||||
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0)
|
||||
+ Line(602, 36, 0, 0) + Line(603, 0, 0, 0));
|
||||
|
||||
Assert.Equal(603, tape.Duration, 6);
|
||||
Assert.Equal(600, tape.GapTime, 6);
|
||||
Assert.Equal(2, tape.RunningTime, 6);
|
||||
Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping
|
||||
Assert.Equal(10 + 10 + 5, tape.DistanceM, 6);
|
||||
Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap()
|
||||
{
|
||||
// a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after
|
||||
var text = new System.Text.StringBuilder(Header);
|
||||
double t = 0;
|
||||
for (int i = 0; i < 40; i++, t += 0.05)
|
||||
text.Append(Line(t, 100, 0, 0));
|
||||
t += 1.017 - 0.05;
|
||||
for (int i = 0; i < 40; i++, t += 0.05)
|
||||
text.Append(Line(t, 100, 0, 0));
|
||||
|
||||
var tape = HaslerTape.Parse(text.ToString());
|
||||
|
||||
Assert.Equal(0, tape.GapTime, 6);
|
||||
Assert.Equal(tape.Duration, tape.RunningTime, 6);
|
||||
Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole()
|
||||
{
|
||||
string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400)
|
||||
+ Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0);
|
||||
var whole = HaslerTape.Parse(text);
|
||||
|
||||
for (int cut = 1; cut < text.Length; cut += 7)
|
||||
{
|
||||
var reader = new HaslerTape.Reader();
|
||||
reader.Feed(text[..cut]);
|
||||
reader.Feed(text[cut..]);
|
||||
Assert.Equal(whole.Samples, reader.Tape(final: true).Samples);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed()
|
||||
{
|
||||
var reader = new HaslerTape.Reader();
|
||||
string line = Line(1, 36, 0, 0);
|
||||
reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]);
|
||||
|
||||
Assert.Single(reader.Tape(final: false).Samples);
|
||||
Assert.Single(reader.Tape(final: false).Samples);
|
||||
reader.Feed(line[20..]);
|
||||
Assert.Equal(2, reader.Tape(final: false).Samples.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole()
|
||||
{
|
||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
|
||||
var tapes = new TestInstallation(files).Tapes;
|
||||
var file = Assert.Single(tapes.List());
|
||||
|
||||
Assert.Single(tapes.Load(file, follow: false)!.Samples);
|
||||
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0));
|
||||
Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count);
|
||||
|
||||
// begun anew, and already longer than was read: its time goes back
|
||||
files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0));
|
||||
var tape = tapes.Load(file, follow: true)!;
|
||||
Assert.Equal(4, tape.Samples.Count);
|
||||
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
||||
|
||||
// begun anew, and shorter
|
||||
files.WithFile(path, Header + Line(0, 18, 0, 0));
|
||||
Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_log_begun_anew_over_the_end_that_was_read_is_read_whole_once_its_time_goes_back()
|
||||
{
|
||||
// the command is free text, here long enough that the end kept of the read part holds no time
|
||||
string command = new('x', 400);
|
||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(3, 36, 0, 0, command));
|
||||
var tapes = new TestInstallation(files).Tapes;
|
||||
var file = Assert.Single(tapes.List());
|
||||
Assert.Equal(3, Assert.Single(tapes.Load(file, follow: false)!.Samples).Time, 6);
|
||||
|
||||
// begun anew: where the read part ended it reads as it did, but the lines added go back to the start
|
||||
files.WithFile(path, Header + Line(0, 36, 0, 0, command) + Line(1, 36, 0, 0, command) + Line(2, 36, 0, 0, command));
|
||||
var tape = tapes.Load(file, follow: true)!;
|
||||
|
||||
Assert.Equal([0.0, 1.0, 2.0], tape.Samples.Select(s => s.Time));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_tape_that_cannot_be_read_is_none_and_told_and_is_read_whole_once_it_can()
|
||||
{
|
||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
|
||||
var installation = new TestInstallation(files);
|
||||
var tapes = installation.Tapes;
|
||||
var file = Assert.Single(tapes.List());
|
||||
tapes.Load(file, follow: false);
|
||||
|
||||
files.FailReading(path);
|
||||
Assert.Null(tapes.Load(file, follow: true));
|
||||
Assert.Contains("EU07-424.dat", installation.Log.Text);
|
||||
|
||||
files.AllowReading(path).WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0));
|
||||
Assert.All(tapes.Load(file, follow: true)!.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_file_read_only_forward_is_read_whole_each_time()
|
||||
{
|
||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)).OpenedForwardOnly(path);
|
||||
var tapes = new TestInstallation(files).Tapes;
|
||||
var file = Assert.Single(tapes.List());
|
||||
|
||||
Assert.Single(tapes.Load(file, follow: true)!.Samples);
|
||||
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0));
|
||||
Assert.Equal(2, tapes.Load(file, follow: true)!.Samples.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Empty_lines_in_a_log_are_passed_over()
|
||||
{
|
||||
var tape = HaslerTape.Parse(Header + "\r\n" + Line(0, 36, 0, 0) + " \r\n" + Line(1, 36, 0, 0));
|
||||
|
||||
Assert.Equal(2, tape.Samples.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Forgetting_another_file_keeps_the_followed_tape_and_its_own_lets_it_go()
|
||||
{
|
||||
string Lines(int firstSpeed, int count) =>
|
||||
Header + Line(0, firstSpeed, 0, 0) + string.Concat(Enumerable.Range(1, count).Select(t => Line(t, 36, 0, 0)));
|
||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
||||
var files = new InMemoryFileSystem().WithFile(path, Lines(36, 20));
|
||||
var tapes = new TestInstallation(files).Tapes;
|
||||
var file = Assert.Single(tapes.List());
|
||||
tapes.Load(file, follow: false);
|
||||
|
||||
// the first line changed, as long as it was and far from the end: a tape still followed doesn't read it again
|
||||
files.WithFile(path, Lines(72, 21));
|
||||
tapes.Forget(TestInstallation.At("physicslog", "EU07-111.dat"));
|
||||
Assert.Equal(36, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
|
||||
|
||||
tapes.Forget(file.Path);
|
||||
Assert.Equal(72, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
|
||||
{
|
||||
|
||||
96
StarterNG.Tests/HaslerTapeWindowTests.cs
Normal file
96
StarterNG.Tests/HaslerTapeWindowTests.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.LogicalTree;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Domain.Tapes;
|
||||
using StarterNG.Tests.Fakes;
|
||||
using StarterNG.Views.Tapes;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
/// <summary>The tapes' window over the tapes of an installation of its own, read as it is opened.</summary>
|
||||
[Collection(AvaloniaControls.Name)]
|
||||
public class HaslerTapeWindowTests
|
||||
{
|
||||
private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
static HaslerTapeWindowTests() => HeadlessDrawing.Ensure();
|
||||
|
||||
private static AppServices Services(InMemoryFileSystem files)
|
||||
{
|
||||
var installation = new TestInstallation(files);
|
||||
installation.Clock.Now = Launched;
|
||||
return AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
|
||||
}
|
||||
|
||||
// The window reads the tapes off the UI thread and shows them on it: what it shows is waited for.
|
||||
private static void Until(Func<bool> shown) =>
|
||||
Assert.True(SpinWait.SpinUntil(() =>
|
||||
{
|
||||
Controls.Settle();
|
||||
return shown();
|
||||
}, TimeSpan.FromSeconds(5)));
|
||||
|
||||
private static Button Button(Window window, string key) =>
|
||||
window.GetLogicalDescendants().OfType<Button>().Single(b => b.Content as string == App.Loc[key]);
|
||||
|
||||
[Fact]
|
||||
public void With_nothing_recorded_it_offers_to_record_and_turns_on_the_black_box_and_the_trains_tapes()
|
||||
{
|
||||
var services = Services(new InMemoryFileSystem());
|
||||
var window = new HaslerTapeWindow();
|
||||
bool told = false;
|
||||
window.LogEnabled += () => told = true;
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
var strip = (Control)Button(window, "HaslerRecordingEnable").Parent!;
|
||||
Until(() => strip.IsVisible);
|
||||
|
||||
Button(window, "HaslerRecordingEnable").RaiseEvent(Controls.Click());
|
||||
|
||||
Assert.True(services.Settings.BlackBox);
|
||||
Assert.True(services.Settings.PhysicsLogTrains);
|
||||
Assert.False(services.Settings.PhysicsLog);
|
||||
Assert.True(told);
|
||||
Assert.False(strip.IsVisible);
|
||||
// the simulator's own log is on as it comes: nothing more to offer
|
||||
Assert.False(((Control)Button(window, "HaslerLogEnable").Parent!).IsVisible);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_tape_of_the_last_launch_is_summed_up_with_its_scenario_and_train()
|
||||
{
|
||||
string path = TestInstallation.At("physicslog", "EP07-424.dat");
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 36, 0, 0) + HaslerTapeTests.Line(60, 36, 0, 0));
|
||||
var services = Services(files);
|
||||
services.Tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "EP07-424", new[] { "EP07-424" },
|
||||
"Tor doświadczalny", "EIE1531");
|
||||
var window = new HaslerTapeWindow();
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
string scenario = string.Format(App.Loc["HaslerScenario"], "Tor doświadczalny");
|
||||
var texts = window.GetLogicalDescendants().OfType<TextBlock>();
|
||||
Until(() => texts.Any(t => t.Text?.Contains(scenario) == true));
|
||||
string summary = texts.First(t => t.Text?.Contains(scenario) == true).Text!;
|
||||
|
||||
Assert.StartsWith("EP07-424", summary);
|
||||
Assert.Contains(string.Format(App.Loc["HaslerTrain"], "EIE1531"), summary);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
// closed, the tape it read is no longer followed: begun anew and longer, it is read whole
|
||||
files.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 72, 0, 0) + HaslerTapeTests.Line(1, 72, 0, 0)
|
||||
+ HaslerTapeTests.Line(2, 72, 0, 0));
|
||||
var tape = services.Tapes.Load(services.Tapes.List().Single(), follow: true)!;
|
||||
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
||||
}
|
||||
}
|
||||
87
StarterNG.Tests/MessageBoxTests.cs
Normal file
87
StarterNG.Tests/MessageBoxTests.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.LogicalTree;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Tests.Fakes;
|
||||
using StarterNG.Views;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
/// <summary>The starter's questions over its window, answered with the mouse or not at all.</summary>
|
||||
[Collection(AvaloniaControls.Name)]
|
||||
public class MessageBoxTests
|
||||
{
|
||||
// The buttons are labelled in the starter's language.
|
||||
static MessageBoxTests()
|
||||
{
|
||||
HeadlessDrawing.Ensure();
|
||||
if (AppServices.CurrentOrNull is null)
|
||||
{
|
||||
var installation = new TestInstallation(new InMemoryFileSystem());
|
||||
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
|
||||
}
|
||||
}
|
||||
|
||||
private static (Window Owner, Window Dialog, Task<bool?> Answer) Choose()
|
||||
{
|
||||
var owner = new Window();
|
||||
owner.Show();
|
||||
var answer = MessageBox.Choose(owner, "Zapisać zmiany przed startem?", "Niezapisane zmiany", "Zapisz", "Nie zapisuj");
|
||||
Controls.Settle();
|
||||
return (owner, Assert.Single(owner.OwnedWindows), answer);
|
||||
}
|
||||
|
||||
// The answer is given once the dialog's closing has gone through the dispatcher.
|
||||
private static bool? Answered(Task<bool?> answer)
|
||||
{
|
||||
Assert.True(SpinWait.SpinUntil(() =>
|
||||
{
|
||||
Controls.Settle();
|
||||
return answer.IsCompleted;
|
||||
}, TimeSpan.FromSeconds(5)));
|
||||
return answer.Result;
|
||||
}
|
||||
|
||||
private static Button[] Buttons(Window dialog) => dialog.GetLogicalDescendants().OfType<Button>().ToArray();
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, true)]
|
||||
[InlineData(1, false)]
|
||||
[InlineData(2, null)]
|
||||
public void A_choice_gives_the_answer_clicked_and_the_way_back_gives_none(int clicked, bool? expected)
|
||||
{
|
||||
var (owner, dialog, answer) = Choose();
|
||||
try
|
||||
{
|
||||
Assert.Equal("Niezapisane zmiany", dialog.Title);
|
||||
Assert.Contains(dialog.GetLogicalDescendants().OfType<TextBlock>(), t => t.Text == "Zapisać zmiany przed startem?");
|
||||
var buttons = Buttons(dialog);
|
||||
Assert.Equal(["Zapisz", "Nie zapisuj", App.Loc["Cancel"]], buttons.Select(b => b.Content as string));
|
||||
Assert.False(answer.IsCompleted);
|
||||
|
||||
buttons[clicked].RaiseEvent(Controls.Click());
|
||||
|
||||
Assert.Equal(expected, Answered(answer));
|
||||
Assert.Empty(owner.OwnedWindows);
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Closing_the_window_of_a_choice_picks_neither_answer()
|
||||
{
|
||||
var (owner, dialog, answer) = Choose();
|
||||
try
|
||||
{
|
||||
dialog.Close();
|
||||
|
||||
Assert.Null(Answered(answer));
|
||||
}
|
||||
finally
|
||||
{
|
||||
owner.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
@@ -270,7 +270,7 @@ public class ScenerySyntaxTests
|
||||
trainset td/rozklad tdo_n1734 0.0 0.1
|
||||
//$o Skład gotowy na żeberku.
|
||||
endtrainset
|
||||
include koniec.scm
|
||||
include koniec.scm end
|
||||
""";
|
||||
|
||||
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
|
||||
@@ -331,13 +331,61 @@ public class ScenerySyntaxTests
|
||||
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_vehicle_without_its_fiz_is_reported_as_one_the_simulator_leaves_out()
|
||||
{
|
||||
// As on Bałtyk Cargo: the wagons of a folder gone empty drop out of the consist.
|
||||
const string scn = """
|
||||
trainset none tor1 0 0.1
|
||||
node -1 0 sm42 dynamic PKP\SM42_V1 6D-468 6D -1 headdriver 3 0 enddynamic
|
||||
node -1 0 eaos-33 dynamic PKP\412W_V1 5340976-0 412wc 0 nobody 3 60 wegiel3 enddynamic
|
||||
node -1 0 eaos-34 dynamic PKP\412W_V1 5351442-9 412W 0 nobody 0 60 mial1 enddynamic
|
||||
endtrainset
|
||||
node -1 0 auto dynamic car car car tor1 0 headdriver 0 0 enddynamic
|
||||
""";
|
||||
var asked = new List<(string, string)>();
|
||||
|
||||
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, loadsVehicle: (folder, mmd) =>
|
||||
{
|
||||
asked.Add((folder, mmd));
|
||||
return !folder.Equals(@"PKP\412W_V1", StringComparison.Ordinal);
|
||||
});
|
||||
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
(SceneryFaultKind.VehicleMissing, "x.scn", 3, (string?)"eaos-33", (string?)@"PKP\412W_V1/412wc.fiz"),
|
||||
(SceneryFaultKind.VehicleMissing, "x.scn", 4, "eaos-34", @"PKP\412W_V1/412W.fiz")
|
||||
}, scenery.Faults.Select(Seen));
|
||||
Assert.Contains(("car", "car"), asked);
|
||||
// Still listed whole: the starter writes them as they are, for when they are back.
|
||||
Assert.Equal(3, Assert.Single(scenery.Trainsets).Vehicles.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_vehicle_folder_there_but_empty_is_no_vehicle()
|
||||
{
|
||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||
.WithLegacyFile("game/scenery/x.scn",
|
||||
"trainset none tor1 0 0\n" +
|
||||
"node -1 0 a1 dynamic PKP\\430W_V2 skin 430W 0 nobody 3 0 enddynamic\n" +
|
||||
"node -1 0 a2 dynamic PKP\\412W_V1 skin 412W 0 nobody 0 0 enddynamic\n" +
|
||||
"endtrainset\n")
|
||||
.WithLegacyFile("game/dynamic/pkp/430w_v2/430w.fiz", "")
|
||||
.WithLegacyFile("game/dynamic/pkp/412w_v1/412w.mmd", "");
|
||||
|
||||
var faults = TestScenery.Repository(files).Load("game/scenery/x.scn")!.Faults;
|
||||
|
||||
Assert.Equal((SceneryFaultKind.VehicleMissing, "x.scn", 3, "a2", @"PKP\412W_V1/412W.fiz"), Seen(Assert.Single(faults)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_include_named_in_another_case_is_found_as_the_simulator_finds_it()
|
||||
{
|
||||
var files = new InMemoryFileSystem(caseSensitive: true)
|
||||
.WithLegacyFile("game/scenery/x.scn", "FirstInit\ninclude Tomaszewo/Auta.SCM end\n")
|
||||
.WithLegacyFile("game/scenery/tomaszewo/auta.scm",
|
||||
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n");
|
||||
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n")
|
||||
.WithLegacyFile("game/dynamic/car/car.fiz", "");
|
||||
var repository = TestScenery.Repository(files);
|
||||
|
||||
var scenery = repository.Load("game/scenery/x.scn")!;
|
||||
@@ -378,4 +426,35 @@ public class ScenerySyntaxTests
|
||||
Assert.Equal(sbt, scenery.HasCompanionTimetable);
|
||||
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_include_with_no_end_is_a_fault_even_as_the_last_line()
|
||||
{
|
||||
const string scn = "FirstInit\ntrainset a t 0 0\nendtrainset\ninclude dekoracje.scm //Sklady dekoracyjne\n";
|
||||
|
||||
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn).Faults.Select(f => (f.Kind, f.Line)).ToList();
|
||||
|
||||
Assert.Equal(new[] { (SceneryFaultKind.IncludeNotClosed, 4) }, faults);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_consists_of_a_last_include_with_no_end_are_listed_as_the_simulator_loads_them()
|
||||
{
|
||||
const string decorations = "trainset d1 t1 0 0\nnode -1 0 a dynamic d s m 0 nobody 3 0 enddynamic\nendtrainset\n";
|
||||
|
||||
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm //Sklady dekoracyjne\n",
|
||||
name => (name, decorations));
|
||||
|
||||
Assert.Contains(SceneryIncludes.BeginMarker + "dekoracje.scm", text);
|
||||
Assert.Contains("trainset d1 t1 0 0", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_include_with_no_end_before_more_of_the_file_is_left_alone()
|
||||
{
|
||||
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm\ntrainset a t 0 0\nendtrainset\n",
|
||||
name => (name, "trainset d1 t1 0 0\nendtrainset\n"));
|
||||
|
||||
Assert.DoesNotContain(SceneryIncludes.BeginMarker, text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,14 +158,12 @@ public class ScreenReaderNamesTests
|
||||
var slider = new Slider();
|
||||
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
|
||||
row.Description = "Gra zajmie cały ekran.";
|
||||
row.IdleNote = "Ten symulator nie zna tego ustawienia.";
|
||||
|
||||
Assert.Equal("Gra zajmie cały ekran., Ten symulator nie zna tego ustawienia.", AutomationProperties.GetHelpText(check));
|
||||
Assert.Equal("Gra zajmie cały ekran.", AutomationProperties.GetHelpText(check));
|
||||
Assert.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
|
||||
Assert.Null(AutomationProperties.GetName(check));
|
||||
|
||||
row.Description = null;
|
||||
row.IdleNote = null;
|
||||
Assert.Null(AutomationProperties.GetHelpText(check));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
using StarterNG.Domain.Settings;
|
||||
using StarterNG.Tests.Fakes;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
|
||||
public class SettingReachTests
|
||||
{
|
||||
private static SimulatorTarget Linux(string renderer = "full", bool server = false) =>
|
||||
new(WindowsBuild: false, renderer, server);
|
||||
|
||||
[Theory]
|
||||
[InlineData("feedbackmode")]
|
||||
[InlineData("feedbackport")]
|
||||
[InlineData("showsystemconsole")]
|
||||
[InlineData("gfx.angleplatform")]
|
||||
public void Windows_only_keys_idle_on_a_linux_build(string key)
|
||||
{
|
||||
Assert.Equal(IdleReason.WindowsBuildOnly, SettingReach.Why(key, Linux()));
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux() with { WindowsBuild = true }));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("full", IdleReason.LegacyRendererOnly)]
|
||||
[InlineData("experimental", IdleReason.LegacyRendererOnly)]
|
||||
[InlineData("legacy", IdleReason.None)]
|
||||
[InlineData("simpleshader", IdleReason.None)]
|
||||
[InlineData("simple", IdleReason.None)]
|
||||
public void Legacy_renderer_keys_follow_the_renderer(string renderer, IdleReason expected)
|
||||
{
|
||||
Assert.Equal(expected, SettingReach.Why("smoothtraction", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("usevbo", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.shadows.cab.range", Linux(renderer)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pausing_in_the_background_needs_a_network_server()
|
||||
{
|
||||
Assert.Equal(IdleReason.NeedsNetworkServer, SettingReach.Why("inactivepause", Linux()));
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("inactivepause", Linux(server: true)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_starters_own_keys_never_idle()
|
||||
{
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("starter.autoclose", Linux()));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("width, height")]
|
||||
[InlineData("fullscreen")]
|
||||
public void The_monitors_own_mode_overrides_size_and_full_screen(string key)
|
||||
{
|
||||
Assert.Equal(IdleReason.MonitorModeInstead,
|
||||
SettingReach.Why(key, Linux() with { FullscreenWindowed = true }));
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_ordinary_key_works_everywhere()
|
||||
{
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("fieldofview", Linux()));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("full", IdleReason.None)]
|
||||
[InlineData("legacy", IdleReason.ModernRendererOnly)]
|
||||
[InlineData("experimental", IdleReason.ModernRendererOnly)]
|
||||
public void Effects_of_the_full_renderer_follow_the_renderer(string renderer, IdleReason expected)
|
||||
{
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.postfx.motionblur.enabled", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("sleeperdistance", Linux(renderer)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("vulkan", IdleReason.None)]
|
||||
[InlineData("vulkan14", IdleReason.None)]
|
||||
[InlineData("full", IdleReason.VulkanOnly)]
|
||||
[InlineData("gl46", IdleReason.VulkanOnly)]
|
||||
[InlineData("legacy", IdleReason.VulkanOnly)]
|
||||
public void What_only_vulkan_reads_follows_the_renderer(string renderer, IdleReason expected)
|
||||
{
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.dlss.preset", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.framegeneration", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.raytracing", Linux(renderer)));
|
||||
// Both renderers of the new simulator read this one.
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.postfx.ao", Linux(renderer)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("vulkan")]
|
||||
[InlineData("vulkan14")]
|
||||
[InlineData("opengl")]
|
||||
[InlineData("gl46")]
|
||||
public void The_new_simulators_renderers_read_what_the_full_one_does(string renderer)
|
||||
{
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("multisampling", Linux(renderer)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("full", IdleReason.None)]
|
||||
[InlineData("legacy", IdleReason.None)]
|
||||
[InlineData("experimental", IdleReason.OpenGlRenderersOnly)]
|
||||
public void The_experimental_renderer_passes_over_what_only_opengl_reads(string renderer, IdleReason expected)
|
||||
{
|
||||
Assert.Equal(expected, SettingReach.Why("multisampling", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("anisotropicfiltering", Linux(renderer)));
|
||||
Assert.Equal(expected, SettingReach.Why("gfx.smoke", Linux(renderer)));
|
||||
// ...but reads the rest of the reflections and shadows.
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.reflections.fidelity", Linux(renderer)));
|
||||
Assert.Equal(IdleReason.None, SettingReach.Why("shadowtune", Linux(renderer)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, 0, false)]
|
||||
[InlineData(0.0, 0, false)]
|
||||
[InlineData(60.0, 0, true)]
|
||||
[InlineData(null, 50, true)] // fpsaverage, the older regulator
|
||||
public void The_draw_range_factor_needs_a_regulator(double? targetFps, double fpsAverage, bool regulated)
|
||||
{
|
||||
var target = Linux() with { TargetFps = targetFps, FpsAverage = fpsAverage };
|
||||
|
||||
Assert.Equal(regulated ? IdleReason.None : IdleReason.NeedsFrameRateTarget,
|
||||
SettingReach.Why("gfx.drawrange.factor.max", target));
|
||||
}
|
||||
|
||||
// ── The rest of the target ───────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void A_windows_build_is_told_from_its_header()
|
||||
{
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
|
||||
.WithFile(TestInstallation.At("eu07.exe"), "MZ binary");
|
||||
var installation = new TestInstallation(files);
|
||||
|
||||
Assert.False(installation.Executables.IsWindowsBuild("eu07"));
|
||||
Assert.True(installation.Executables.IsWindowsBuild("eu07.exe"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_network_server_in_the_ini_is_noticed()
|
||||
{
|
||||
string ini = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
|
||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||
.WithFile(ini, "network.server tcp 0.0.0.0:7424\n"));
|
||||
installation.Environment.With("HOME", "/home/kolejarz");
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
Assert.True(installation.SettingsStore.Settings.NetworkServer);
|
||||
}
|
||||
}
|
||||
@@ -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", true, false, "mousescale -1.5 0.5")]
|
||||
[InlineData("mousescale -1.5 -0.5", false, false, "mousescale 1.5 0.5")]
|
||||
[InlineData("mousescale 2.5 0.123456", false, true, "mousescale 2.5 -0.123456")]
|
||||
[InlineData("mousescale 2.5 0.5", false, true, "mousescale 2.5 -0.5")]
|
||||
// Further than the slider goes.
|
||||
[InlineData("mousescale 12 0.5", true, false, "mousescale -12 0.5")]
|
||||
public void A_mouse_scale_keeps_its_numbers_when_an_axis_is_inverted(
|
||||
@@ -540,7 +540,35 @@ public class SettingsStoreTests
|
||||
|
||||
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 ────────────────────────────────────────
|
||||
@@ -885,12 +913,8 @@ public class SettingsStoreTests
|
||||
[InlineData("default")]
|
||||
[InlineData("simpleshader")]
|
||||
[InlineData("off")]
|
||||
[InlineData("opengl")]
|
||||
[InlineData("gl46")]
|
||||
[InlineData("vulkan14")]
|
||||
[InlineData("legacy")]
|
||||
[InlineData("simple")]
|
||||
[InlineData("experimental")]
|
||||
public void A_renderer_word_the_simulator_reads_as_another_stays_until_changed(string word)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
|
||||
@@ -901,16 +925,33 @@ public class SettingsStoreTests
|
||||
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
|
||||
}
|
||||
|
||||
// Words master does not know start the full renderer with a line in its log, and the
|
||||
// experimental renderer is not in a player's build: a save puts "default" in their place.
|
||||
[Theory]
|
||||
[InlineData(0, "full")]
|
||||
[InlineData("full")]
|
||||
[InlineData("opengl")]
|
||||
[InlineData("gl46")]
|
||||
[InlineData("vulkan14")]
|
||||
[InlineData("experimental")]
|
||||
[InlineData("null")]
|
||||
public void A_renderer_word_master_does_not_run_is_saved_as_default(string word)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Contains("gfxrenderer default\n", SavedLines(installation));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "default")]
|
||||
[InlineData(1, "legacy")]
|
||||
[InlineData(2, "simple")]
|
||||
[InlineData(3, "experimental")]
|
||||
[InlineData(4, "vulkan")]
|
||||
public void A_chosen_renderer_is_saved_as_the_simulator_reads_it(int engine, string saved)
|
||||
{
|
||||
// application.cpp knows full (or default), experimental and simple; every
|
||||
// other word - "simpleshader" and "off" from older starters - is legacy.
|
||||
// application.cpp on master knows default, legacy and simple; "simpleshader" and "off"
|
||||
// from older starters are legacy, and any other word gets the full renderer.
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine;
|
||||
@@ -926,8 +967,10 @@ public class SettingsStoreTests
|
||||
[InlineData("full", 0)]
|
||||
[InlineData("gl46", 0)]
|
||||
[InlineData("opengl", 0)]
|
||||
[InlineData("vulkan", 4)]
|
||||
[InlineData("VULKAN14", 4)]
|
||||
[InlineData("vulkan", 0)]
|
||||
[InlineData("VULKAN14", 0)]
|
||||
[InlineData("whatever", 0)]
|
||||
[InlineData("experimental", 0)]
|
||||
[InlineData("simpleshader", 1)]
|
||||
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine)
|
||||
{
|
||||
@@ -935,7 +978,7 @@ public class SettingsStoreTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_buffer_is_written_for_old_and_new_simulators()
|
||||
public void The_buffer_is_written_as_the_framebuffer_master_reads()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1000\nheight 500\n"));
|
||||
installation.SettingsStore.Load();
|
||||
@@ -944,19 +987,20 @@ public class SettingsStoreTests
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
string saved = SavedLines(installation);
|
||||
Assert.Contains("gfx.buffer.percent 50\n", saved);
|
||||
Assert.DoesNotContain("gfx.buffer.percent", saved);
|
||||
Assert.Contains("gfx.framebuffer.width 500\n", saved);
|
||||
Assert.Contains("gfx.framebuffer.height 250\n", saved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("gfx.buffer.percent 0.5\n", 50)]
|
||||
[InlineData("gfx.buffer.percent 75\n", 75)]
|
||||
[InlineData("gfx.buffer.percent 10\n", 25)]
|
||||
[InlineData("gfx.buffer.percent 300\n", 200)]
|
||||
[InlineData("width 1000\ngfx.framebuffer.width 500\n", 50)]
|
||||
[InlineData("width 1000\ngfx.framebuffer.width 100\n", 25)]
|
||||
[InlineData("width 1000\ngfx.framebuffer.width 3000\n", 100)]
|
||||
[InlineData("gfx.framebuffer.width 500\n", 100)]
|
||||
[InlineData("starter.bufferscale 60\n", 60)]
|
||||
[InlineData("starter.bufferscale 60\ngfx.buffer.percent 80\n", 80)]
|
||||
public void The_buffer_is_read_from_the_key_the_new_simulator_goes_by(string ini, int percent)
|
||||
[InlineData("starter.bufferscale 60\nwidth 1000\ngfx.framebuffer.width 800\n", 60)]
|
||||
[InlineData("gfx.buffer.percent 0.5\n", 100)]
|
||||
public void The_buffer_is_read_from_the_starters_key_or_the_framebuffer(string ini, int percent)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
|
||||
@@ -965,36 +1009,6 @@ public class SettingsStoreTests
|
||||
Assert.Equal(percent, installation.SettingsStore.Settings.BufferScalePercent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_two_anti_aliasing_keys_untouched_keep_their_order()
|
||||
{
|
||||
// Moving them would change which of the two the simulator goes by.
|
||||
const string ini = "gfx.antialiasing taa\nwidth 800\nmultisampling 2\n";
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
string saved = SavedLines(installation);
|
||||
Assert.True(saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal) < saved.IndexOf("multisampling 2", StringComparison.Ordinal), saved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_chosen_anti_aliasing_is_saved_below_multisampling_for_the_later_line_to_count()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfx.antialiasing msaax4\nwidth 800\nmultisampling 2\n"));
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
installation.SettingsStore.Settings.AntiAliasing = AntiAliasingMode.Taa;
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
string saved = SavedLines(installation);
|
||||
Assert.True(saved.IndexOf("multisampling ", StringComparison.Ordinal) < saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal), saved);
|
||||
var again = WithHome(installation.Files);
|
||||
again.SettingsStore.Load();
|
||||
Assert.Equal(AntiAliasingMode.Taa, again.SettingsStore.Settings.AntiAliasing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_field_of_view_down_to_ten_degrees_survives_a_save()
|
||||
{
|
||||
@@ -1257,6 +1271,39 @@ public class SettingsStoreTests
|
||||
Assert.False(store.LoadFailed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_profile_from_before_the_tapes_of_the_trains_is_moved_as_the_ini_would_be()
|
||||
{
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithFile(UserIni, "physicslog no\nphysicslog.trains no\n")
|
||||
.WithFile(Profile, "physicslog yes\nblackbox yes\n");
|
||||
var store = WithHome(files).SettingsStore;
|
||||
store.Load();
|
||||
|
||||
Assert.True(store.TryLoadProfile(Profile));
|
||||
store.Save();
|
||||
|
||||
Assert.False(store.Settings.PhysicsLog);
|
||||
Assert.True(store.Settings.PhysicsLogTrains);
|
||||
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_profile_exported_from_a_pages_edits_leaves_the_settings_held_and_the_ini_alone()
|
||||
{
|
||||
var files = new InMemoryFileSystem().WithFile(UserIni, "fieldofview 45\n");
|
||||
var store = WithHome(files).SettingsStore;
|
||||
store.Load();
|
||||
var edited = store.Settings.Copy();
|
||||
edited.FieldOfView = 60;
|
||||
|
||||
Assert.True(store.ExportTo(Profile, edited));
|
||||
|
||||
Assert.Contains("fieldofview 60", files.ReadAllText(Profile, System.Text.Encoding.UTF8));
|
||||
Assert.Equal(45, store.Settings.FieldOfView);
|
||||
Assert.Contains("fieldofview 45", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_missing_profile_leaves_the_settings_as_they_are()
|
||||
{
|
||||
@@ -1302,4 +1349,189 @@ public class SettingsStoreTests
|
||||
Assert.False(store.LoadFailed);
|
||||
Assert.Equal(60, store.Settings.FieldOfView);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("physicslog yes\n", true)]
|
||||
[InlineData("physicslog no\n", false)]
|
||||
[InlineData("physicslog yes\nblackbox no\n", false)]
|
||||
[InlineData("physicslog no\nblackbox yes\n", true)]
|
||||
public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tapes_turned_on_write_the_black_box_and_leave_the_physics_log_off()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.BlackBox = true;
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.Width = 1600;
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Null(LineFor(installation, "blackbox"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("physicslog yes\nblackbox yes\n")]
|
||||
[InlineData("physicslog no\nblackbox yes\n")]
|
||||
public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.BlackBox = false;
|
||||
installation.SettingsStore.Settings.PhysicsLog = false;
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Equal("blackbox no", LineFor(installation, "blackbox"));
|
||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_physics_log_turned_off_keeps_the_tapes_it_brought()
|
||||
{
|
||||
// an ini of before the black box had a key: the tapes came with the physics log
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.PhysicsLog = false;
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("physicslog no\n", false, false)]
|
||||
[InlineData("physicslog no\nphysicslog.trains yes\n", true, true)]
|
||||
[InlineData("physicslog no\nphysicslog.trains yes\nblackbox no\n", true, false)]
|
||||
public void The_logs_of_the_trains_are_read_and_bring_the_black_box_as_the_simulator_has_it(string ini, bool trains, bool recorded)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
Assert.Equal(trains, installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("physicslog yes\nblackbox yes\n")]
|
||||
[InlineData("physicslog no\nblackbox yes\n")]
|
||||
public void Recording_turned_on_before_the_tapes_of_the_trains_is_moved_to_them(string ini)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
var s = installation.SettingsStore.Settings;
|
||||
Assert.False(s.PhysicsLog);
|
||||
Assert.True(s.PhysicsLogTrains);
|
||||
Assert.True(s.BlackBox);
|
||||
|
||||
installation.SettingsStore.Save();
|
||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
||||
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("physicslog yes\n", true)]
|
||||
[InlineData("physicslog yes\nblackbox no\n", true)]
|
||||
[InlineData("physicslog yes\nblackbox yes\nphysicslog.trains no\n", true)]
|
||||
[InlineData("physicslog no\nblackbox yes\nphysicslog.trains no\n", false)]
|
||||
public void Without_a_black_box_line_saying_yes_or_with_the_trains_tapes_line_nothing_is_moved(string ini, bool physicsLog)
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
Assert.Equal(physicsLog, installation.SettingsStore.Settings.PhysicsLog);
|
||||
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is()
|
||||
{
|
||||
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
|
||||
var files = new InMemoryFileSystem()
|
||||
.WithFile(UserIni, "physicslog yes\nphysicslog.trains no\n")
|
||||
.WithFile(backup, "physicslog yes\nblackbox yes\n");
|
||||
var store = WithHome(files).SettingsStore;
|
||||
store.Load();
|
||||
|
||||
Assert.True(store.ImportFrom(backup));
|
||||
store.Save();
|
||||
|
||||
Assert.False(store.Settings.PhysicsLog);
|
||||
Assert.True(store.Settings.PhysicsLogTrains);
|
||||
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\nblackbox yes\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.PhysicsLog = true;
|
||||
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
|
||||
Assert.True(installation.SettingsStore.Settings.PhysicsLog);
|
||||
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
||||
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Save();
|
||||
Assert.Null(LineFor(installation, "physicslog.trains"));
|
||||
|
||||
installation.SettingsStore.Settings.PhysicsLogTrains = true;
|
||||
installation.SettingsStore.Settings.BlackBox = true;
|
||||
installation.SettingsStore.Save();
|
||||
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
||||
// it says no more than the logs of the trains bring
|
||||
Assert.Null(LineFor(installation, "blackbox"));
|
||||
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
||||
installation.SettingsStore.Save();
|
||||
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_black_box_line_written_once_goes_away_when_it_says_no_more()
|
||||
{
|
||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
||||
installation.SettingsStore.Load();
|
||||
installation.SettingsStore.Settings.BlackBox = true;
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
installation.SettingsStore.Settings.BlackBox = false;
|
||||
installation.SettingsStore.Save();
|
||||
|
||||
Assert.Null(LineFor(installation, "blackbox"));
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes()
|
||||
{
|
||||
var (start, _, installation) = Rig(files => files.WithExecutable(Build), sceneryClock: "07:52");
|
||||
installation.SettingsStore.Settings.BlackBox = true;
|
||||
|
||||
start.Execute(freeFly: false, saveSettings: false);
|
||||
|
||||
string noted = installation.Files.ReadAllText(TestInstallation.At("physicslog", "starter-launch.txt"));
|
||||
Assert.Contains("clock\t07:52", noted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_the_physics_log_nothing_is_noted()
|
||||
{
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using StarterNG.Classes;
|
||||
using StarterNG.Domain;
|
||||
using StarterNG.Domain.Settings;
|
||||
using StarterNG.Views;
|
||||
|
||||
namespace StarterNG.Tests;
|
||||
@@ -58,6 +59,63 @@ public class TrainsetDisplayTests
|
||||
Assert.False(TrainsetDisplay.ListedIn(picked, showAi: false, drivableOnly: true, current: picked));
|
||||
}
|
||||
|
||||
private static SimulatorSettings Mode(bool advanced) =>
|
||||
new() { AdvancedSettings = advanced, ShowAiVehicles = true, DrivableOnly = false };
|
||||
|
||||
[Fact]
|
||||
public void The_standard_mode_lists_every_consist_but_starts_only_in_one_a_player_drives()
|
||||
{
|
||||
var standard = Mode(advanced: false);
|
||||
var decor = new Trainset("trainset a tor 0 0 //$decor\nnode -1 0 v1 dynamic d s m 0 headdriver 3 0 enddynamic\nendtrainset");
|
||||
Assert.True(decor.Decor);
|
||||
|
||||
foreach (var consist in new[] { Consist(), Consist(description: "-ai"), Consist(driver: "nobody"), decor })
|
||||
Assert.True(TrainsetDisplay.ListedIn(consist, standard, current: null));
|
||||
|
||||
Assert.True(TrainsetDisplay.StartableIn(Consist(), standard));
|
||||
Assert.True(TrainsetDisplay.StartableIn(Consist(driver: "nobody"), standard));
|
||||
Assert.False(TrainsetDisplay.StartableIn(Consist(description: "-ai"), standard));
|
||||
Assert.False(TrainsetDisplay.StartableIn(decor, standard));
|
||||
Assert.True(TrainsetDisplay.StartableIn(decor, Mode(advanced: true)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_filters_work_in_the_advanced_mode()
|
||||
{
|
||||
var settings = Mode(advanced: true);
|
||||
|
||||
settings.ShowAiVehicles = false;
|
||||
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), settings, current: null));
|
||||
Assert.True(TrainsetDisplay.ListedIn(Consist(), settings, current: null));
|
||||
|
||||
settings.DrivableOnly = true;
|
||||
Assert.False(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), settings, current: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_standard_mode_has_no_filters_and_leaves_out_empty_consists()
|
||||
{
|
||||
var standard = new SimulatorSettings { AdvancedSettings = false, ShowAiVehicles = false, DrivableOnly = true };
|
||||
var empty = new Trainset("trainset a tor 0 0\nendtrainset");
|
||||
|
||||
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), standard, current: null));
|
||||
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), standard, current: null));
|
||||
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: null));
|
||||
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_advanced_mode_lists_by_its_own_filters()
|
||||
{
|
||||
var advanced = Mode(advanced: true);
|
||||
|
||||
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
|
||||
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), advanced, current: null));
|
||||
|
||||
advanced.ShowAiVehicles = false;
|
||||
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(eDriverType.Headdriver, 0)]
|
||||
[InlineData(eDriverType.Reardriver, 1)]
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace StarterNG.Tests;
|
||||
|
||||
// PresetStore keeps the disk of the first test that reaches it, a fake one as every
|
||||
// composition root in the tests is built on fakes. So each test has a name to itself.
|
||||
// Puts in services of its own: not while the controls read theirs.
|
||||
[Collection(AvaloniaControls.Name)]
|
||||
public class WarehouseEditTests
|
||||
{
|
||||
private const string Text =
|
||||
@@ -96,6 +98,23 @@ public class WarehouseEditTests
|
||||
Assert.Null(Stored("edit-changed"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_write_tells_the_list_the_name_and_the_entry_and_no_write_tells_nothing()
|
||||
{
|
||||
var told = new List<(string Name, string Entry)>();
|
||||
_edit.Saved += (name, entry) => told.Add((name, entry));
|
||||
var trainset = _edit.Open(Preset("edit-told"));
|
||||
|
||||
_edit.Save();
|
||||
Assert.Empty(told);
|
||||
|
||||
trainset.Vehicles.Add(trainset.Vehicles[0].Clone());
|
||||
_edit.Save();
|
||||
|
||||
Assert.Equal([("edit-told", ConsistText.Serialize(trainset))], told);
|
||||
PresetStore.Delete("edit-told");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Nothing_is_written_with_nothing_open()
|
||||
{
|
||||
|
||||
@@ -207,8 +207,12 @@ public partial class App : Avalonia.Application
|
||||
if (check.ExecutableMissing())
|
||||
await main.OfferExecutablePickAsync();
|
||||
|
||||
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
|
||||
await main.ShowCpuNoticeAsync();
|
||||
// A build without AVX2 in the folder is started instead, and needs no notice.
|
||||
var services = AppServices.Current;
|
||||
if (services.Settings.CpuNotice
|
||||
&& services.Executables.Resolve(services.Settings, out _) is var executable
|
||||
&& services.Executables.WillNotRunHere(executable))
|
||||
await main.ShowCpuNoticeAsync(executable);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,13 +63,12 @@ public sealed class AppServices
|
||||
SceneryFiles = new SceneryFileWatch(files, Sceneries, Library, State);
|
||||
|
||||
Executables = new ExecutableLocator(files, paths, environment, log);
|
||||
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(dlssPlatform: !environment.IsMacOS), Executables);
|
||||
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(), Executables);
|
||||
MissingVehicleLog = new MissingVehicleLog(SettingsStore.Settings, missingAssets, Library, log);
|
||||
Favorites = new FavoriteSceneries(files, log, settingsPaths.FavoritesPath());
|
||||
Tapes = new HaslerTapes(files, paths, log, clock, Timetables, () => State.SimulatorRunning);
|
||||
Gpus = new LinuxGpus(files, environment);
|
||||
GraphicsCards = new GraphicsCards(files, environment, Gpus);
|
||||
Displays = new Displays(files, environment);
|
||||
StartSimulation = new StartSimulation(State, SettingsStore, Library.Vehicles, Executables,
|
||||
files, paths, Processes, random, log, Gpus, environment,
|
||||
new WineConfigLink(files, environment, settingsPaths, log), Tapes);
|
||||
@@ -141,8 +140,6 @@ public sealed class AppServices
|
||||
|
||||
public GraphicsCards GraphicsCards { get; }
|
||||
|
||||
public Displays Displays { get; }
|
||||
|
||||
public SettingsPaths SettingsPaths { get; }
|
||||
|
||||
public MissingVehicleLog MissingVehicleLog { get; }
|
||||
|
||||
@@ -35,6 +35,7 @@ public sealed class HaslerTapes
|
||||
{
|
||||
private const int RememberedLaunches = 30;
|
||||
private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2);
|
||||
private static readonly TimeSpan TapesAfterBlackBox = TimeSpan.FromSeconds(10);
|
||||
|
||||
private readonly IFileSystem _files;
|
||||
private readonly IGamePaths _paths;
|
||||
@@ -244,8 +245,9 @@ public sealed class HaslerTapes
|
||||
/// <summary>
|
||||
/// The runs the tapes came from, the running or latest one first. A tape belongs
|
||||
/// to the last launch before it was written, unless a run the starter didn't launch
|
||||
/// began between them; one with no launch goes with those written about the same
|
||||
/// time, as a run writes them all at its end.
|
||||
/// began between them; one with no launch goes with the black box recording when it
|
||||
/// was written, or else with those written about the same time, as a run writes its
|
||||
/// logs until it ends.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TapeSession> Sessions()
|
||||
{
|
||||
@@ -278,11 +280,15 @@ public sealed class HaslerTapes
|
||||
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
|
||||
}
|
||||
|
||||
// What no launch covers goes together by when it was written: a run writes it all at its end.
|
||||
// What no launch covers goes together by when it was written: a run writes its logs until it ends. A tape
|
||||
// written while a black box recorded is of its run, though: the black box writes the tapes of the player's
|
||||
// vehicles as it goes, and that of a vehicle the player left ends before the run does.
|
||||
var looseBoxes = boxes.Where(b => LaunchOf(b, launches) is null).ToList();
|
||||
var recordings = Recordings(looseBoxes);
|
||||
var loose = tapes.Where(t => tapeLaunch[t] is null)
|
||||
.Select(t => (Written: t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
||||
.Concat(boxes.Where(b => LaunchOf(b, launches) is null)
|
||||
.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
||||
.Select(t => (Written: RecordingAt(t.LastWriteUtc, recordings)?.LastWriteUtc ?? t.LastWriteUtc,
|
||||
Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
||||
.Concat(looseBoxes.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
||||
.OrderBy(file => file.Written);
|
||||
var run = new List<TapeFile>();
|
||||
var runBoxes = new List<BlackBoxRecording>();
|
||||
@@ -315,6 +321,39 @@ public sealed class HaslerTapes
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When each black box recorded, its name read once: from the start its name has, to when it was last written,
|
||||
/// and the tapes a moment after. No longer than until the next one started, though: a box downloaded or copied
|
||||
/// later was last written then, not when it stopped, and would take in the tapes of the runs since.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> Recordings(IEnumerable<BlackBoxRecording> boxes)
|
||||
{
|
||||
var named = boxes.Select(box => (Box: box, Named: NamedBy(box.Path)))
|
||||
.Where(each => each.Named is not null)
|
||||
.Select(each => (each.Box, FromUtc: each.Named!.Value.StartedUtc))
|
||||
.OrderBy(each => each.FromUtc)
|
||||
.ToList();
|
||||
var recordings = new List<(BlackBoxRecording, DateTime, DateTime)>(named.Count);
|
||||
for (int i = 0; i < named.Count; i++)
|
||||
{
|
||||
var to = named[i].Box.LastWriteUtc + TapesAfterBlackBox;
|
||||
if (i + 1 < named.Count && named[i + 1].FromUtc < to)
|
||||
to = named[i + 1].FromUtc;
|
||||
recordings.Add((named[i].Box, named[i].FromUtc, to));
|
||||
}
|
||||
return recordings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The black box that was recording at the moment, the tapes being written last, a moment after it is closed.
|
||||
/// Of more, the one that stopped nearest to it.
|
||||
/// </summary>
|
||||
public static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> recordings) =>
|
||||
recordings.Where(each => each.FromUtc <= momentUtc && momentUtc <= each.ToUtc)
|
||||
.OrderBy(each => (each.Box.LastWriteUtc - momentUtc).Duration())
|
||||
.Select(each => each.Box)
|
||||
.FirstOrDefault();
|
||||
|
||||
private TapeFile ReadTape(string path) =>
|
||||
new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path));
|
||||
|
||||
@@ -411,19 +450,88 @@ public sealed class HaslerTapes
|
||||
return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded);
|
||||
}
|
||||
|
||||
public HaslerTape? Load(TapeFile file)
|
||||
// the tape followed as the simulator writes it: what of its file was read, and where it ended
|
||||
private readonly object _followedLock = new();
|
||||
private (string Path, long Read, byte[] Tail, HaslerTape.Reader Reader)? _followed;
|
||||
// what of the end of the read part is kept, to tell the file still has it: one begun anew doesn't
|
||||
private const int FollowedTail = 256;
|
||||
|
||||
public HaslerTape? Load(TapeFile file) => Load(file, follow: false);
|
||||
|
||||
/// <summary>
|
||||
/// The tape of this file no longer followed: what was kept of it is let go. Another file's, followed for another
|
||||
/// window, stays.
|
||||
/// </summary>
|
||||
public void Forget(string path)
|
||||
{
|
||||
try
|
||||
lock (_followedLock)
|
||||
if (_followed?.Path == path)
|
||||
_followed = null;
|
||||
}
|
||||
|
||||
// what the file has between the two: less, up to its end, when it was cut shorter since its length was taken
|
||||
private static byte[] Bytes(Stream stream, long from, long to)
|
||||
{
|
||||
stream.Seek(from, SeekOrigin.Begin);
|
||||
var bytes = new byte[to - from];
|
||||
int read = stream.ReadAtLeast(bytes, bytes.Length, throwOnEndOfStream: false);
|
||||
return read == bytes.Length ? bytes : bytes[..read];
|
||||
}
|
||||
|
||||
// the end of what was read, after the part added to it
|
||||
private static byte[] Tail(byte[] before, byte[] added)
|
||||
{
|
||||
if (added.Length >= FollowedTail)
|
||||
return added[^FollowedTail..];
|
||||
var keptBefore = Math.Min(before.Length, FollowedTail - added.Length);
|
||||
return [.. before[^keptBefore..], .. added];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tape of the file. Followed, the one read last and grown since: only what was added is read, so a log
|
||||
/// written fast, at a higher time speed, is kept up with; a line not ended yet waits for the next time. Not
|
||||
/// followed, or another file, or one shorter than was read - begun anew - it is read whole, and kept to be
|
||||
/// followed from there.
|
||||
/// </summary>
|
||||
public HaslerTape? Load(TapeFile file, bool follow)
|
||||
{
|
||||
lock (_followedLock)
|
||||
{
|
||||
// Through OpenRead, which does not mind the simulator still writing the file.
|
||||
using var stream = _files.OpenRead(file.Path);
|
||||
using var reader = new StreamReader(stream, Encoding.ASCII);
|
||||
return HaslerTape.Parse(reader.ReadToEnd());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Log($"reading {file.Path}", ex);
|
||||
return null;
|
||||
try
|
||||
{
|
||||
// Through OpenRead, which does not mind the simulator still writing the file.
|
||||
using var stream = _files.OpenRead(file.Path);
|
||||
if (!stream.CanSeek)
|
||||
{
|
||||
_followed = null;
|
||||
using var whole = new StreamReader(stream, Encoding.ASCII);
|
||||
return HaslerTape.Parse(whole.ReadToEnd());
|
||||
}
|
||||
|
||||
long length = stream.Length;
|
||||
// the same file grown, its end as it was read: else another, or begun anew, read whole
|
||||
if (!follow || _followed is not { } followed || followed.Path != file.Path || length < followed.Read
|
||||
|| !Bytes(stream, followed.Read - followed.Tail.Length, followed.Read).AsSpan().SequenceEqual(followed.Tail))
|
||||
followed = (file.Path, 0, Array.Empty<byte>(), new HaslerTape.Reader());
|
||||
// what was read, not the length taken before: the file may be cut shorter meanwhile
|
||||
var added = Bytes(stream, followed.Read, length);
|
||||
followed.Reader.Feed(Encoding.ASCII.GetString(added));
|
||||
// the time went back in what was added: the log begun anew and already longer than was read
|
||||
if (followed.Read > 0 && followed.Reader.WentBack)
|
||||
{
|
||||
followed = (file.Path, 0, Array.Empty<byte>(), new HaslerTape.Reader());
|
||||
added = Bytes(stream, 0, length);
|
||||
followed.Reader.Feed(Encoding.ASCII.GetString(added));
|
||||
}
|
||||
_followed = (file.Path, followed.Read + added.Length, Tail(followed.Tail, added), followed.Reader);
|
||||
return followed.Reader.Tape(final: !follow);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_followed = null;
|
||||
_log.Log($"reading {file.Path}", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -75,6 +76,9 @@ public sealed class SettingsStore
|
||||
|
||||
public string SavePath => _savePath;
|
||||
|
||||
/// <summary>The last save found eu07.ini changed by something else and kept those changes: what is held was read again.</summary>
|
||||
public bool LastSaveMerged { get; private set; }
|
||||
|
||||
public void RegisterCapture(ISettingsCapture capture) => _capture = capture;
|
||||
|
||||
public void Load()
|
||||
@@ -92,9 +96,30 @@ public sealed class SettingsStore
|
||||
return;
|
||||
|
||||
GraphicsPreset.High.ApplyTo(Settings);
|
||||
// Nothing of an older starter to bring over: the settings start in the standard mode.
|
||||
Settings.MovedToStandard = true;
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy of eu07.ini beside it, the file name and <paramref name="suffix"/>, before
|
||||
/// something changes many keys at once; one already there is left as it is.
|
||||
/// </summary>
|
||||
public void KeepCopy(string suffix)
|
||||
{
|
||||
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
|
||||
string copy = path + suffix;
|
||||
try
|
||||
{
|
||||
if (_files.FileExists(path) && !_files.FileExists(copy))
|
||||
_files.CopyFile(path, copy, overwrite: false);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_log.Log($"{copy} could not be made: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void LoadFrom(string path)
|
||||
{
|
||||
try
|
||||
@@ -113,6 +138,9 @@ public sealed class SettingsStore
|
||||
|
||||
_serializer.Read(Settings, _config);
|
||||
_synced = Render(Settings);
|
||||
// after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would
|
||||
if (!LoadFailed)
|
||||
SettingsSerializer.MoveToTrainTapes(Settings);
|
||||
TouchConfigAge();
|
||||
}
|
||||
|
||||
@@ -157,8 +185,30 @@ public sealed class SettingsStore
|
||||
return;
|
||||
}
|
||||
|
||||
// Edited by other hands since it was read or written here: their file is what the changes
|
||||
// go onto, so a key the player left alone keeps what was put there meanwhile.
|
||||
bool merged = false;
|
||||
if (string.Equals(path, _savePath, StringComparison.Ordinal) && IsConfigNewerOnDisk())
|
||||
{
|
||||
try
|
||||
{
|
||||
_config = ConfigFile.Parse(_files.ReadAllText(path, _encoding));
|
||||
merged = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Log($"re-reading {path} before saving", ex);
|
||||
}
|
||||
}
|
||||
|
||||
ApplyChanges(_config, Changes(Settings));
|
||||
if (merged)
|
||||
{
|
||||
// What is held follows the file: the player's changes and the others' together.
|
||||
_serializer.Read(Settings, _config);
|
||||
}
|
||||
_synced = Render(Settings);
|
||||
LastSaveMerged = merged;
|
||||
|
||||
try
|
||||
{
|
||||
@@ -185,16 +235,8 @@ public sealed class SettingsStore
|
||||
else
|
||||
config.Set(change.Key, change.After);
|
||||
}
|
||||
|
||||
// Each sets the mode as the simulator reads it, so the new one has to come later to count.
|
||||
// Untouched, the two keep their order: moving them would change which one decides.
|
||||
if (changes.Any(change => change.Key is "gfx.antialiasing" or "multisampling"))
|
||||
config.MoveAfter("gfx.antialiasing", "multisampling");
|
||||
}
|
||||
|
||||
/// <summary>Whether the simulator can have DLSS on this platform at all.</summary>
|
||||
public bool DlssPlatform => _serializer.DlssPlatform;
|
||||
|
||||
/// <summary>
|
||||
/// Takes the settings of another eu07.ini (a backup, a file from another machine)
|
||||
/// into the current ones, keeping what belongs to this installation: the chosen
|
||||
@@ -220,9 +262,6 @@ public sealed class SettingsStore
|
||||
var gpu = s.Gpu;
|
||||
string lastScenery = s.LastScenery;
|
||||
bool maximized = s.WindowMaximized;
|
||||
// Only read for the dependencies and never written, so they stay as this user's file has them.
|
||||
bool cabLampLight = s.CabLampLight;
|
||||
bool depthPrepassScene = s.DepthPrepassScene;
|
||||
|
||||
_serializer.Read(s, imported);
|
||||
|
||||
@@ -231,8 +270,8 @@ public sealed class SettingsStore
|
||||
s.Gpu = gpu;
|
||||
s.LastScenery = lastScenery;
|
||||
s.WindowMaximized = maximized;
|
||||
s.CabLampLight = cabLampLight;
|
||||
s.DepthPrepassScene = depthPrepassScene;
|
||||
// an ini of before the tapes of the trains goes the same way as a profile
|
||||
SettingsSerializer.MoveToTrainTapes(s);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -240,7 +279,8 @@ public sealed class SettingsStore
|
||||
/// Writes the settings as a complete eu07.ini somewhere else - this user's file
|
||||
/// with the settings applied - leaving the file itself and its state alone.
|
||||
/// </summary>
|
||||
public bool ExportTo(string path)
|
||||
/// <param name="settings">What to write, when not the settings held: a page's edits, still not taken in.</param>
|
||||
public bool ExportTo(string path, SimulatorSettings? settings = null)
|
||||
{
|
||||
if (LoadFailed)
|
||||
{
|
||||
@@ -249,7 +289,7 @@ public sealed class SettingsStore
|
||||
}
|
||||
|
||||
var copy = ConfigFile.Parse(_config.ToText());
|
||||
ApplyChanges(copy, Changes(Settings));
|
||||
ApplyChanges(copy, Changes(settings ?? Settings));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -278,6 +318,86 @@ public sealed class SettingsStore
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys the starter knows that the file gives a value it cannot read, with that value:
|
||||
/// the setting shows its default, while the file keeps its own until the setting is changed.
|
||||
/// A value read another way (tak, 1.0, a clamped number) is no unknown one.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, string> UnreadableValues()
|
||||
{
|
||||
var unreadable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
var defaults = Render(WithFile(new ConfigFile()));
|
||||
var read = Render(WithFile(_config));
|
||||
var overCap = SettingsSerializer.OverCapKeys(_config);
|
||||
foreach (var (key, fallback) in defaults)
|
||||
{
|
||||
// Read, only brought down to the cap.
|
||||
if (NotReadAlone.Contains(key) || overCap.Contains(key))
|
||||
continue;
|
||||
if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw)
|
||||
continue;
|
||||
if (read.TryGetValue(key, out string? shown) && shown == fallback && !SameValue(raw, shown))
|
||||
unreadable[key] = raw;
|
||||
}
|
||||
|
||||
foreach (var key in SimulatorKeys.All)
|
||||
{
|
||||
if (_config.IsPastEnd(key.Key) || _config.GetRaw(key.Key) is not { Length: > 0 } raw)
|
||||
continue;
|
||||
string first = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)[0];
|
||||
bool readable = key.Kind switch
|
||||
{
|
||||
SimulatorKeyKind.Toggle => Bool(first) is not null,
|
||||
SimulatorKeyKind.Number => double.TryParse(first, NumberStyles.Float, CultureInfo.InvariantCulture, out _),
|
||||
_ => true
|
||||
};
|
||||
if (!readable)
|
||||
unreadable[key.Key] = raw;
|
||||
}
|
||||
return unreadable;
|
||||
}
|
||||
|
||||
// Written from other keys, or rewritten on purpose whatever they say: what they hold is no setting of their own.
|
||||
private static readonly HashSet<string> NotReadAlone = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"mousescale", "gfxrenderer", "gfx.shadowmap.enabled", "gfx.framebuffer.width", "gfx.framebuffer.height"
|
||||
};
|
||||
|
||||
private SimulatorSettings WithFile(ConfigFile config)
|
||||
{
|
||||
var s = new SimulatorSettings();
|
||||
_serializer.Read(s, config);
|
||||
return s;
|
||||
}
|
||||
|
||||
// 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>
|
||||
/// What saving <paramref name="settings"/> would change in the file: the keys
|
||||
/// changed since it was read, those it lacks, and the ones no simulator reads.
|
||||
@@ -290,6 +410,8 @@ public sealed class SettingsStore
|
||||
var shown = _capture?.ShownUnlikeSettings ?? new Dictionary<string, ShownValue>();
|
||||
var changes = new List<IniChange>();
|
||||
var listed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
// Above the starter's caps the file is brought down, though nothing on screen moved.
|
||||
var overCap = SettingsSerializer.OverCapKeys(_config);
|
||||
|
||||
foreach (string key in SettingsSerializer.ObsoleteKeys)
|
||||
Add(key, null);
|
||||
@@ -316,6 +438,14 @@ public sealed class SettingsStore
|
||||
return Uart.FeaturesStand(_config.GetRaw(key), value);
|
||||
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
|
||||
return _config.GetRaw(key) == value;
|
||||
if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) &&
|
||||
!SimulatorSettings.KeptRendererWord(_config.GetRaw(key)))
|
||||
return false;
|
||||
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
|
||||
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
|
||||
return false;
|
||||
if (overCap.Contains(key))
|
||||
return false;
|
||||
string? synced = _synced.GetValueOrDefault(key);
|
||||
if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced)
|
||||
return true;
|
||||
|
||||
@@ -144,7 +144,7 @@ public sealed class StartSimulation
|
||||
if (saveSettings)
|
||||
_settings.CaptureAndSave();
|
||||
|
||||
if (_settings.Settings.PhysicsLog)
|
||||
if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox || _settings.Settings.PhysicsLogTrains)
|
||||
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
|
||||
|
||||
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)
|
||||
|
||||
@@ -58,5 +58,9 @@ public sealed class WarehouseEdit
|
||||
|
||||
PresetStore.Save(Name, entry);
|
||||
_saved = entry;
|
||||
Saved?.Invoke(Name, entry);
|
||||
}
|
||||
|
||||
/// <summary>The consist was written under its name, with this entry - for the list showing it.</summary>
|
||||
public event Action<string, string>? Saved;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ public sealed class ConfigFile
|
||||
// Its first line, or -1 when the file runs to its end.
|
||||
private int _end = -1;
|
||||
|
||||
// While lines are indexed: the one at hand starts inside a block comment.
|
||||
private bool _inBlock;
|
||||
|
||||
public static ConfigFile Parse(string text)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
@@ -37,7 +40,10 @@ public sealed class ConfigFile
|
||||
|
||||
private void IndexLine(int line)
|
||||
{
|
||||
if (!TryParseKey(_lines[line], out string key))
|
||||
// The simulator skips what /* */ encloses, over as many lines as it runs.
|
||||
bool startsInBlock = _inBlock;
|
||||
_inBlock = EndsInBlock(_lines[line], startsInBlock);
|
||||
if (startsInBlock || !TryParseKey(_lines[line], out string key))
|
||||
return;
|
||||
|
||||
if (_end < 0 && key.Equals(EndKey, StringComparison.OrdinalIgnoreCase))
|
||||
@@ -52,6 +58,7 @@ public sealed class ConfigFile
|
||||
{
|
||||
_index.Clear();
|
||||
_end = -1;
|
||||
_inBlock = false;
|
||||
for (int line = 0; line < _lines.Count; line++)
|
||||
IndexLine(line);
|
||||
}
|
||||
@@ -252,17 +259,53 @@ public sealed class ConfigFile
|
||||
}
|
||||
}
|
||||
|
||||
// Where a comment starts as the simulator's parser sees one: // or /* anywhere, even glued
|
||||
// to a value, but not within quotes, which it keeps whole.
|
||||
private static int FindCommentStart(string body)
|
||||
{
|
||||
for (int i = 0; i + 1 < body.Length; i++)
|
||||
bool quoted = false;
|
||||
for (int i = 0; i < body.Length; i++)
|
||||
{
|
||||
if (body[i] == '/' && body[i + 1] == '/' &&
|
||||
(i == 0 || char.IsWhiteSpace(body[i - 1])))
|
||||
if (body[i] == '"')
|
||||
quoted = !quoted;
|
||||
else if (!quoted && i + 1 < body.Length && body[i] == '/' && body[i + 1] is '/' or '*')
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Whether a block comment is still open at the end of the line.
|
||||
private static bool EndsInBlock(string raw, bool inBlock)
|
||||
{
|
||||
bool quoted = false;
|
||||
for (int i = 0; i < raw.Length; i++)
|
||||
{
|
||||
if (inBlock)
|
||||
{
|
||||
if (raw[i] == '*' && i + 1 < raw.Length && raw[i + 1] == '/')
|
||||
{
|
||||
inBlock = false;
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (raw[i] == '"')
|
||||
quoted = !quoted;
|
||||
else if (!quoted && raw[i] == '/' && i + 1 < raw.Length)
|
||||
{
|
||||
if (raw[i + 1] == '/')
|
||||
return false;
|
||||
if (raw[i + 1] == '*')
|
||||
{
|
||||
inBlock = true;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return inBlock;
|
||||
}
|
||||
|
||||
private static int IndexOfWhitespace(string s)
|
||||
{
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
|
||||
@@ -19,11 +19,27 @@ public class SettingRow : ContentControl
|
||||
AvaloniaProperty.Register<SettingRow, string?>(nameof(ValueText));
|
||||
|
||||
/// <summary>
|
||||
/// Why the simulator to be started would pass this setting over; the row dims
|
||||
/// and says so. The input stays usable - the file may serve another build.
|
||||
/// A setting for those who know what it does: the standard mode leaves it out, as
|
||||
/// one a player can break the game with or has no need of.
|
||||
/// </summary>
|
||||
public static readonly StyledProperty<string?> IdleNoteProperty =
|
||||
AvaloniaProperty.Register<SettingRow, string?>(nameof(IdleNote));
|
||||
public static readonly StyledProperty<bool> AdvancedProperty =
|
||||
AvaloniaProperty.Register<SettingRow, bool>(nameof(Advanced));
|
||||
|
||||
public bool Advanced
|
||||
{
|
||||
get => GetValue(AdvancedProperty);
|
||||
set => SetValue(AdvancedProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>The value eu07.ini gives the setting that the starter cannot read, said under it; null when there is none.</summary>
|
||||
public static readonly StyledProperty<string?> UnknownValueProperty =
|
||||
AvaloniaProperty.Register<SettingRow, string?>(nameof(UnknownValue));
|
||||
|
||||
public string? UnknownValue
|
||||
{
|
||||
get => GetValue(UnknownValueProperty);
|
||||
set => SetValue(UnknownValueProperty, value);
|
||||
}
|
||||
|
||||
public string? Label
|
||||
{
|
||||
@@ -49,12 +65,6 @@ public class SettingRow : ContentControl
|
||||
set => SetValue(ValueTextProperty, value);
|
||||
}
|
||||
|
||||
public string? IdleNote
|
||||
{
|
||||
get => GetValue(IdleNoteProperty);
|
||||
set => SetValue(IdleNoteProperty, value);
|
||||
}
|
||||
|
||||
public SettingRow()
|
||||
{
|
||||
UpdatePseudoClasses();
|
||||
@@ -68,22 +78,19 @@ public class SettingRow : ContentControl
|
||||
change.Property == DescriptionProperty ||
|
||||
change.Property == ConfigKeyProperty ||
|
||||
change.Property == ValueTextProperty ||
|
||||
change.Property == IdleNoteProperty ||
|
||||
change.Property == UnknownValueProperty ||
|
||||
change.Property == ContentProperty)
|
||||
UpdatePseudoClasses();
|
||||
|
||||
if (change.Property == IdleNoteProperty)
|
||||
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
|
||||
|
||||
if (change.Property == LabelProperty || change.Property == ContentProperty)
|
||||
ScreenReaderNames.NameInputs(Content, Label);
|
||||
|
||||
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
|
||||
ScreenReaderNames.TellValue(Content, ValueText);
|
||||
|
||||
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
|
||||
if (change.Property == DescriptionProperty || change.Property == UnknownValueProperty ||
|
||||
change.Property == ContentProperty)
|
||||
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
|
||||
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
|
||||
}
|
||||
|
||||
// Again once in the window: a panel given as content may be filled after it was set.
|
||||
@@ -92,7 +99,7 @@ public class SettingRow : ContentControl
|
||||
base.OnLoaded(e);
|
||||
ScreenReaderNames.NameInputs(Content, Label);
|
||||
ScreenReaderNames.TellValue(Content, ValueText);
|
||||
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
|
||||
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
|
||||
}
|
||||
|
||||
private void UpdatePseudoClasses()
|
||||
@@ -102,6 +109,6 @@ public class SettingRow : ContentControl
|
||||
PseudoClasses.Set(":no-key", string.IsNullOrEmpty(ConfigKey));
|
||||
PseudoClasses.Set(":no-value", string.IsNullOrEmpty(ValueText));
|
||||
PseudoClasses.Set(":no-content", Content is null);
|
||||
PseudoClasses.Set(":idle", !string.IsNullOrEmpty(IdleNote));
|
||||
PseudoClasses.Set(":unknown", !string.IsNullOrEmpty(UnknownValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,16 @@ namespace StarterNG.Controls;
|
||||
|
||||
public class SettingsSection : HeaderedContentControl
|
||||
{
|
||||
/// <summary>Every row of the section is for the advanced mode only.</summary>
|
||||
public static readonly StyledProperty<bool> AdvancedProperty =
|
||||
AvaloniaProperty.Register<SettingsSection, bool>(nameof(Advanced));
|
||||
|
||||
public bool Advanced
|
||||
{
|
||||
get => GetValue(AdvancedProperty);
|
||||
set => SetValue(AdvancedProperty, value);
|
||||
}
|
||||
|
||||
public static readonly StyledProperty<object?> ToggleProperty =
|
||||
AvaloniaProperty.Register<SettingsSection, object?>(nameof(Toggle));
|
||||
|
||||
|
||||
42
StarterNG/Domain/ConsistRuns.cs
Normal file
42
StarterNG/Domain/ConsistRuns.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using StarterNG.Classes;
|
||||
|
||||
namespace StarterNG.Domain;
|
||||
|
||||
/// <summary>A stretch of a consist made of vehicles alike, shown as one picture with a count.</summary>
|
||||
public sealed record ConsistRun(Dynamic First, int Count);
|
||||
|
||||
public static class ConsistRuns
|
||||
{
|
||||
/// <summary>
|
||||
/// The consist's vehicles in order, those next to each other that look alike taken together.
|
||||
/// </summary>
|
||||
/// <param name="keyOf">
|
||||
/// What makes two vehicles alike, given the vehicle and its place in the consist.
|
||||
/// No key keeps the vehicle on its own.
|
||||
/// </param>
|
||||
public static List<ConsistRun> Of(IReadOnlyList<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf)
|
||||
{
|
||||
var runs = new List<ConsistRun>();
|
||||
string? prevKey = null;
|
||||
|
||||
for (int i = 0; i < vehicles.Count; i++)
|
||||
{
|
||||
string? key = keyOf(vehicles[i], i);
|
||||
if (key is not null && prevKey is not null && runs.Count > 0 &&
|
||||
string.Equals(key, prevKey, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var last = runs[^1];
|
||||
runs[^1] = last with { Count = last.Count + 1 };
|
||||
}
|
||||
else
|
||||
{
|
||||
runs.Add(new ConsistRun(vehicles[i], 1));
|
||||
}
|
||||
prevKey = key;
|
||||
}
|
||||
|
||||
return runs;
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,13 @@ public enum SceneryFaultKind
|
||||
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
|
||||
IncludeNotClosed,
|
||||
|
||||
/// <summary>
|
||||
/// A vehicle whose <c>.fiz</c> is not in its folder under dynamic: the simulator
|
||||
/// leaves it out, and its trainset runs short. <see cref="SceneryFault.Token"/>
|
||||
/// names the file.
|
||||
/// </summary>
|
||||
VehicleMissing,
|
||||
|
||||
/// <summary>A trainset the starter could not read, for a reason none of the above names.</summary>
|
||||
TrainsetUnreadable,
|
||||
|
||||
|
||||
@@ -15,9 +15,10 @@ namespace StarterNG.Domain.Sceneries;
|
||||
/// include, so they are not loaded twice.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only the plain <c>include path end</c> form: an include with parameters needs
|
||||
/// them put in, and one whose <c>end</c> is not on its line is read by the
|
||||
/// simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
|
||||
/// Only the plain <c>include path end</c> form, or <c>include path</c> as the last
|
||||
/// thing in the file, where the simulator runs out of words before it would
|
||||
/// look for an <c>end</c>: an include with parameters needs them put in, and one
|
||||
/// whose <c>end</c> is not on its line is read by the simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
|
||||
/// whether it is loaded is the player's to choose. Each inlined file is wrapped in
|
||||
/// marker comments, which is how a trainset is told to belong to it.
|
||||
/// </remarks>
|
||||
@@ -29,7 +30,8 @@ public static class SceneryIncludes
|
||||
private static readonly Regex FirstInit = new(@"\bFirstInit\b", RegexOptions.IgnoreCase);
|
||||
|
||||
private static readonly Regex Include = new(
|
||||
@"^[ \t]*include[ \t]+(\S+)[ \t]+end\b[^\r\n]*", RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
||||
@"^[ \t]*include[ \t]+(\S+?)(?:[ \t]+end\b[^\r\n]*|[ \t]*(?://[^\r\n]*)?\s*\z)",
|
||||
RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
||||
|
||||
private static readonly Regex HasTrainset = new(@"^[ \t]*trainset\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
|
||||
|
||||
|
||||
@@ -33,13 +33,18 @@ public static class ScenerySyntax
|
||||
/// Whether the simulator opens an include, named as the include names it; null
|
||||
/// leaves includes unchecked.
|
||||
/// </param>
|
||||
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null)
|
||||
/// <param name="loadsVehicle">
|
||||
/// Whether the simulator finds a vehicle's definition, by its folder under dynamic
|
||||
/// and its .mmd's name, as the scenery writes them; null leaves vehicles unchecked.
|
||||
/// </param>
|
||||
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null,
|
||||
Func<string, string, bool>? loadsVehicle = null)
|
||||
{
|
||||
string code = SceneryCode.Mask(text, out int unclosed);
|
||||
var tokens = SceneryCode.Tokens(code);
|
||||
var lines = new SceneryLines(text, file);
|
||||
|
||||
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true);
|
||||
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true, loadsVehicle);
|
||||
simulator.Run();
|
||||
var author = new Reading(tokens, lines, null, asSimulator: false);
|
||||
author.Run();
|
||||
@@ -110,7 +115,8 @@ public static class ScenerySyntax
|
||||
}
|
||||
|
||||
private sealed class Reading(
|
||||
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
|
||||
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator,
|
||||
Func<string, string, bool>? loadsVehicle = null)
|
||||
{
|
||||
public readonly List<(int Start, int End, string Name)> Trainsets = new();
|
||||
public readonly List<(int, int)> Loose = new();
|
||||
@@ -253,6 +259,9 @@ public static class ScenerySyntax
|
||||
return tokens.Count - 1;
|
||||
}
|
||||
|
||||
if (complete)
|
||||
Definition(at, name);
|
||||
|
||||
var (fault, trackless) = CheckFields(at, complete, inTrainset, name);
|
||||
if (fault is null && !closed)
|
||||
fault = SceneryFaultKind.VehicleNotClosed;
|
||||
@@ -267,6 +276,16 @@ public static class ScenerySyntax
|
||||
return end;
|
||||
}
|
||||
|
||||
// Without its .fiz the simulator makes nothing of the vehicle, and reads on to the next.
|
||||
private void Definition(int at, string name)
|
||||
{
|
||||
string folder = tokens[at + 5].Text;
|
||||
string mmd = tokens[at + 7].Text;
|
||||
if (loadsVehicle is null || !Plain(folder) || !Plain(mmd) || loadsVehicle(folder, mmd))
|
||||
return;
|
||||
Fault(SceneryFaultKind.VehicleMissing, tokens[at].Index, name, $"{folder}/{mmd}.fiz");
|
||||
}
|
||||
|
||||
// As the author meant it: there to be listed, whatever is wrong with it.
|
||||
private int ListVehicle(int at, bool complete, bool closed, int meant)
|
||||
{
|
||||
@@ -378,7 +397,8 @@ public static class ScenerySyntax
|
||||
while (end < tokens.Count && tokens[end].Text != "end")
|
||||
end++;
|
||||
int last = Math.Min(end, tokens.Count - 1);
|
||||
if (Lost(at + 1, last) is not null)
|
||||
// No "end" at all is a mistake too, even where the file runs out before it costs anything.
|
||||
if (end >= tokens.Count || Lost(at + 1, last) is not null)
|
||||
Fault(SceneryFaultKind.IncludeNotClosed, token.Index, token: name, swallowed: (at + 1, last));
|
||||
return last;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
|
||||
namespace StarterNG.Domain.Settings;
|
||||
@@ -40,176 +39,42 @@ public sealed record GraphicsExtras(
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What only Ultra sets, switches and limits with no scale to climb. Not every best is the
|
||||
/// top of a scale: shadows are longest with the limit at its bottom, the regulator and the
|
||||
/// release of textures would only take away, off.
|
||||
/// Left to the player, picture unchanged: separate windows for the screens
|
||||
/// (python.displaywindows, python.vsync), texture streaming, the frame pacing.
|
||||
/// What only Ultra sets, with no scale to climb: the longest shadows, at the bottom of their
|
||||
/// limit, and the screens drawn. What only the advanced mode shows no level sets.
|
||||
/// </summary>
|
||||
/// <param name="ShadowAngleLimit">gfx.shadow.angle.min: how low the sun counts for shadows, so how long they
|
||||
/// get: up to 5× the height of what casts them at 0.2, no longer than it at 1 (opengl33renderer.cpp).</param>
|
||||
/// <param name="TargetFps">targetfps: above 0 the simulator moves the distance factor by itself.</param>
|
||||
/// <param name="ScreenWindowFps">python.fpslimit: read only by the screens' separate windows
|
||||
/// (pythonscreenviewer.cpp), it does nothing without them.</param>
|
||||
/// <param name="TextureRelease">gfx.textures.releasedistance: above 0 textures of far vehicles leave the card.</param>
|
||||
/// <param name="CompressTextures">compresstex: on saves card memory at a cost to the picture.</param>
|
||||
/// <param name="SkipDecor">starter.ignoreirrelevant: on leaves decorative consists out of the scenario.</param>
|
||||
public sealed record GraphicsTop(
|
||||
double ShadowAngleLimit,
|
||||
double TargetFps,
|
||||
double ScreenWindowFps,
|
||||
double TextureRelease,
|
||||
bool Screens,
|
||||
bool ScreenMipmaps,
|
||||
bool CompressTextures,
|
||||
bool SkipDecor,
|
||||
bool Sky,
|
||||
bool Cab,
|
||||
bool AirCouplers,
|
||||
bool SmoothTraction)
|
||||
/// <param name="Screens">python.enabled.</param>
|
||||
public sealed record GraphicsTop(double ShadowAngleLimit, bool Screens)
|
||||
{
|
||||
public const string TargetFpsKey = "targetfps";
|
||||
public const string ScreenWindowFpsKey = "python.fpslimit";
|
||||
public const string TextureReleaseKey = "gfx.textures.releasedistance";
|
||||
public const string SkyKey = "skyenabled";
|
||||
public const string CabKey = "rendercab";
|
||||
public const string AirCouplersKey = "newaircouplers";
|
||||
public const string SmoothTractionKey = "smoothtraction";
|
||||
|
||||
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> RowKeys = new[]
|
||||
{
|
||||
TargetFpsKey, ScreenWindowFpsKey, TextureReleaseKey, SkyKey, CabKey, AirCouplersKey, SmoothTractionKey
|
||||
};
|
||||
|
||||
/// <summary>The eu07.ini keys these values live in.</summary>
|
||||
public static readonly IReadOnlyList<string> Keys = RowKeys.Concat(new[]
|
||||
{
|
||||
"gfx.shadow.angle.min", "python.enabled", "python.mipmaps", "compresstex", "starter.ignoreirrelevant"
|
||||
}).ToList();
|
||||
public static readonly IReadOnlyList<string> Keys = new[] { "gfx.shadow.angle.min", "python.enabled" };
|
||||
|
||||
/// <summary>What they are with nothing set, as <see cref="GraphicsExtras.None"/>.</summary>
|
||||
public static readonly GraphicsTop None =
|
||||
new(0.2, 0, 100, 0, true, true, true, false, true, true, true, true);
|
||||
public static readonly GraphicsTop None = new(0.2, true);
|
||||
|
||||
public static GraphicsTop Of(SimulatorSettings s) =>
|
||||
new(s.ShadowAngleLimit, GraphicsPreset.NumberOf(s, TargetFpsKey),
|
||||
GraphicsPreset.NumberOf(s, ScreenWindowFpsKey), GraphicsPreset.NumberOf(s, TextureReleaseKey),
|
||||
s.PythonScreens, s.ScreenMipmaps, s.CompressTextures, s.IgnoreIrrelevantTrains,
|
||||
GraphicsPreset.ToggleOf(s, SkyKey), GraphicsPreset.ToggleOf(s, CabKey),
|
||||
GraphicsPreset.ToggleOf(s, AirCouplersKey), GraphicsPreset.ToggleOf(s, SmoothTractionKey));
|
||||
public static GraphicsTop Of(SimulatorSettings s) => new(s.ShadowAngleLimit, s.PythonScreens);
|
||||
|
||||
public void ApplyTo(SimulatorSettings s)
|
||||
{
|
||||
void Number(string key, double value) => s.Extra[key] = value.ToString(CultureInfo.InvariantCulture);
|
||||
void Toggle(string key, bool value) => s.Extra[key] = SimulatorKey.FormatToggle(value);
|
||||
|
||||
s.ShadowAngleLimit = ShadowAngleLimit;
|
||||
Number(TargetFpsKey, TargetFps);
|
||||
Number(ScreenWindowFpsKey, ScreenWindowFps);
|
||||
Number(TextureReleaseKey, TextureRelease);
|
||||
s.PythonScreens = Screens;
|
||||
s.ScreenMipmaps = ScreenMipmaps;
|
||||
s.CompressTextures = CompressTextures;
|
||||
s.IgnoreIrrelevantTrains = SkipDecor;
|
||||
Toggle(SkyKey, Sky);
|
||||
Toggle(CabKey, Cab);
|
||||
Toggle(AirCouplersKey, AirCouplers);
|
||||
Toggle(SmoothTractionKey, SmoothTraction);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What only the simulators with the OpenGL 4.6 and Vulkan 1.4 renderers read, the others pass it
|
||||
/// over. High is what they do with nothing set. Left to the player: frame generation, Reflex, the
|
||||
/// choice of the card, automatic exposure, the fitted cascades and the bounced light of the cab.
|
||||
/// </summary>
|
||||
/// <param name="CabProbeInterval">gfx.cabprobe.interval, in frames: the lower the dearer.</param>
|
||||
/// <param name="RayTracing">gfx.raytracing: the Vulkan renderer's alone, off on OpenGL.</param>
|
||||
public sealed record GraphicsNewRenderer(
|
||||
int LampShadows,
|
||||
int ContactShadows,
|
||||
int Occlusion,
|
||||
int OcclusionSlices,
|
||||
int OcclusionSteps,
|
||||
bool OcclusionLighting,
|
||||
int CabProbe,
|
||||
int CabProbeInterval,
|
||||
bool CabProbeReflections,
|
||||
int ScreenReflections,
|
||||
bool RayTracing,
|
||||
bool VolumetricFog,
|
||||
int FogQuality,
|
||||
int Clouds,
|
||||
bool CloudShadows,
|
||||
bool Grass,
|
||||
int GrassDistance,
|
||||
double GrassDensity,
|
||||
int Precipitation,
|
||||
bool Bloom)
|
||||
{
|
||||
/// <summary>The eu07.ini keys these values live in; the fade of the grass follows its distance.</summary>
|
||||
public static readonly IReadOnlyList<string> Keys = new[]
|
||||
{
|
||||
"gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality", "gfx.postfx.ao.lighting",
|
||||
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections", "gfx.ssr", "gfx.raytracing",
|
||||
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows",
|
||||
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
|
||||
"gfx.precipitation.particles", "gfx.postfx.bloom"
|
||||
};
|
||||
|
||||
public static GraphicsNewRenderer Of(SimulatorSettings s) =>
|
||||
new(s.LightShadows, s.ContactShadows, s.AmbientOcclusion, s.AoSlices, s.AoSteps, s.AoLighting,
|
||||
s.CabProbe, s.CabProbeInterval, s.CabProbeReflections, s.Ssr, s.RayTracing,
|
||||
s.VolumetricFog, s.FogQuality, s.Clouds, s.CloudShadows,
|
||||
s.Grass, s.GrassDistance, s.GrassDensity, s.PrecipitationParticles, s.Bloom);
|
||||
|
||||
/// <summary>This level as it lands on <paramref name="s"/>: ray tracing on Vulkan only.</summary>
|
||||
public GraphicsNewRenderer For(SimulatorSettings s) =>
|
||||
GraphicsRules.RayTracingAllowed(s) ? this : this with { RayTracing = false };
|
||||
|
||||
public void ApplyTo(SimulatorSettings s)
|
||||
{
|
||||
s.LightShadows = LampShadows;
|
||||
s.ContactShadows = ContactShadows;
|
||||
s.AmbientOcclusion = Occlusion;
|
||||
s.AoSlices = OcclusionSlices;
|
||||
s.AoSteps = OcclusionSteps;
|
||||
s.AoLighting = OcclusionLighting;
|
||||
s.CabProbe = CabProbe;
|
||||
s.CabProbeInterval = CabProbeInterval;
|
||||
s.CabProbeReflections = CabProbeReflections;
|
||||
s.Ssr = ScreenReflections;
|
||||
s.RayTracing = RayTracing && GraphicsRules.RayTracingAllowed(s);
|
||||
s.VolumetricFog = VolumetricFog;
|
||||
s.FogQuality = FogQuality;
|
||||
s.Clouds = Clouds;
|
||||
s.CloudShadows = CloudShadows;
|
||||
s.Grass = Grass;
|
||||
s.GrassDistance = GrassDistance;
|
||||
s.GrassDensity = GrassDensity;
|
||||
s.PrecipitationParticles = Precipitation;
|
||||
s.Bloom = Bloom;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A level of detail set in one go: what weighs on the graphics card. Every scale climbs in
|
||||
/// even steps from <see cref="Minimal"/> to <see cref="Ultra"/>, as far as it has steps for six
|
||||
/// levels. The screen (resolution, field of view), the frame pacing and the effects that are a
|
||||
/// matter of taste - motion blur, chromatic aberration - stay as they are, except at the
|
||||
/// two ends of the scale, which have <see cref="Extras"/>.
|
||||
/// levels. A level sets only what the standard mode shows, and only to what its sliders offer
|
||||
/// (<see cref="SliderRanges"/>, the old starter's ranges): never past the old starter. The screen
|
||||
/// (resolution, buffer, field of view), the frame pacing and the effects that are a matter of
|
||||
/// taste - motion blur, chromatic aberration - stay as they are, except at the two ends of the
|
||||
/// scale, which have <see cref="Extras"/>.
|
||||
/// </summary>
|
||||
/// <param name="NameKey">Its name's translation key.</param>
|
||||
/// <param name="CabShadowsRange">gfx.shadows.cab.range, in metres, read only by the legacy renderer.</param>
|
||||
/// <param name="AntiAliasing">Multisampling, as older simulators read it too. DLSS, once on, stays: no level does better.</param>
|
||||
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second.</param>
|
||||
/// <param name="DrawRange">basedrawrange, in metres. Below 2000 it changes nothing on screen: the renderer
|
||||
/// keeps at least that for signals and lights (opengl33renderer.cpp).</param>
|
||||
/// <param name="DistanceFactor">heightbase: the only thing that draws less than those 2 km, and draws
|
||||
/// shapes, wires and sections nearer. A regulating targetfps moves it from there.</param>
|
||||
/// <param name="BufferScale">starter.bufferscale, in percent. Above the screen over High: on a 4K one
|
||||
/// Ultra is a picture of 8K, multisampled on top.</param>
|
||||
/// <param name="AntiAliasing">multisampling.</param>
|
||||
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second, one of the old starter's steps.</param>
|
||||
/// <param name="DrawRangeFactor">gfx.drawrange.factor.max: how far the regulator may stretch the draw range.</param>
|
||||
public sealed record GraphicsPreset(
|
||||
string NameKey,
|
||||
@@ -228,122 +93,73 @@ public sealed record GraphicsPreset(
|
||||
double ReflectionsRate,
|
||||
bool ExtraEffects,
|
||||
int SplineFidelity,
|
||||
double DrawRange,
|
||||
double DistanceFactor,
|
||||
int BufferScale,
|
||||
double SleeperDistance,
|
||||
double DrawRangeFactor,
|
||||
double ReflectedInstances,
|
||||
double ReflectedVehicles,
|
||||
int CabShadowsRange,
|
||||
GraphicsNewRenderer NewRenderer,
|
||||
GraphicsExtras? Extras = null,
|
||||
GraphicsTop? Top = null)
|
||||
{
|
||||
public const string DrawRangeKey = "basedrawrange";
|
||||
public const string DistanceFactorKey = "heightbase";
|
||||
public const string SleeperKey = "sleeperdistance";
|
||||
public const string ReflectedInstancesKey = "gfx.reflections.range_instances";
|
||||
public const string ReflectedVehiclesKey = "gfx.reflections.range_vehicles";
|
||||
|
||||
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> RowKeys = new[]
|
||||
{
|
||||
DrawRangeKey, DistanceFactorKey, SleeperKey, ReflectedInstancesKey, ReflectedVehiclesKey
|
||||
};
|
||||
|
||||
/// <summary>The eu07.ini keys a level sets.</summary>
|
||||
public static readonly IReadOnlyList<string> Keys = new[]
|
||||
{
|
||||
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "gfx.antialiasing", "dynamiclights",
|
||||
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "dynamiclights",
|
||||
"gfx.smoke.fidelity", "shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff",
|
||||
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.extraeffects",
|
||||
"splinefidelity", DrawRangeKey, DistanceFactorKey, "starter.bufferscale", "gfx.buffer.percent", SleeperKey,
|
||||
"gfx.drawrange.factor.max", ReflectedInstancesKey, ReflectedVehiclesKey, "gfx.shadows.cab.range"
|
||||
}.Concat(GraphicsNewRenderer.Keys).ToList();
|
||||
"splinefidelity", "gfx.drawrange.factor.max", "gfx.shadows.cab.range"
|
||||
};
|
||||
|
||||
/// <summary>The last resort: no shadows, no reflections, no effects, no smoke, a softer picture.</summary>
|
||||
/// <summary>The last resort: no shadows, no reflections, no effects, no smoke.</summary>
|
||||
public static readonly GraphicsPreset Minimal = new(
|
||||
"PresetMinimal", TextureSize: 512, CabTextureSize: 512, Anisotropy: 1, AntiAliasing: AntiAliasingMode.Off,
|
||||
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 512, ShadowRange: 75, ShadowRank: 1,
|
||||
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1 / 300.0, ExtraEffects: false,
|
||||
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.6, BufferScale: 70,
|
||||
SleeperDistance: 100, DrawRangeFactor: 1, ReflectedInstances: 250, ReflectedVehicles: 50, CabShadowsRange: 0,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 0, ContactShadows: 0, Occlusion: 0, OcclusionSlices: 2, OcclusionSteps: 3,
|
||||
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 0,
|
||||
RayTracing: false, VolumetricFog: false, FogQuality: 1, Clouds: 0, CloudShadows: false, Grass: false,
|
||||
GrassDistance: 30, GrassDensity: 0.25, Precipitation: 16384, Bloom: false),
|
||||
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 1024, ShadowRange: 75, ShadowRank: 1,
|
||||
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: false,
|
||||
SplineFidelity: 1, DrawRangeFactor: 1, CabShadowsRange: 0,
|
||||
Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800));
|
||||
|
||||
public static readonly GraphicsPreset Low = new(
|
||||
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 2, AntiAliasing: AntiAliasingMode.Off,
|
||||
DynamicLights: 3, SmokeFidelity: 1, Shadows: true, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 2,
|
||||
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1 / 60.0, ExtraEffects: true,
|
||||
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.7, BufferScale: 80,
|
||||
SleeperDistance: 150, DrawRangeFactor: 1.5, ReflectedInstances: 400, ReflectedVehicles: 100, CabShadowsRange: 0,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 2, OcclusionSteps: 3,
|
||||
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 1,
|
||||
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: false, Grass: true,
|
||||
GrassDistance: 40, GrassDensity: 0.5, Precipitation: 32768, Bloom: true));
|
||||
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: true,
|
||||
SplineFidelity: 2, DrawRangeFactor: 1, CabShadowsRange: 0);
|
||||
|
||||
public static readonly GraphicsPreset Medium = new(
|
||||
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 4, AntiAliasing: AntiAliasingMode.Msaa2,
|
||||
DynamicLights: 5, SmokeFidelity: 2, Shadows: true, ShadowMap: 1024, ShadowRange: 175, ShadowRank: 2,
|
||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1 / 30.0, ExtraEffects: true,
|
||||
SplineFidelity: 2, DrawRange: 2250, DistanceFactor: 0.85, BufferScale: 90,
|
||||
SleeperDistance: 200, DrawRangeFactor: 2, ReflectedInstances: 550, ReflectedVehicles: 150, CabShadowsRange: 20,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 3, OcclusionSteps: 4,
|
||||
OcclusionLighting: false, CabProbe: 1, CabProbeInterval: 8, CabProbeReflections: true, ScreenReflections: 1,
|
||||
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: true, Grass: true,
|
||||
GrassDistance: 50, GrassDensity: 0.75, Precipitation: 32768, Bloom: true));
|
||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1, ExtraEffects: true,
|
||||
SplineFidelity: 2, DrawRangeFactor: 2, CabShadowsRange: 20);
|
||||
|
||||
/// <summary>
|
||||
/// Where a player with no settings of their own starts. The simulator's own values (Globals.h),
|
||||
/// but for smoke, track curves, reflections and cab shadows: theirs are the bottom of a scale
|
||||
/// with levels to go under this one.
|
||||
/// with levels to go under this one, or below what the old starter offered.
|
||||
/// </summary>
|
||||
public static readonly GraphicsPreset High = new(
|
||||
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa4,
|
||||
DynamicLights: 7, SmokeFidelity: 2, Shadows: true, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
|
||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 0.1, ExtraEffects: true,
|
||||
SplineFidelity: 2, DrawRange: 2500, DistanceFactor: 1, BufferScale: 100,
|
||||
SleeperDistance: 250, DrawRangeFactor: 3, ReflectedInstances: 750, ReflectedVehicles: 250, CabShadowsRange: 40,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 2, ContactShadows: 0, Occlusion: 2, OcclusionSlices: 3, OcclusionSteps: 4,
|
||||
OcclusionLighting: true, CabProbe: 2, CabProbeInterval: 4, CabProbeReflections: true, ScreenReflections: 2,
|
||||
RayTracing: false, VolumetricFog: true, FogQuality: 2, Clouds: 2, CloudShadows: true, Grass: true,
|
||||
GrassDistance: 60, GrassDensity: 1, Precipitation: 65536, Bloom: true));
|
||||
|
||||
/// <summary>For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.</summary>
|
||||
public static readonly GraphicsPreset VeryHigh = new(
|
||||
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
|
||||
DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3,
|
||||
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 2, ExtraEffects: true,
|
||||
SplineFidelity: 3, DrawRange: 5000, DistanceFactor: 2, BufferScale: 150,
|
||||
SleeperDistance: 2000, DrawRangeFactor: 3, ReflectedInstances: 1500, ReflectedVehicles: 1000, CabShadowsRange: 70,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 2, Occlusion: 2, OcclusionSlices: 4, OcclusionSteps: 6,
|
||||
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 3, CabProbeReflections: true, ScreenReflections: 3,
|
||||
RayTracing: false, VolumetricFog: true, FogQuality: 3, Clouds: 3, CloudShadows: true, Grass: true,
|
||||
GrassDistance: 120, GrassDensity: 1.5, Precipitation: 131072, Bloom: true));
|
||||
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 3, ExtraEffects: true,
|
||||
SplineFidelity: 2, DrawRangeFactor: 3, CabShadowsRange: 30);
|
||||
|
||||
/// <summary>
|
||||
/// Every value at the top of what the screen offers. Not the best picture throughout: a map
|
||||
/// of 8192 stretches the cascades fourfold, so shadows reach 2400 m but are coarser up close
|
||||
/// than at <see cref="VeryHigh"/>.
|
||||
/// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.
|
||||
/// Filtering stays as High's, so the textures tell this level from Ultra.
|
||||
/// </summary>
|
||||
public static readonly GraphicsPreset VeryHigh = new(
|
||||
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa8,
|
||||
DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3,
|
||||
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 10, ExtraEffects: true,
|
||||
SplineFidelity: 3, DrawRangeFactor: 3, CabShadowsRange: 50);
|
||||
|
||||
/// <summary>
|
||||
/// The top of every slider, which is the most the old starter gave. Not the best picture
|
||||
/// throughout: a map of 8192 stretches the cascades fourfold, so shadows reach 1600 m but are
|
||||
/// coarser up close than at <see cref="VeryHigh"/>.
|
||||
/// </summary>
|
||||
public static readonly GraphicsPreset Ultra = new(
|
||||
"PresetUltra", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
|
||||
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 600, ShadowRank: 3,
|
||||
"PresetUltra", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
|
||||
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 400, ShadowRank: 3,
|
||||
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 60, ExtraEffects: true,
|
||||
SplineFidelity: 4, DrawRange: 10000, DistanceFactor: 3, BufferScale: 200,
|
||||
SleeperDistance: 5000, DrawRangeFactor: 3, ReflectedInstances: 3000, ReflectedVehicles: 2000, CabShadowsRange: 100,
|
||||
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 3, Occlusion: 2, OcclusionSlices: 6, OcclusionSteps: 8,
|
||||
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 2, CabProbeReflections: true, ScreenReflections: 3,
|
||||
RayTracing: true, VolumetricFog: true, FogQuality: 4, Clouds: 4, CloudShadows: true, Grass: true,
|
||||
GrassDistance: 300, GrassDensity: 2, Precipitation: 262144, Bloom: true),
|
||||
SplineFidelity: 4, DrawRangeFactor: 3, CabShadowsRange: 100,
|
||||
Extras: new GraphicsExtras(MotionBlur: true, ChromaticAberration: true, Smoke: true, PythonUpdateMs: 200),
|
||||
Top: new GraphicsTop(ShadowAngleLimit: 0.2, TargetFps: 0, ScreenWindowFps: 200, TextureRelease: 0,
|
||||
Screens: true, ScreenMipmaps: true, CompressTextures: false, SkipDecor: false,
|
||||
Sky: true, Cab: true, AirCouplers: true, SmoothTraction: true));
|
||||
Top: new GraphicsTop(ShadowAngleLimit: 0.2, Screens: true));
|
||||
|
||||
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra };
|
||||
|
||||
@@ -352,8 +168,7 @@ public sealed record GraphicsPreset(
|
||||
s.MaxTextureSize = TextureSize;
|
||||
s.MaxCabTextureSize = CabTextureSize;
|
||||
s.TextureFiltering = Anisotropy;
|
||||
if (!GraphicsRules.IsDlss(s.AntiAliasing))
|
||||
s.AntiAliasing = AntiAliasing;
|
||||
s.AntiAliasing = AntiAliasing;
|
||||
s.CabShadowsRange = CabShadowsRange;
|
||||
s.DynamicLights = DynamicLights;
|
||||
s.SmokeFidelity = SmokeFidelity;
|
||||
@@ -366,14 +181,7 @@ public sealed record GraphicsPreset(
|
||||
s.ReflectionsFramerate = ReflectionsRate;
|
||||
s.ExtraEffects = ExtraEffects;
|
||||
s.SplineFidelity = SplineFidelity;
|
||||
s.Extra[DrawRangeKey] = DrawRange.ToString(CultureInfo.InvariantCulture);
|
||||
s.Extra[DistanceFactorKey] = DistanceFactor.ToString(CultureInfo.InvariantCulture);
|
||||
s.BufferScalePercent = BufferScale;
|
||||
s.Extra[SleeperKey] = SleeperDistance.ToString(CultureInfo.InvariantCulture);
|
||||
s.DrawRangeFactor = DrawRangeFactor;
|
||||
s.Extra[ReflectedInstancesKey] = ReflectedInstances.ToString(CultureInfo.InvariantCulture);
|
||||
s.Extra[ReflectedVehiclesKey] = ReflectedVehicles.ToString(CultureInfo.InvariantCulture);
|
||||
NewRenderer.ApplyTo(s);
|
||||
Extras?.ApplyTo(s);
|
||||
Top?.ApplyTo(s);
|
||||
}
|
||||
@@ -381,20 +189,14 @@ public sealed record GraphicsPreset(
|
||||
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
|
||||
public bool Matches(SimulatorSettings s) =>
|
||||
s.MaxTextureSize == TextureSize && s.MaxCabTextureSize == CabTextureSize &&
|
||||
Near(s.TextureFiltering, Anisotropy) && (GraphicsRules.IsDlss(s.AntiAliasing) || s.AntiAliasing == AntiAliasing) &&
|
||||
Near(s.TextureFiltering, Anisotropy) && s.AntiAliasing == AntiAliasing &&
|
||||
s.DynamicLights == DynamicLights && s.SmokeFidelity == SmokeFidelity &&
|
||||
s.RenderShadows == Shadows && s.ShadowMapResolution == ShadowMap &&
|
||||
s.ShadowProjectionRange == ShadowRange && s.ShadowRankCutoff == ShadowRank &&
|
||||
s.EnvMap == EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
|
||||
Near(s.ReflectionsFramerate, ReflectionsRate) && s.ExtraEffects == ExtraEffects &&
|
||||
s.SplineFidelity == SplineFidelity && Near(NumberOf(s, DrawRangeKey), DrawRange) &&
|
||||
Near(NumberOf(s, DistanceFactorKey), DistanceFactor) &&
|
||||
s.BufferScalePercent == BufferScale &&
|
||||
Near(NumberOf(s, SleeperKey), SleeperDistance) && Near(s.DrawRangeFactor, DrawRangeFactor) &&
|
||||
Near(NumberOf(s, ReflectedInstancesKey), ReflectedInstances) &&
|
||||
Near(NumberOf(s, ReflectedVehiclesKey), ReflectedVehicles) &&
|
||||
s.SplineFidelity == SplineFidelity && Near(s.DrawRangeFactor, DrawRangeFactor) &&
|
||||
s.CabShadowsRange == CabShadowsRange &&
|
||||
GraphicsNewRenderer.Of(s) == NewRenderer.For(s) &&
|
||||
(Extras is null || GraphicsExtras.Of(s) == Extras) &&
|
||||
(Top is null || GraphicsTop.Of(s) == Top);
|
||||
|
||||
@@ -407,31 +209,23 @@ public sealed record GraphicsPreset(
|
||||
return key.ParseNumber(key.RawIn(s));
|
||||
}
|
||||
|
||||
internal static bool ToggleOf(SimulatorSettings s, string name) =>
|
||||
SimulatorKey.ParseToggle(SimulatorKeys.Named(name).RawIn(s));
|
||||
|
||||
// As the file rounds it: 1/300 comes back as 0.003333.
|
||||
// As the file rounds it.
|
||||
private static bool Near(double value, double target) =>
|
||||
Math.Abs(value - target) <= Math.Abs(target) * 2e-4 + 1e-9;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A part of the picture with a level of its own, as its section on the screen has it. The rest
|
||||
/// of a level - the buffer, the anti-aliasing, the post-processing switches, the frame pacing, the sky and the cab - goes only with the whole.
|
||||
/// of a level - the anti-aliasing, the post-processing switches, the dynamic lights and the smoke - goes only with the whole.
|
||||
/// </summary>
|
||||
/// <param name="Keys">The eu07.ini keys it sets.</param>
|
||||
public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
|
||||
{
|
||||
public static readonly GraphicsGroup DrawRange = new(new[]
|
||||
{
|
||||
GraphicsPreset.DrawRangeKey, GraphicsPreset.DistanceFactorKey, "splinefidelity",
|
||||
GraphicsPreset.SleeperKey, "gfx.drawrange.factor.max"
|
||||
});
|
||||
public static readonly GraphicsGroup DrawRange = new(new[] { "splinefidelity", "gfx.drawrange.factor.max" });
|
||||
|
||||
public static readonly GraphicsGroup Textures = new(new[]
|
||||
{
|
||||
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering",
|
||||
"compresstex", GraphicsTop.TextureReleaseKey
|
||||
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering"
|
||||
});
|
||||
|
||||
public static readonly GraphicsGroup Shadows = new(new[]
|
||||
@@ -439,39 +233,20 @@ public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
|
||||
"shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff", "gfx.shadow.angle.min", "gfx.shadows.cab.range"
|
||||
});
|
||||
|
||||
public static readonly GraphicsGroup Lights = new(new[]
|
||||
{
|
||||
"dynamiclights", "gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality",
|
||||
"gfx.postfx.ao.lighting", "gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections"
|
||||
});
|
||||
|
||||
public static readonly GraphicsGroup Reflections = new(new[]
|
||||
{
|
||||
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate",
|
||||
GraphicsPreset.ReflectedInstancesKey, GraphicsPreset.ReflectedVehiclesKey, "gfx.ssr", "gfx.raytracing"
|
||||
});
|
||||
|
||||
public static readonly GraphicsGroup Atmosphere = new(new[]
|
||||
{
|
||||
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows"
|
||||
});
|
||||
|
||||
public static readonly GraphicsGroup Nature = new(new[]
|
||||
{
|
||||
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
|
||||
"gfx.smoke", "gfx.smoke.fidelity", "gfx.precipitation.particles"
|
||||
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate"
|
||||
});
|
||||
|
||||
public static readonly IReadOnlyList<GraphicsGroup> All = new[]
|
||||
{
|
||||
DrawRange, Textures, Shadows, Lights, Reflections, Atmosphere, Nature
|
||||
DrawRange, Textures, Shadows, Reflections
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>What applying a level touched.</summary>
|
||||
/// <param name="RowKeys">The keys of <see cref="SimulatorKeys"/> rows to show its values in, in that order.</param>
|
||||
/// <param name="ChosenKeys">The eu07.ini keys it chose as a whole.</param>
|
||||
public sealed record PresetApplied(IReadOnlyList<string> RowKeys, IReadOnlyList<string> ChosenKeys);
|
||||
public sealed record PresetApplied(IReadOnlyList<string> ChosenKeys);
|
||||
|
||||
/// <summary>
|
||||
/// Remembers what was there before an end of the scale, which comes back with any level
|
||||
@@ -498,15 +273,11 @@ public sealed class GraphicsPresetMemory
|
||||
comingTop?.ApplyTo(settings);
|
||||
preset.ApplyTo(settings);
|
||||
|
||||
var rows = new List<string>(GraphicsPreset.RowKeys);
|
||||
var chosen = new List<string>(GraphicsPreset.Keys);
|
||||
if (preset.Extras is not null || coming is not null)
|
||||
chosen.AddRange(GraphicsExtras.Keys);
|
||||
if (preset.Top is not null || comingTop is not null)
|
||||
{
|
||||
chosen.AddRange(GraphicsTop.Keys);
|
||||
rows.AddRange(GraphicsTop.RowKeys);
|
||||
}
|
||||
return new PresetApplied(rows, chosen);
|
||||
return new PresetApplied(chosen);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +1,32 @@
|
||||
namespace StarterNG.Domain.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// What the simulator does with combinations of graphics settings, mirrored here so
|
||||
/// the starter only offers what takes effect and writes eu07.ini the way the
|
||||
/// simulator will run it (utilities/Globals.cpp, rendering/vulkan14, rendering/opengl46).
|
||||
/// What the simulator does with graphics values, mirrored here so the starter writes
|
||||
/// eu07.ini the way the simulator will run it (utilities/Globals.cpp), and how far the
|
||||
/// starter lets them go: no further than the old starter did (MaSzyna-EU07/Starter).
|
||||
/// </summary>
|
||||
public static class GraphicsRules
|
||||
{
|
||||
public static bool IsDlss(AntiAliasingMode mode) => mode is AntiAliasingMode.Dlss or AntiAliasingMode.Dlaa;
|
||||
/// <summary>maxcabtexturesize: the old starter's list ended at 4096.</summary>
|
||||
public const int MaxCabTextureSize = 4096;
|
||||
|
||||
public static bool IsTemporal(AntiAliasingMode mode) => mode == AntiAliasingMode.Taa || IsDlss(mode);
|
||||
|
||||
public static bool IsVulkan(SimulatorSettings s) => s.Backend == GraphicsBackend.Vulkan;
|
||||
/// <summary>The projection range of shadowtune: the old starter's list ended at 400.</summary>
|
||||
public const int MaxShadowRange = 400;
|
||||
|
||||
/// <summary>
|
||||
/// DLSS is the Vulkan renderer's only (the OpenGL one takes TAA instead), and the
|
||||
/// DLSS SDK has no macOS libraries.
|
||||
/// The frame buffer, in percent of the window. The old starter's choice of buffer
|
||||
/// (gfx.framebuffer.fidelity) is not read by the simulator, so it always had the window's size.
|
||||
/// </summary>
|
||||
public static bool DlssAllowed(SimulatorSettings s, bool dlssPlatform) => dlssPlatform && IsVulkan(s);
|
||||
public const int MaxBufferScale = 100;
|
||||
|
||||
public static bool DlssActive(SimulatorSettings s, bool dlssPlatform) =>
|
||||
DlssAllowed(s, dlssPlatform) && IsDlss(s.AntiAliasing);
|
||||
|
||||
/// <summary>The frame generation goes with gfx.antialiasing dlss or dlaa, nothing else.</summary>
|
||||
public static bool FrameGenerationAllowed(SimulatorSettings s, bool dlssPlatform) => DlssActive(s, dlssPlatform);
|
||||
|
||||
/// <summary>Reflex (VK_NV_low_latency2) is the Vulkan renderer's only.</summary>
|
||||
public static bool ReflexAllowed(SimulatorSettings s) => IsVulkan(s);
|
||||
|
||||
/// <summary>The frame generation turns Reflex on whatever gfx.reflex says.</summary>
|
||||
public static bool ReflexForced(SimulatorSettings s, bool dlssPlatform) =>
|
||||
FrameGenerationAllowed(s, dlssPlatform) && s.FrameGeneration > 1;
|
||||
|
||||
/// <summary>Ray traced reflections: the Vulkan renderer on a GPU with ray queries.</summary>
|
||||
public static bool RayTracingAllowed(SimulatorSettings s) => IsVulkan(s);
|
||||
|
||||
/// <summary>The render scale is ignored by DLAA, which always draws at the size of the window.</summary>
|
||||
public static bool BufferScaleUsed(SimulatorSettings s, bool dlssPlatform) =>
|
||||
!(DlssActive(s, dlssPlatform) && s.AntiAliasing == AntiAliasingMode.Dlaa);
|
||||
|
||||
/// <summary>TAA and DLSS run in the post-processing which gfx.skippipeline leaves out.</summary>
|
||||
public static bool TemporalWithoutPipeline(SimulatorSettings s) => s.SkipPipeline && IsTemporal(s.AntiAliasing);
|
||||
|
||||
/// <summary>With the clustered lights the headlights come from the clusters; dynamiclights only caps the old path.</summary>
|
||||
public static bool DynamicLightsUsed(SimulatorSettings s) => !s.LightsClustered;
|
||||
|
||||
/// <summary>The ambient occlusion goes into the lighting only with GTAO.</summary>
|
||||
public static bool AoLightingUsed(SimulatorSettings s) => s.AmbientOcclusion == 2;
|
||||
|
||||
/// <summary>
|
||||
/// The AO in the lighting needs the depth of the whole scene drawn before its colour. SSR, contact
|
||||
/// shadows and gfx.depthprepass.scene draw it anyway; without them it is an extra pass (CPU time on OpenGL).
|
||||
/// </summary>
|
||||
public static bool AoLightingAddsDepthPrepass(SimulatorSettings s) =>
|
||||
AoLightingUsed(s) && s.AoLighting && s.Ssr == 0 && s.ContactShadows == 0 && !s.DepthPrepassScene;
|
||||
|
||||
public static bool CabProbeUsed(SimulatorSettings s) => s.CabProbe > 0;
|
||||
|
||||
/// <summary>
|
||||
/// The light bounced around the cab comes from the cab lamp as a light, which needs the clustered lights
|
||||
/// and gfx.lights.cab; without them the probe gives the reflections only.
|
||||
/// </summary>
|
||||
public static bool CabProbeLights(SimulatorSettings s) => CabProbeUsed(s) && s.LightsClustered && s.CabLampLight;
|
||||
|
||||
/// <summary>
|
||||
/// Brings the settings to what the simulator would run with: the Vulkan-only
|
||||
/// features off on OpenGL, DLSS falling back to TAA, values within the ranges
|
||||
/// the simulator clamps them to.
|
||||
/// </summary>
|
||||
public static void Normalize(SimulatorSettings s, bool dlssPlatform)
|
||||
/// <summary>Brings the values within the ranges the simulator clamps them to, and the starter's caps.</summary>
|
||||
public static void Normalize(SimulatorSettings s)
|
||||
{
|
||||
if (IsDlss(s.AntiAliasing) && !DlssAllowed(s, dlssPlatform))
|
||||
s.AntiAliasing = AntiAliasingMode.Taa;
|
||||
|
||||
s.FrameGeneration = FrameGenerationAllowed(s, dlssPlatform) ? Clamp(s.FrameGeneration, 1, 4) : 1;
|
||||
s.Reflex = ReflexAllowed(s) ? Clamp(s.Reflex, 0, 2) : 0;
|
||||
if (!RayTracingAllowed(s))
|
||||
s.RayTracing = false;
|
||||
|
||||
if (!IsKnownDlssPreset(s.DlssPreset))
|
||||
s.DlssPreset = "default";
|
||||
|
||||
s.MaxTextureSize = PowerOfTwo(s.MaxTextureSize, 64, 8192);
|
||||
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, 8192);
|
||||
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, MaxCabTextureSize);
|
||||
s.ShadowMapResolution = PowerOfTwo(s.ShadowMapResolution, 512, 8192);
|
||||
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, 200);
|
||||
s.LightShadows = Clamp(s.LightShadows, 0, 3);
|
||||
s.ContactShadows = Clamp(s.ContactShadows, 0, 3);
|
||||
s.AmbientOcclusion = Clamp(s.AmbientOcclusion, 0, 2);
|
||||
s.AoSlices = Clamp(s.AoSlices, 1, 8);
|
||||
s.AoSteps = Clamp(s.AoSteps, 1, 16);
|
||||
s.CabProbe = Clamp(s.CabProbe, 0, 3);
|
||||
s.CabProbeInterval = Clamp(s.CabProbeInterval, 1, 120);
|
||||
s.CabProbeBounce = s.CabProbeBounce < 0 ? 0 : (s.CabProbeBounce > 4 ? 4 : s.CabProbeBounce);
|
||||
s.Ssr = Clamp(s.Ssr, 0, 3);
|
||||
s.RayTracingRange = Clamp(s.RayTracingRange, 10, 5000);
|
||||
s.FogQuality = Clamp(s.FogQuality, 1, 4);
|
||||
s.Clouds = Clamp(s.Clouds, 0, 4);
|
||||
s.GrassDistance = Clamp(s.GrassDistance, 5, 500);
|
||||
s.GrassDensity = s.GrassDensity < 0 ? 0 : (s.GrassDensity > 4 ? 4 : s.GrassDensity);
|
||||
s.PrecipitationParticles = Clamp(s.PrecipitationParticles, 0, 1 << 20);
|
||||
}
|
||||
|
||||
public static readonly string[] DlssPresets = { "default", "j", "k", "l", "m" };
|
||||
|
||||
public static bool IsKnownDlssPreset(string? preset)
|
||||
{
|
||||
foreach (string known in DlssPresets)
|
||||
if (string.Equals(known, preset, System.StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
return false;
|
||||
s.ShadowProjectionRange = s.ShadowProjectionRange > MaxShadowRange ? MaxShadowRange : s.ShadowProjectionRange;
|
||||
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, MaxBufferScale);
|
||||
}
|
||||
|
||||
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
||||
|
||||
14
StarterNG/Domain/Settings/Renderers.cs
Normal file
14
StarterNG/Domain/Settings/Renderers.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace StarterNG.Domain.Settings;
|
||||
|
||||
/// <summary>The renderers a gfxrenderer word picks, as application.cpp tells them apart.</summary>
|
||||
public enum RendererKind { Modern, Legacy }
|
||||
|
||||
public static class Renderers
|
||||
{
|
||||
/// <summary>"legacy", "simple", "simpleshader" and "off" draw with the legacy renderer, any other word with the full one.</summary>
|
||||
public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch
|
||||
{
|
||||
"legacy" or "simple" or "simpleshader" or "off" => RendererKind.Legacy,
|
||||
_ => RendererKind.Modern
|
||||
};
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace StarterNG.Domain.Settings;
|
||||
|
||||
/// <summary>Why the simulator about to be started would pass a key over.</summary>
|
||||
public enum IdleReason
|
||||
{
|
||||
None,
|
||||
WindowsBuildOnly,
|
||||
LegacyRendererOnly,
|
||||
/// <summary>Read by the full OpenGL renderer alone.</summary>
|
||||
ModernRendererOnly,
|
||||
/// <summary>Read by the OpenGL renderers, which the experimental one is not.</summary>
|
||||
OpenGlRenderersOnly,
|
||||
NeedsNetworkServer,
|
||||
/// <summary>The draw range is only stretched by the frame rate regulator, which is off.</summary>
|
||||
NeedsFrameRateTarget,
|
||||
/// <summary>fullscreenwindowed takes the monitor's own mode instead.</summary>
|
||||
MonitorModeInstead,
|
||||
VulkanOnly
|
||||
}
|
||||
|
||||
/// <summary>What about the simulator to be started decides which keys it heeds.</summary>
|
||||
/// <param name="WindowsBuild">The executable is a Windows build, under Wine or not.</param>
|
||||
/// <param name="Renderer">The gfxrenderer word, as <see cref="SimulatorSettings.RenderEngines"/> has it.</param>
|
||||
/// <param name="NetworkServer">eu07.ini starts a network.server.</param>
|
||||
/// <param name="TargetFps">targetfps as eu07.ini sets it, or null where it does not.</param>
|
||||
/// <param name="FpsAverage">fpsaverage, the older regulator's target; 0 for none.</param>
|
||||
/// <param name="FullscreenWindowed">fullscreenwindowed is on.</param>
|
||||
public sealed record SimulatorTarget(bool WindowsBuild, string Renderer, bool NetworkServer,
|
||||
double? TargetFps = null, double FpsAverage = 0,
|
||||
bool FullscreenWindowed = false);
|
||||
|
||||
/// <summary>The renderers a gfxrenderer word picks, as application.cpp tells them apart.</summary>
|
||||
public enum RendererKind { Modern, Legacy, Experimental }
|
||||
|
||||
/// <summary>
|
||||
/// Where an eu07.ini key takes effect, from the simulator's sources: a key it
|
||||
/// reads but leaves alone on the platform, render path or setup at hand.
|
||||
/// </summary>
|
||||
public static class SettingReach
|
||||
{
|
||||
// The keyboard lights, LPT and PoKeys behind feedback live in Console.cpp,
|
||||
// which only the Windows build compiles; the system console and ANGLE are
|
||||
// Windows-only in application.cpp.
|
||||
private static readonly HashSet<string> WindowsBuildOnly = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"feedbackmode", "feedbackport", "showsystemconsole", "gfx.angleplatform"
|
||||
};
|
||||
|
||||
// Read by openglrenderer.cpp alone; the modern path forces VBOs on.
|
||||
private static readonly HashSet<string> LegacyRendererOnly = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"smoothtraction", "gfx.shadows.cab.range", "usevbo"
|
||||
};
|
||||
|
||||
// Read by opengl33renderer.cpp and the shaders it builds (glsl_common.cpp) alone.
|
||||
private static readonly HashSet<string> ModernRendererOnly = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"gfx.postfx.chromaticaberration.enabled", "gfx.postfx.motionblur.enabled",
|
||||
"gfx.postfx.motionblur.shutter", "gfx.extraeffects", "gfx.envmap.enabled", "gfx.skippipeline",
|
||||
"rendercab", "sleeperdistance"
|
||||
};
|
||||
|
||||
// Read by both OpenGL renderers but not by the experimental one, which sets its
|
||||
// own anisotropy, draws no smoke and has no frame rate regulator.
|
||||
private static readonly HashSet<string> OpenGlRenderersOnly = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"anisotropicfiltering", "multisampling", "dynamiclights", "gfx.smoke", "gfx.smoke.fidelity",
|
||||
"gfx.reflections.framerate", "gfx.reflections.range_vehicles", "gfx.shadow.angle.min",
|
||||
"scalespeculars", "gfx.drawrange.factor.max"
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> VulkanRendererOnly = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"gfx.dlss.preset", "gfx.framegeneration", "gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.vulkan.device"
|
||||
};
|
||||
|
||||
// application.cpp: fullscreenwindowed takes its size from the monitor and always
|
||||
// goes full screen. "width, height" is how the settings screen names that row.
|
||||
private static readonly HashSet<string> OverriddenByMonitorMode = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"width, height", "fullscreen"
|
||||
};
|
||||
|
||||
public static IdleReason Why(string key, SimulatorTarget target)
|
||||
{
|
||||
// The starter's own keys mean nothing to any simulator, and need not.
|
||||
if (key.StartsWith("starter.", StringComparison.OrdinalIgnoreCase))
|
||||
return IdleReason.None;
|
||||
if (WindowsBuildOnly.Contains(key) && !target.WindowsBuild)
|
||||
return IdleReason.WindowsBuildOnly;
|
||||
if (OverriddenByMonitorMode.Contains(key) && target.FullscreenWindowed)
|
||||
return IdleReason.MonitorModeInstead;
|
||||
|
||||
var renderer = KindOf(target.Renderer);
|
||||
if (LegacyRendererOnly.Contains(key) && renderer != RendererKind.Legacy)
|
||||
return IdleReason.LegacyRendererOnly;
|
||||
if (ModernRendererOnly.Contains(key) && renderer != RendererKind.Modern)
|
||||
return IdleReason.ModernRendererOnly;
|
||||
if (OpenGlRenderersOnly.Contains(key) && renderer == RendererKind.Experimental)
|
||||
return IdleReason.OpenGlRenderersOnly;
|
||||
if (VulkanRendererOnly.Contains(key) && !IsVulkan(target.Renderer))
|
||||
return IdleReason.VulkanOnly;
|
||||
|
||||
// on_focus_change pauses only a simulator that serves the network.
|
||||
if (string.Equals(key, "inactivepause", StringComparison.OrdinalIgnoreCase) && !target.NetworkServer)
|
||||
return IdleReason.NeedsNetworkServer;
|
||||
if (string.Equals(key, "gfx.drawrange.factor.max", StringComparison.OrdinalIgnoreCase) &&
|
||||
!DrawRangeRegulated(target))
|
||||
return IdleReason.NeedsFrameRateTarget;
|
||||
return IdleReason.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the renderer moves the draw range with the frame rate - the only use
|
||||
/// of gfx.drawrange.factor.max: targetfps does it, as the older fpsaverage does.
|
||||
/// </summary>
|
||||
private static bool DrawRangeRegulated(SimulatorTarget target) =>
|
||||
target.FpsAverage != 0 || (target.TargetFps ?? 0) != 0;
|
||||
|
||||
/// <summary>"full", its other names and the Vulkan renderer are the modern kind, "experimental" its own; every other word the legacy one.</summary>
|
||||
public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch
|
||||
{
|
||||
"full" or "default" or "opengl" or "gl46" or "vulkan" or "vulkan14" => RendererKind.Modern,
|
||||
"experimental" => RendererKind.Experimental,
|
||||
_ => RendererKind.Legacy
|
||||
};
|
||||
|
||||
public static bool IsVulkan(string renderer) => renderer.ToLowerInvariant() is "vulkan" or "vulkan14";
|
||||
}
|
||||
@@ -63,6 +63,12 @@ public sealed record SimulatorKey(
|
||||
|
||||
public static class SimulatorKeys
|
||||
{
|
||||
/// <summary>
|
||||
/// The keys a player sees in the standard mode, which has what the old starter had. It had
|
||||
/// none of these: they are all for the advanced mode.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlySet<string> Standard = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public const string General = "general";
|
||||
public const string Graphics = "graphics";
|
||||
public const string Sound = "sound";
|
||||
@@ -94,13 +100,12 @@ public static class SimulatorKeys
|
||||
Toggle("loadinglog", false, General, "IniSectionInterface"),
|
||||
Toggle("captureonstart", true, General, "IniSectionInterface"),
|
||||
Toggle("mousecontrol", true, General, "IniSectionInterface"),
|
||||
Text("fullscreenmonitor", General, "IniSectionInterface"),
|
||||
Text("screenshotsdir", General, "IniSectionInterface"),
|
||||
|
||||
Number("basedrawrange", 2500, Graphics, "IniSectionRanges", 500, 10000, 250, " m"),
|
||||
Number("heightbase", 1, Graphics, "IniSectionRanges", 0.5, 3, 0.05, "×"),
|
||||
Number("targetfps", 0, Graphics, "IniSectionRanges", 0, 240, 5, " FPS", zeroIsOff: true),
|
||||
Number("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 5000, 50, " m", zeroIsOff: true),
|
||||
Number("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 1000, 50, " m", zeroIsOff: true),
|
||||
Number("gfx.reflections.range_instances", 750, Graphics, "IniSectionRanges", 0, 3000, 50, " m"),
|
||||
Number("gfx.reflections.range_vehicles", 250, Graphics, "IniSectionRanges", 0, 2000, 50, " m"),
|
||||
Toggle("gfx.textures.streaming", false, Graphics, "IniSectionRanges"),
|
||||
|
||||
@@ -8,11 +8,8 @@ public enum ConsistReadyOverride { Scenery = 0, AlwaysCold = 1, AlwaysReady = 2
|
||||
|
||||
public enum ExeProblem { None, NotFound, NotExecutable, WrongPlatform, NotAProgram }
|
||||
|
||||
// gfxrenderer: the OpenGL renderer ("full", read by every build) or the Vulkan 1.4 one.
|
||||
public enum GraphicsBackend { OpenGL = 0, Vulkan = 1 }
|
||||
|
||||
// gfx.antialiasing. Dlss and Dlaa are the Vulkan renderer's only; the simulator falls back to TAA elsewhere.
|
||||
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8, Taa, Dlss, Dlaa }
|
||||
// multisampling: 0 off, then 2, 4 and 8 samples.
|
||||
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8 }
|
||||
|
||||
public sealed class SimulatorSettings
|
||||
{
|
||||
@@ -34,7 +31,8 @@ public sealed class SimulatorSettings
|
||||
public bool InvertMouseHorizontal;
|
||||
public bool InvertMouseVertical;
|
||||
|
||||
public bool IgnoreGamepad;
|
||||
/// <summary>input.gamepad no: the recommended setting, so the starter's default, though the simulator's own is yes.</summary>
|
||||
public bool IgnoreGamepad = true;
|
||||
public int FeedbackMode = 1;
|
||||
public int FeedbackPort = 888;
|
||||
public bool UartEnabled;
|
||||
@@ -55,8 +53,6 @@ public sealed class SimulatorSettings
|
||||
public bool LogMissingVehicleFiles;
|
||||
|
||||
public int RenderEngine;
|
||||
public GraphicsBackend Backend => RenderEngine == VulkanEngine ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL;
|
||||
public string VulkanDevice = "";
|
||||
public int Width = 1280;
|
||||
public int Height = 720;
|
||||
public int BufferScalePercent = 100;
|
||||
@@ -64,9 +60,6 @@ public sealed class SimulatorSettings
|
||||
public int MaxCabTextureSize = 4096;
|
||||
public double TextureFiltering = 8;
|
||||
public AntiAliasingMode AntiAliasing = AntiAliasingMode.Msaa4;
|
||||
public string DlssPreset = "default";
|
||||
public int FrameGeneration = 1;
|
||||
public int Reflex;
|
||||
public int DynamicLights = 7;
|
||||
public double DrawRangeFactor = 3.0;
|
||||
public bool VSync;
|
||||
@@ -77,37 +70,8 @@ public sealed class SimulatorSettings
|
||||
public bool ExtraEffects = true;
|
||||
public bool EnvMap = true;
|
||||
public bool RenderShadows = true;
|
||||
public bool ShadowSdsm;
|
||||
public int LightShadows = 2;
|
||||
public int ContactShadows;
|
||||
public bool LightsClustered = true;
|
||||
public int AmbientOcclusion = 2;
|
||||
public int AoSlices = 3;
|
||||
public int AoSteps = 4;
|
||||
public bool AoLighting = true;
|
||||
public int CabProbe = 2;
|
||||
public int CabProbeInterval = 4;
|
||||
public double CabProbeBounce = 1.0;
|
||||
public bool CabProbeReflections = true;
|
||||
|
||||
// Read from eu07.ini only, for the dependencies shown: the starter offers no switch for them.
|
||||
public bool CabLampLight { get; internal set; } = true;
|
||||
public bool DepthPrepassScene { get; internal set; }
|
||||
public int Ssr = 2;
|
||||
public bool RayTracing;
|
||||
public int RayTracingRange = 500;
|
||||
public bool VolumetricFog = true;
|
||||
public int FogQuality = 2;
|
||||
public int Clouds = 2;
|
||||
public bool CloudShadows = true;
|
||||
public bool Grass = true;
|
||||
public int GrassDistance = 60;
|
||||
public double GrassDensity = 1.0;
|
||||
public int PrecipitationParticles = 65536;
|
||||
public bool Bloom = true;
|
||||
public bool AutoExposure = true;
|
||||
|
||||
// Only the older simulators read these.
|
||||
// Only the legacy renderer, or only Windows builds, read these.
|
||||
public bool UseVbo = true;
|
||||
public bool RenderAngleVulkan;
|
||||
public bool UseGLES;
|
||||
@@ -127,12 +91,28 @@ public sealed class SimulatorSettings
|
||||
public double FpsLimit = 30;
|
||||
public double ShadowAngleLimit = 0.2;
|
||||
public bool FullscreenWindowed;
|
||||
/// <summary>fullscreenmonitor: the monitor a full screen opens on, as "name:x,y"; empty for the primary one.</summary>
|
||||
public string FullscreenMonitor = "";
|
||||
|
||||
public int SplineFidelity = 1;
|
||||
public bool FullPhysics = true;
|
||||
public bool EnableTraction = true;
|
||||
public bool LiveTraction = true;
|
||||
public bool PhysicsLog;
|
||||
/// <summary>
|
||||
/// The black box of the session, and with it the tapes (.dat) of the vehicles the player was in, written when the
|
||||
/// simulator closes: the tapes without the log of every vehicle. With no entry of its own it goes with the physics log.
|
||||
/// </summary>
|
||||
public bool BlackBox;
|
||||
/// <summary>Whether eu07.ini had a line of its own for the black box when read: it is kept saying what is wanted.</summary>
|
||||
public bool BlackBoxInIni;
|
||||
/// <summary>
|
||||
/// The physics logs (.dat) of the trains only, "physicslog.trains": of each driver of rail vehicles, not of the
|
||||
/// passengers nor of the vehicles of the roads. The tapes of every train, far fewer files than the log of every vehicle.
|
||||
/// </summary>
|
||||
public bool PhysicsLogTrains;
|
||||
/// <summary>Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on.</summary>
|
||||
public bool PhysicsLogTrainsInIni;
|
||||
public bool DebugLog = true;
|
||||
public bool MultipleLogs;
|
||||
public bool DisplaySimulation = true;
|
||||
@@ -166,6 +146,18 @@ public sealed class SimulatorSettings
|
||||
public bool LargeThumbnails;
|
||||
public bool AutoExpandSceneryTree;
|
||||
|
||||
/// <summary>
|
||||
/// Every setting on show, the ones a player can break the game with too. Off, the standard
|
||||
/// mode keeps the settings, the consists and the scenario to what a driver needs.
|
||||
/// </summary>
|
||||
public bool AdvancedSettings;
|
||||
|
||||
/// <summary>
|
||||
/// The settings were brought into the standard mode once, on the first start of this
|
||||
/// starter: the advanced ones to their defaults, the sliders into their ranges.
|
||||
/// </summary>
|
||||
public bool MovedToStandard;
|
||||
|
||||
/// <summary>Warn at start when the processor cannot run the official simulator builds.</summary>
|
||||
public bool CpuNotice = true;
|
||||
|
||||
@@ -198,25 +190,26 @@ public sealed class SimulatorSettings
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gfxrenderer words the simulator tells apart (application.cpp): every
|
||||
/// other word - the "simpleshader" and "off" older starters offered among them -
|
||||
/// gets the legacy renderer. A simulator with the OpenGL 4.6 and Vulkan 1.4
|
||||
/// renderers runs everything but "vulkan" as the first, and "vulkan" too when
|
||||
/// it was built without it or the card cannot run it.
|
||||
/// The gfxrenderer words the starter offers. "default" is the full renderer, the one to use
|
||||
/// wherever it runs; the other two draw with the legacy one. The experimental renderer is
|
||||
/// not offered: the simulator a player has is built without it.
|
||||
/// </summary>
|
||||
public static readonly string[] RenderEngines = { "full", "legacy", "simple", "experimental", "vulkan" };
|
||||
public static readonly string[] RenderEngines = { "default", "legacy", "simple" };
|
||||
|
||||
/// <summary>Where "vulkan" stands among <see cref="RenderEngines"/>.</summary>
|
||||
public const int VulkanEngine = 4;
|
||||
/// <summary>
|
||||
/// The words of the file that stay as they are while the choice stands: those application.cpp
|
||||
/// on master knows, but "experimental". Any other word starts the full renderer with a line in
|
||||
/// the log, so a save puts "default" in its place.
|
||||
/// </summary>
|
||||
public static bool KeptRendererWord(string? word) =>
|
||||
word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off";
|
||||
|
||||
/// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary>
|
||||
public static int RenderEngineOf(string word) => word.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"full" or "default" or "opengl" or "gl46" => 0,
|
||||
"legacy" or "simpleshader" or "off" => 1,
|
||||
"simple" => 2,
|
||||
"experimental" => 3,
|
||||
"vulkan" or "vulkan14" => 4,
|
||||
_ => 1
|
||||
_ => 0
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -242,7 +235,12 @@ public sealed class SimulatorSettings
|
||||
/// </summary>
|
||||
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>
|
||||
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
|
||||
{
|
||||
// Columns counted from the start; the security flag is counted from the end, past
|
||||
// the command, which is free text. The header says m/s and MPa, the values are km/h and bar.
|
||||
// the command, which is free text, as far from the end as the header has it: the
|
||||
// simulator adds a new column at the end (the vehicle's speed, 2026-10). The header
|
||||
// says m/s and MPa, the values are km/h and bar.
|
||||
private const int TimeColumn = 0;
|
||||
private const int VelocityColumn = 1;
|
||||
private const int BrakePressColumn = 8;
|
||||
private const int PipePressColumn = 9;
|
||||
private const int MotorCurrentColumn = 10;
|
||||
private const int SecurityFromEnd = 6;
|
||||
private const string SecurityHeading = "Security";
|
||||
private const int SecurityFromEndOf25 = 6; // a log with no header to tell: the columns up to the water's temperature
|
||||
private const int MinimumColumns = 17;
|
||||
|
||||
public HaslerTape(IReadOnlyList<TapeSample> samples)
|
||||
// above the longest step the simulator makes at once (its frame is held to a second) and a line's interval: a
|
||||
// stall of the simulator, a dragged window say, is time driven or stood, not a gap
|
||||
private const double MinimumGapSeconds = 2.0;
|
||||
private const int GapSteps = 20;
|
||||
|
||||
public HaslerTape(IReadOnlyList<TapeSample> samples) : this(samples, GapAbove(samples))
|
||||
{
|
||||
}
|
||||
|
||||
// the gap already found, by the reader: the steps are sorted once, not again here
|
||||
private HaslerTape(IReadOnlyList<TapeSample> samples, double gap)
|
||||
{
|
||||
Samples = samples;
|
||||
foreach (var s in samples)
|
||||
MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh);
|
||||
GapSeconds = gap;
|
||||
for (int i = 1; i < samples.Count; i++)
|
||||
if (samples[i].SpeedKmh > 0.5)
|
||||
RunningTime += samples[i].Time - samples[i - 1].Time;
|
||||
{
|
||||
double step = samples[i].Time - samples[i - 1].Time;
|
||||
if (step > gap)
|
||||
GapTime += step;
|
||||
else if (samples[i].SpeedKmh > 0.5)
|
||||
RunningTime += step;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<TapeSample> Samples { get; }
|
||||
@@ -60,50 +79,137 @@ public sealed class HaslerTape
|
||||
|
||||
public double MaxSpeedKmh { get; }
|
||||
|
||||
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing.</summary>
|
||||
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing, or not recorded.</summary>
|
||||
public double RunningTime { get; }
|
||||
|
||||
public double StandingTime => Duration - RunningTime;
|
||||
/// <summary>Seconds of <see cref="Duration"/> not recorded: the gaps, see <see cref="GapAbove"/>.</summary>
|
||||
public double GapTime { get; }
|
||||
|
||||
/// <summary>A step between two lines longer than this is a gap: <see cref="GapAbove"/> of this tape.</summary>
|
||||
public double GapSeconds { get; }
|
||||
|
||||
public double StandingTime => Duration - RunningTime - GapTime;
|
||||
|
||||
/// <summary>Mean speed while moving.</summary>
|
||||
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
|
||||
|
||||
/// <summary>Mean speed over the whole recording, stops included - the commercial speed.</summary>
|
||||
public double AverageWithStopsKmh => Duration > 0 ? DistanceM / Duration * 3.6 : 0;
|
||||
public double AverageWithStopsKmh => Duration - GapTime > 0 ? DistanceM / (Duration - GapTime) * 3.6 : 0;
|
||||
|
||||
/// <summary>
|
||||
/// A step between two lines longer than this is time not recorded, the player in another vehicle before
|
||||
/// coming back to this one: neither driving nor standing, and no distance. The lines come every 0.05 s of
|
||||
/// simulated time or so; it is twenty of their usual steps, two seconds at least.
|
||||
/// </summary>
|
||||
public static double GapAbove(IReadOnlyList<TapeSample> samples)
|
||||
{
|
||||
if (samples.Count < 2)
|
||||
return MinimumGapSeconds;
|
||||
var steps = new double[samples.Count - 1];
|
||||
for (int i = 1; i < samples.Count; i++)
|
||||
steps[i - 1] = samples[i].Time - samples[i - 1].Time;
|
||||
Array.Sort(steps);
|
||||
return Math.Max(MinimumGapSeconds, GapSteps * steps[steps.Length / 2]);
|
||||
}
|
||||
|
||||
public static HaslerTape Parse(string text)
|
||||
{
|
||||
var samples = new List<TapeSample>();
|
||||
double distance = 0;
|
||||
TapeSample? previous = null;
|
||||
var reader = new Reader();
|
||||
reader.Feed(text);
|
||||
return reader.Tape(final: true);
|
||||
}
|
||||
|
||||
foreach (var raw in text.Split('\n'))
|
||||
/// <summary>
|
||||
/// A tape read as it is written: each piece of the file given once, in order, so a log the simulator keeps
|
||||
/// adding to - fast, at a higher time speed - is not read and split from its start every time it grows. A line
|
||||
/// not ended yet waits for the rest.
|
||||
/// </summary>
|
||||
public sealed class Reader
|
||||
{
|
||||
private readonly List<TapeSample> _samples = new();
|
||||
private readonly System.Text.StringBuilder _unended = new();
|
||||
private int _securityFromEnd = SecurityFromEndOf25;
|
||||
|
||||
public void Feed(string text)
|
||||
{
|
||||
WentBack = false;
|
||||
int start = 0;
|
||||
for (int end = text.IndexOf('\n'); end >= 0; end = text.IndexOf('\n', start))
|
||||
{
|
||||
if (_unended.Length > 0)
|
||||
{
|
||||
_unended.Append(text, start, end - start);
|
||||
Keep(_unended.ToString(), _samples);
|
||||
_unended.Clear();
|
||||
}
|
||||
else
|
||||
Keep(text.Substring(start, end - start), _samples);
|
||||
start = end + 1;
|
||||
}
|
||||
_unended.Append(text, start, text.Length - start);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tape of what was read. Final, the end of the file: a last line with no end is read too, though
|
||||
/// only for this tape; otherwise it may be cut short by a simulator still writing, and waits.
|
||||
/// </summary>
|
||||
public HaslerTape Tape(bool final)
|
||||
{
|
||||
var read = _samples;
|
||||
if (final && _unended.Length > 0)
|
||||
{
|
||||
read = new List<TapeSample>(_samples);
|
||||
Keep(_unended.ToString(), read);
|
||||
}
|
||||
// the distance, trapezoid by trapezoid, none over the gaps
|
||||
var samples = new List<TapeSample>(read.Count);
|
||||
double gap = GapAbove(read), distance = 0;
|
||||
for (int i = 0; i < read.Count; i++)
|
||||
{
|
||||
var sample = read[i];
|
||||
if (i > 0)
|
||||
{
|
||||
var before = read[i - 1];
|
||||
double step = sample.Time - before.Time;
|
||||
if (step <= gap)
|
||||
distance += (before.SpeedKmh + sample.SpeedKmh) / 2 / 3.6 * step;
|
||||
}
|
||||
samples.Add(sample with { DistanceM = distance });
|
||||
}
|
||||
return new HaslerTape(samples, gap);
|
||||
}
|
||||
|
||||
private void Keep(string raw, List<TapeSample> samples)
|
||||
{
|
||||
var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (columns.Length < MinimumColumns
|
||||
|| !Number(columns[TimeColumn], out double time)
|
||||
|| !Number(columns[VelocityColumn], out double velocity))
|
||||
continue; // the header, or a line cut short by a simulator still writing
|
||||
if (columns.Length == 0)
|
||||
return;
|
||||
if (!Number(columns[TimeColumn], out double time))
|
||||
{
|
||||
// the header; a line of figures may have the word too, in the free text of its command
|
||||
int heading = Array.IndexOf(columns, SecurityHeading);
|
||||
if (heading >= 0)
|
||||
_securityFromEnd = columns.Length - heading;
|
||||
return;
|
||||
}
|
||||
if (columns.Length < MinimumColumns || !Number(columns[VelocityColumn], out double velocity))
|
||||
return; // a line cut short by a simulator still writing
|
||||
|
||||
Number(columns[BrakePressColumn], out double brake);
|
||||
Number(columns[PipePressColumn], out double pipe);
|
||||
Number(columns[MotorCurrentColumn], out double current);
|
||||
bool security = columns[^SecurityFromEnd] == "1";
|
||||
bool security = _securityFromEnd <= columns.Length && columns[^_securityFromEnd] == "1";
|
||||
|
||||
double speed = Math.Abs(velocity);
|
||||
if (previous is { } p)
|
||||
if (samples.Count > 0 && time < samples[^1].Time)
|
||||
{
|
||||
if (time < p.Time)
|
||||
continue;
|
||||
distance += (p.SpeedKmh + speed) / 2 / 3.6 * (time - p.Time);
|
||||
WentBack = true;
|
||||
return;
|
||||
}
|
||||
|
||||
var sample = new TapeSample(time, speed, distance, brake, pipe, current, security);
|
||||
samples.Add(sample);
|
||||
previous = sample;
|
||||
samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security));
|
||||
}
|
||||
|
||||
return new HaslerTape(samples);
|
||||
/// <summary>In the last piece fed, a line whose time was before the last one's, left out: maybe the log begun anew.</summary>
|
||||
public bool WentBack { get; private set; }
|
||||
}
|
||||
|
||||
/// <summary>Index of the last sample at or before the given time or distance.</summary>
|
||||
|
||||
@@ -199,23 +199,8 @@ public sealed class TexRandomizer
|
||||
VehicleTexture? current)
|
||||
{
|
||||
var result = new List<VehicleTexture>();
|
||||
foreach (var t in _db.Textures)
|
||||
foreach (var t in ByMini(minis))
|
||||
{
|
||||
if (t.Wreck) continue;
|
||||
if (WithoutArchival && t.ResolvedArchived) continue;
|
||||
if (_db.IsSetFollower(t)) continue;
|
||||
|
||||
string candidateMini = t.ResolvedClass;
|
||||
if (string.IsNullOrEmpty(candidateMini))
|
||||
candidateMini = _db.ResolveMiniName(t) ?? "";
|
||||
if (string.IsNullOrEmpty(candidateMini)) continue;
|
||||
|
||||
bool miniOk = minis.Any(m =>
|
||||
string.Equals(m, candidateMini, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(m, t.TextureMini, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(m, t.MiniRef, StringComparison.OrdinalIgnoreCase));
|
||||
if (!miniOk) continue;
|
||||
|
||||
if (!string.IsNullOrEmpty(owner) &&
|
||||
!string.Equals(owner, t.Meta?.Operator, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
@@ -236,6 +221,49 @@ public sealed class TexRandomizer
|
||||
return result;
|
||||
}
|
||||
|
||||
// The textures that can be drawn, by every mini name they answer to, in the catalogue's
|
||||
// order. Made once: a scenery's worth of consists looks them up hundreds of times.
|
||||
private Dictionary<string, List<(int Order, VehicleTexture Texture)>>? _byMini;
|
||||
|
||||
/// <summary>The textures that can be drawn under any of <paramref name="minis"/>, each once, in the catalogue's order.</summary>
|
||||
private IEnumerable<VehicleTexture> ByMini(IReadOnlyList<string> minis)
|
||||
{
|
||||
_byMini ??= IndexByMini();
|
||||
var found = new List<(int Order, VehicleTexture Texture)>();
|
||||
foreach (string mini in minis)
|
||||
if (!string.IsNullOrEmpty(mini) && _byMini.TryGetValue(mini, out var textures))
|
||||
found.AddRange(textures);
|
||||
return found.Distinct().OrderBy(entry => entry.Order).Select(entry => entry.Texture);
|
||||
}
|
||||
|
||||
private Dictionary<string, List<(int Order, VehicleTexture Texture)>> IndexByMini()
|
||||
{
|
||||
var index = new Dictionary<string, List<(int, VehicleTexture)>>(StringComparer.OrdinalIgnoreCase);
|
||||
int order = 0;
|
||||
foreach (var t in _db.Textures)
|
||||
{
|
||||
order++;
|
||||
if (t.Wreck) continue;
|
||||
if (WithoutArchival && t.ResolvedArchived) continue;
|
||||
if (_db.IsSetFollower(t)) continue;
|
||||
|
||||
string candidateMini = t.ResolvedClass;
|
||||
if (string.IsNullOrEmpty(candidateMini))
|
||||
candidateMini = _db.ResolveMiniName(t) ?? "";
|
||||
if (string.IsNullOrEmpty(candidateMini)) continue;
|
||||
|
||||
foreach (string? name in new[] { candidateMini, t.TextureMini, t.MiniRef }
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
if (!index.TryGetValue(name, out var list))
|
||||
index[name] = list = new List<(int, VehicleTexture)>();
|
||||
list.Add((order, t));
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public static int? ParseRevisionYear(string? revision)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(revision)) return null;
|
||||
|
||||
@@ -8,6 +8,7 @@ using StarterNG.Classes;
|
||||
using StarterNG.Domain.Sceneries;
|
||||
using StarterNG.Domain.Vehicles;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
namespace StarterNG.Domain;
|
||||
|
||||
@@ -30,10 +31,27 @@ public static class TrainsetDisplay
|
||||
!string.IsNullOrEmpty(trainset.Description) &&
|
||||
trainset.Description.TrimStart().StartsWith("-", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Whether a list of the scenery's consists shows it, under the two filters those lists have.</summary>
|
||||
/// <summary>Whether a list of the scenery's consists shows it, under the filters those lists have.</summary>
|
||||
public static bool ListedIn(Trainset trainset, bool showAi, bool drivableOnly, Trainset? current) =>
|
||||
(showAi || !IsAi(trainset)) && (!drivableOnly || ListedAsDrivable(trainset, current));
|
||||
|
||||
/// <summary>
|
||||
/// Whether a list of the scenery's consists shows it: in the advanced mode under the filters
|
||||
/// the settings hold; in the standard mode, which has no filters, every consist with vehicles
|
||||
/// on it, and one emptied here, so it can be filled again or saved.
|
||||
/// </summary>
|
||||
public static bool ListedIn(Trainset trainset, SimulatorSettings settings, Trainset? current) =>
|
||||
settings.AdvancedSettings
|
||||
? ListedIn(trainset, settings.ShowAiVehicles, settings.DrivableOnly, current)
|
||||
: !IsEmpty(trainset) || SceneryTrainsetText.IsModified(trainset);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the simulator may start with the player in it: in the standard mode not in one
|
||||
/// the simulator drives itself nor in a decoration, which the scenario keeps as they are.
|
||||
/// </summary>
|
||||
public static bool StartableIn(Trainset trainset, SimulatorSettings settings) =>
|
||||
settings.AdvancedSettings || (!IsAi(trainset) && !trainset.Decor);
|
||||
|
||||
/// <summary>The consist's row in those lists: what it is made of, or the track of one with nothing on it.</summary>
|
||||
public static string ListLabel(Trainset trainset) =>
|
||||
CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? "");
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
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,7 +24,12 @@ public sealed class SceneryParser
|
||||
/// Whether the simulator opens an include, as the include names it; null leaves
|
||||
/// includes unchecked.
|
||||
/// </param>
|
||||
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null)
|
||||
/// <param name="loadsVehicle">
|
||||
/// Whether the simulator finds a vehicle's .fiz, by its folder and .mmd name as
|
||||
/// written; null leaves vehicles unchecked.
|
||||
/// </param>
|
||||
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null,
|
||||
Func<string, string, bool>? loadsVehicle = null)
|
||||
{
|
||||
string original = content;
|
||||
|
||||
@@ -38,7 +43,7 @@ public sealed class SceneryParser
|
||||
|
||||
// Read from the text with its optional includes blanked, which keeps every
|
||||
// place where it was, so a fault's line is the line in the file.
|
||||
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude);
|
||||
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude, loadsVehicle);
|
||||
var faults = syntax.Faults.ToList();
|
||||
var inlined = SceneryIncludes.Ranges(content);
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
||||
|
||||
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
|
||||
string text = SceneryIncludes.Inline(own, ReadInclude);
|
||||
var scenery = _parser.Parse(path, text, OpensInclude);
|
||||
var scenery = _parser.Parse(path, text, OpensInclude, LoadsVehicle);
|
||||
scenery.HasCompanionTimetable = binaryTerrain;
|
||||
scenery.Sources = sources;
|
||||
scenery.TextEncoding = ownEncoding;
|
||||
@@ -119,6 +119,15 @@ public sealed class SceneryRepository : ISceneryRepository
|
||||
/// </summary>
|
||||
private bool Opens(string name) => ResolveInclude(name) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the simulator finds a vehicle's definition - its .fiz, named after its
|
||||
/// .mmd, in its folder under dynamic - whatever the case of the letters. Without
|
||||
/// it the simulator leaves the vehicle out; a folder there all the same, empty,
|
||||
/// makes no difference.
|
||||
/// </summary>
|
||||
private bool LoadsVehicle(string folder, string mmd) =>
|
||||
_names.Resolve(_paths.Dynamic, $"{folder}/{mmd}.fiz") is not null;
|
||||
|
||||
/// <summary>
|
||||
/// An include's file as it is named on disk, from the scenery folder, whatever
|
||||
/// the case of its letters - as Windows, or Wine, finds it: whose consists the
|
||||
|
||||
@@ -22,15 +22,37 @@ public sealed class ExecutableLocator
|
||||
private string? _wine;
|
||||
private bool _wineLookedUp;
|
||||
private string? _missingPickLogged;
|
||||
private readonly bool _lacksAvx2;
|
||||
|
||||
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log)
|
||||
/// <param name="lacksAvx2">Whether this processor runs no AVX2; asked of it when left out.</param>
|
||||
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log,
|
||||
bool? lacksAvx2 = null)
|
||||
{
|
||||
_files = files;
|
||||
_paths = paths;
|
||||
_environment = environment;
|
||||
_log = log;
|
||||
_lacksAvx2 = lacksAvx2 ?? CpuFeatures.LacksAvx2;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The end of the name of a simulator built without AVX2, last before any extension:
|
||||
/// eu07-x64_2026-11-15_abc1234_noavx2.exe, eu07_noavx2. It runs on any x86-64 processor.
|
||||
/// </summary>
|
||||
public const string NoAvx2Suffix = "_noavx2";
|
||||
|
||||
public static bool IsNoAvx2(string path) =>
|
||||
Path.GetFileNameWithoutExtension(path).EndsWith(NoAvx2Suffix, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="executable"/> stops at its first instruction here: a build
|
||||
/// with AVX2 on a processor without it. Such a processor is told so before a start.
|
||||
/// </summary>
|
||||
public bool WillNotRunHere(string executable) => _lacksAvx2 && !IsNoAvx2(executable);
|
||||
|
||||
/// <summary>The newest build without AVX2 in the installation, or null where there is none.</summary>
|
||||
public string? NewestNoAvx2() => ListCandidates().FirstOrDefault(IsNoAvx2);
|
||||
|
||||
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
|
||||
|
||||
/// <summary>
|
||||
@@ -71,7 +93,8 @@ public sealed class ExecutableLocator
|
||||
{
|
||||
var candidates = _files.GetFiles(_paths.Root, "eu07*")
|
||||
.Where(IsCandidate)
|
||||
.OrderBy(path => IsExeOnLinux(path) ? 1 : 0)
|
||||
.OrderBy(Rank)
|
||||
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
|
||||
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
|
||||
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
||||
.ThenBy(path => Path.GetFileName(path).Length);
|
||||
@@ -101,6 +124,18 @@ public sealed class ExecutableLocator
|
||||
return CanonicalName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The order of the search. Without AVX2 a build without it comes first, the newest of
|
||||
/// them, even through Wine: the others stop at once. With AVX2 one is the last resort,
|
||||
/// as the build made for the processor runs faster; native before Wine either way.
|
||||
/// </summary>
|
||||
private int Rank(string path)
|
||||
{
|
||||
int wine = IsExeOnLinux(path) ? 1 : 0;
|
||||
int noAvx2 = IsNoAvx2(path) ? 1 : 0;
|
||||
return _lacksAvx2 ? (1 - noAvx2) * 2 + wine : wine * 2 + noAvx2;
|
||||
}
|
||||
|
||||
public List<string> ListCandidates(string? directory = null)
|
||||
{
|
||||
try
|
||||
@@ -267,33 +302,6 @@ public sealed class ExecutableLocator
|
||||
return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage";
|
||||
}
|
||||
|
||||
/// <summary>Whether the DLSS and frame generation libraries lie next to the simulator: without them it cannot use either.</summary>
|
||||
public (bool Dlss, bool FrameGeneration) DlssLibraries(string executable)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Resolve hands back either a path of its own search or the bare name of the pick.
|
||||
string full = _files.FileExists(executable) ? executable : FullPath(executable);
|
||||
string? directory = Path.GetDirectoryName(full);
|
||||
if (string.IsNullOrEmpty(directory) || !_files.DirectoryExists(directory))
|
||||
return (false, false);
|
||||
|
||||
bool windowsBuild = _files.FileExists(full)
|
||||
? Format(full) == BinaryFormat.PortableExecutable
|
||||
: _environment.IsWindows;
|
||||
|
||||
return windowsBuild
|
||||
? (Has(directory, "nvngx_dlss.dll"), Has(directory, "nvngx_dlssg.dll"))
|
||||
: (Has(directory, "libnvidia-ngx-dlss.so*"), Has(directory, "libnvidia-ngx-dlssg.so*"));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return (false, false);
|
||||
}
|
||||
}
|
||||
|
||||
private bool Has(string directory, string pattern) => _files.GetFiles(directory, pattern).Count > 0;
|
||||
|
||||
/// <summary>A path as <see cref="Resolve"/> gives it, which may be relative to the installation, made whole.</summary>
|
||||
public string FullPath(string path) =>
|
||||
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -9,16 +10,21 @@ namespace StarterNG.Infrastructure.Settings;
|
||||
|
||||
public sealed class SettingsSerializer
|
||||
{
|
||||
private readonly bool _dlssPlatform;
|
||||
|
||||
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
|
||||
public SettingsSerializer(bool dlssPlatform = true)
|
||||
/// <summary>
|
||||
/// An ini of before the tapes of the trains, its recording turned on ("blackbox yes", with the physics log of every
|
||||
/// vehicle, hundreds of files on a big scenery): moved to the tapes of the trains, the log of every vehicle off.
|
||||
/// Once: saved, the line of the trains' tapes is in the file, even turned off again before. A change of the
|
||||
/// starter's, after the file is read, so saving writes it.
|
||||
/// </summary>
|
||||
public static void MoveToTrainTapes(SimulatorSettings s)
|
||||
{
|
||||
_dlssPlatform = dlssPlatform;
|
||||
if (s.PhysicsLogTrainsInIni || !s.BlackBoxInIni || !s.BlackBox)
|
||||
return;
|
||||
s.PhysicsLogTrains = true;
|
||||
s.PhysicsLogTrainsInIni = true;
|
||||
s.PhysicsLog = false;
|
||||
}
|
||||
|
||||
public bool DlssPlatform => _dlssPlatform;
|
||||
|
||||
public void Read(SimulatorSettings s, ConfigFile c)
|
||||
{
|
||||
s.LanguageWasSet = c.Has("lang");
|
||||
@@ -30,20 +36,21 @@ public sealed class SettingsSerializer
|
||||
s.FpsAverage = c.GetDouble("fpsaverage", 0);
|
||||
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");
|
||||
if (mouse.Length >= 1 && double.TryParse(mouse[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double mx))
|
||||
if (mouse.Length >= 1 && TryParseMouseScale(mouse[0], out double mx))
|
||||
{
|
||||
s.InvertMouseHorizontal = mx < 0;
|
||||
s.MouseScaleXMagnitude = Math.Abs(mx);
|
||||
s.CursorSensitivity = SensitivityStep(mx);
|
||||
}
|
||||
if (mouse.Length >= 2 && double.TryParse(mouse[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double my))
|
||||
{
|
||||
s.InvertMouseVertical = my < 0;
|
||||
s.MouseScaleYMagnitude = Math.Abs(my);
|
||||
}
|
||||
if (mouse.Length >= 1)
|
||||
s.InvertMouseVertical = mouse.Length >= 2 && TryParseMouseScale(mouse[1], out double my) && my < 0;
|
||||
|
||||
s.IgnoreGamepad = !c.GetBool("input.gamepad", true);
|
||||
s.IgnoreGamepad = !c.GetBool("input.gamepad", false);
|
||||
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
|
||||
s.FeedbackPort = c.GetInt("feedbackport", 888);
|
||||
s.UartEnabled = c.Has("uart");
|
||||
@@ -76,8 +83,7 @@ public sealed class SettingsSerializer
|
||||
s.VirtualShunting = c.GetBool("ai.trainman", true);
|
||||
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
|
||||
|
||||
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "full"));
|
||||
s.VulkanDevice = c.GetString("gfx.vulkan.device", "");
|
||||
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default"));
|
||||
s.Width = c.GetInt("width", 1280);
|
||||
s.Height = c.GetInt("height", 720);
|
||||
s.BufferScalePercent = ReadBufferScale(c);
|
||||
@@ -85,9 +91,6 @@ public sealed class SettingsSerializer
|
||||
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
|
||||
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
|
||||
s.AntiAliasing = ReadAntiAliasing(c);
|
||||
s.DlssPreset = c.GetString("gfx.dlss.preset", "default").ToLowerInvariant();
|
||||
s.FrameGeneration = ParseFrameGeneration(FirstToken(c, "gfx.framegeneration"));
|
||||
s.Reflex = ParseReflex(FirstToken(c, "gfx.reflex"));
|
||||
s.DynamicLights = Clamp(c.GetInt("dynamiclights", 7), 0, 7);
|
||||
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
|
||||
s.VSync = c.GetBool("vsync", false);
|
||||
@@ -99,34 +102,6 @@ public sealed class SettingsSerializer
|
||||
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
|
||||
s.UseVbo = c.GetBool("usevbo", true);
|
||||
s.RenderShadows = c.GetBool("shadows", true);
|
||||
s.ShadowSdsm = c.GetBool("gfx.shadow.sdsm", false);
|
||||
s.LightShadows = ParseLevel(FirstToken(c, "gfx.lights.shadows"), 2, 3);
|
||||
s.ContactShadows = ParseLevel(FirstToken(c, "gfx.contactshadows"), 0, 3);
|
||||
s.LightsClustered = c.GetBool("gfx.lights.clustered", true);
|
||||
s.AmbientOcclusion = ParseAmbientOcclusion(FirstToken(c, "gfx.postfx.ao"));
|
||||
var aoQuality = c.GetTokens("gfx.postfx.ao.quality");
|
||||
s.AoSlices = aoQuality.Length >= 1 ? ParseInt(aoQuality[0], 3) : 3;
|
||||
s.AoSteps = aoQuality.Length >= 2 ? ParseInt(aoQuality[1], 4) : 4;
|
||||
s.AoLighting = c.GetBool("gfx.postfx.ao.lighting", true);
|
||||
s.CabProbe = ParseCabProbe(FirstToken(c, "gfx.cabprobe"));
|
||||
s.CabProbeInterval = c.GetInt("gfx.cabprobe.interval", 4);
|
||||
s.CabProbeBounce = c.GetDouble("gfx.cabprobe.bounce", 1.0);
|
||||
s.CabProbeReflections = c.GetBool("gfx.cabprobe.reflections", true);
|
||||
s.CabLampLight = c.GetBool("gfx.lights.cab", true);
|
||||
s.DepthPrepassScene = c.GetBool("gfx.depthprepass.scene", false);
|
||||
s.Ssr = ParseLevel(FirstToken(c, "gfx.ssr"), 2, 3);
|
||||
s.RayTracing = c.GetBool("gfx.raytracing", false);
|
||||
s.RayTracingRange = (int)Math.Round(c.GetDouble("gfx.raytracing.range", 500));
|
||||
s.VolumetricFog = ParseVolumetricFog(FirstToken(c, "gfx.fog"));
|
||||
s.FogQuality = ParseFogQuality(FirstToken(c, "gfx.fog.quality"));
|
||||
s.Clouds = ParseLevel(FirstToken(c, "gfx.clouds"), 2, 4);
|
||||
s.CloudShadows = c.GetBool("gfx.clouds.shadows", true);
|
||||
s.Grass = c.GetBool("gfx.grass", true);
|
||||
s.GrassDistance = (int)Math.Round(c.GetDouble("gfx.grass.distance", 60));
|
||||
s.GrassDensity = c.GetDouble("gfx.grass.density", 1.0);
|
||||
s.PrecipitationParticles = c.GetInt("gfx.precipitation.particles", 65536);
|
||||
s.Bloom = c.GetBool("gfx.postfx.bloom", true);
|
||||
s.AutoExposure = c.GetBool("gfx.postfx.autoexposure", true);
|
||||
// A negative rate counts as its size; none at all, as never.
|
||||
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
|
||||
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
|
||||
@@ -150,6 +125,7 @@ public sealed class SettingsSerializer
|
||||
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
|
||||
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
|
||||
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
|
||||
s.FullscreenMonitor = c.GetString("fullscreenmonitor", "").Trim();
|
||||
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4);
|
||||
@@ -157,6 +133,11 @@ public sealed class SettingsSerializer
|
||||
s.EnableTraction = c.GetBool("enabletraction", true);
|
||||
s.LiveTraction = c.GetBool("livetraction", true);
|
||||
s.PhysicsLog = c.GetBool("physicslog", false);
|
||||
s.PhysicsLogTrainsInIni = c.Has("physicslog.trains");
|
||||
s.PhysicsLogTrains = c.GetBool("physicslog.trains", false);
|
||||
// the simulator records the black box along with the physics logs when the ini says nothing of it
|
||||
s.BlackBoxInIni = c.Has("blackbox");
|
||||
s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog || s.PhysicsLogTrains;
|
||||
int debugLog = c.GetInt("debuglog", 3);
|
||||
s.DebugLog = (debugLog & 1) != 0;
|
||||
s.DebugLogVisible = (debugLog & 2) != 0;
|
||||
@@ -193,6 +174,8 @@ public sealed class SettingsSerializer
|
||||
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
|
||||
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
|
||||
s.AutoExpandSceneryTree = c.GetBool("starter.expandtree", false);
|
||||
s.AdvancedSettings = c.GetBool("starter.settings.advanced", false);
|
||||
s.MovedToStandard = c.GetBool("starter.settings.standard", false);
|
||||
s.CpuNotice = c.GetBool("starter.cpunotice", true);
|
||||
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
|
||||
? GpuPreference.System
|
||||
@@ -217,7 +200,7 @@ public sealed class SettingsSerializer
|
||||
if (c.Has(key.Key))
|
||||
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
|
||||
|
||||
GraphicsRules.Normalize(s, _dlssPlatform);
|
||||
GraphicsRules.Normalize(s);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -228,13 +211,20 @@ public sealed class SettingsSerializer
|
||||
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
|
||||
|
||||
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
|
||||
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "gfx.vulkan.device" };
|
||||
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "fullscreenmonitor" };
|
||||
|
||||
/// <summary>Keys no simulator reads any more, taken out of the file on a save.</summary>
|
||||
public static readonly string[] ObsoleteKeys =
|
||||
{
|
||||
"gfx.postfx.tonemapping",
|
||||
"starter.developertools",
|
||||
// The OpenGL 4.6 and Vulkan renderers', which the simulator's master does not have.
|
||||
"gfx.antialiasing", "gfx.buffer.percent", "gfx.vulkan.device", "gfx.dlss.preset", "gfx.framegeneration",
|
||||
"gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.ssr", "gfx.lights.clustered", "gfx.lights.shadows",
|
||||
"gfx.contactshadows", "gfx.shadow.sdsm", "gfx.postfx.ao", "gfx.postfx.ao.lighting", "gfx.postfx.ao.quality",
|
||||
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.bounce", "gfx.cabprobe.reflections", "gfx.fog",
|
||||
"gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows", "gfx.postfx.bloom", "gfx.postfx.autoexposure",
|
||||
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density", "gfx.precipitation.particles",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -244,7 +234,7 @@ public sealed class SettingsSerializer
|
||||
public void Write(SimulatorSettings settings, ConfigFile c)
|
||||
{
|
||||
var s = settings.Copy();
|
||||
GraphicsRules.Normalize(s, _dlssPlatform);
|
||||
GraphicsRules.Normalize(s);
|
||||
|
||||
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
|
||||
? "en"
|
||||
@@ -257,7 +247,7 @@ public sealed class SettingsSerializer
|
||||
? s.MouseScaleXMagnitude
|
||||
: s.CursorSensitivity;
|
||||
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",
|
||||
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
|
||||
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
|
||||
@@ -292,26 +282,16 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
|
||||
|
||||
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
|
||||
if (!string.IsNullOrWhiteSpace(s.VulkanDevice)) c.Set("gfx.vulkan.device", s.VulkanDevice.Trim());
|
||||
c.SetInt("width", s.Width);
|
||||
c.SetInt("height", s.Height);
|
||||
c.SetInt("starter.bufferscale", s.BufferScalePercent);
|
||||
int fbw = (int)Math.Round(s.Width * s.BufferScalePercent / 100.0);
|
||||
int fbh = (int)Math.Round(s.Height * s.BufferScalePercent / 100.0);
|
||||
// The size for the simulators before gfx.buffer.percent, which pass that one over and the other way round.
|
||||
c.SetInt("gfx.framebuffer.width", fbw);
|
||||
c.SetInt("gfx.framebuffer.height", fbh);
|
||||
c.SetInt("gfx.buffer.percent", s.BufferScalePercent);
|
||||
// The simulator draws into a buffer of this size and stretches it to the window.
|
||||
c.SetInt("gfx.framebuffer.width", (int)Math.Round(s.Width * s.BufferScalePercent / 100.0));
|
||||
c.SetInt("gfx.framebuffer.height", (int)Math.Round(s.Height * s.BufferScalePercent / 100.0));
|
||||
c.SetInt("maxtexturesize", s.MaxTextureSize);
|
||||
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
|
||||
c.SetDouble("anisotropicfiltering", s.TextureFiltering);
|
||||
// multisampling is what older simulators read; gfx.antialiasing overrides it in the new ones, but only from
|
||||
// a later line, since each key sets the mode as it is read.
|
||||
c.SetInt("multisampling", MultisamplingLevel(s.AntiAliasing));
|
||||
c.Set("gfx.antialiasing", AntiAliasingToken(s.AntiAliasing));
|
||||
c.Set("gfx.dlss.preset", s.DlssPreset);
|
||||
c.Set("gfx.framegeneration", s.FrameGeneration > 1 ? $"x{s.FrameGeneration}" : "off");
|
||||
c.Set("gfx.reflex", s.Reflex switch { 1 => "on", 2 => "boost", _ => "off" });
|
||||
c.SetInt("dynamiclights", s.DynamicLights);
|
||||
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
|
||||
c.SetBool("vsync", s.VSync);
|
||||
@@ -324,32 +304,6 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("usevbo", s.UseVbo);
|
||||
c.SetBool("shadows", s.RenderShadows);
|
||||
c.SetBool("gfx.shadowmap.enabled", s.RenderShadows);
|
||||
c.SetBool("gfx.shadow.sdsm", s.ShadowSdsm);
|
||||
c.Set("gfx.lights.shadows", LevelToken(s.LightShadows));
|
||||
c.Set("gfx.contactshadows", LevelToken(s.ContactShadows));
|
||||
c.SetBool("gfx.lights.clustered", s.LightsClustered);
|
||||
c.Set("gfx.postfx.ao", s.AmbientOcclusion switch { 1 => "ssao", 2 => "gtao", _ => "no" });
|
||||
c.Set("gfx.postfx.ao.quality", $"{s.AoSlices} {s.AoSteps}");
|
||||
c.SetBool("gfx.postfx.ao.lighting", s.AoLighting);
|
||||
c.Set("gfx.cabprobe", LevelToken(s.CabProbe));
|
||||
c.SetInt("gfx.cabprobe.interval", s.CabProbeInterval);
|
||||
c.SetDouble("gfx.cabprobe.bounce", s.CabProbeBounce);
|
||||
c.SetBool("gfx.cabprobe.reflections", s.CabProbeReflections);
|
||||
c.Set("gfx.ssr", LevelToken(s.Ssr));
|
||||
c.SetBool("gfx.raytracing", s.RayTracing);
|
||||
c.SetInt("gfx.raytracing.range", s.RayTracingRange);
|
||||
c.Set("gfx.fog", s.VolumetricFog ? "yes" : "analytic");
|
||||
c.Set("gfx.fog.quality", LevelToken(s.FogQuality));
|
||||
c.Set("gfx.clouds", LevelToken(s.Clouds));
|
||||
c.SetBool("gfx.clouds.shadows", s.CloudShadows);
|
||||
c.SetBool("gfx.grass", s.Grass);
|
||||
c.SetInt("gfx.grass.distance", s.GrassDistance);
|
||||
// The grass thins out past its distance; the simulator's own default keeps a sixth of it for that.
|
||||
c.SetInt("gfx.grass.fadedistance", Math.Min(600, s.GrassDistance + Math.Max(10, s.GrassDistance / 6)));
|
||||
c.SetDouble("gfx.grass.density", s.GrassDensity);
|
||||
c.SetInt("gfx.precipitation.particles", s.PrecipitationParticles);
|
||||
c.SetBool("gfx.postfx.bloom", s.Bloom);
|
||||
c.SetBool("gfx.postfx.autoexposure", s.AutoExposure);
|
||||
c.Set("gfx.reflections.framerate", s.ReflectionsFramerate.ToString("0.######", CultureInfo.InvariantCulture));
|
||||
c.Set("shadowtune",
|
||||
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
|
||||
@@ -363,6 +317,7 @@ public sealed class SettingsSerializer
|
||||
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
|
||||
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
|
||||
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
|
||||
if (!string.IsNullOrWhiteSpace(s.FullscreenMonitor)) c.Set("fullscreenmonitor", s.FullscreenMonitor.Trim());
|
||||
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
|
||||
|
||||
c.SetInt("splinefidelity", s.SplineFidelity);
|
||||
@@ -370,6 +325,13 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("enabletraction", s.EnableTraction);
|
||||
c.SetBool("livetraction", s.LiveTraction);
|
||||
c.SetBool("physicslog", s.PhysicsLog);
|
||||
// written where it says more than the physics logs, or where the file has it already: an ini without it
|
||||
// stays so, and a line written once and no longer saying more goes away on the next save
|
||||
if (s.BlackBoxInIni || s.BlackBox != (s.PhysicsLog || s.PhysicsLogTrains))
|
||||
c.SetBool("blackbox", s.BlackBox);
|
||||
// a simulator before it doesn't know the line: an ini without it stays so while it is off
|
||||
if (s.PhysicsLogTrainsInIni || s.PhysicsLogTrains)
|
||||
c.SetBool("physicslog.trains", s.PhysicsLogTrains);
|
||||
c.SetInt("debuglog",
|
||||
(s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits);
|
||||
c.SetBool("multiplelogs", s.MultipleLogs);
|
||||
@@ -402,6 +364,8 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("starter.autoclose", s.AutoCloseStarter);
|
||||
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
|
||||
c.SetBool("starter.expandtree", s.AutoExpandSceneryTree);
|
||||
c.SetBool("starter.settings.advanced", s.AdvancedSettings);
|
||||
c.SetBool("starter.settings.standard", s.MovedToStandard);
|
||||
c.SetBool("starter.cpunotice", s.CpuNotice);
|
||||
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
|
||||
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
|
||||
@@ -420,60 +384,42 @@ public sealed class SettingsSerializer
|
||||
c.Set(key.Key, value.Trim());
|
||||
}
|
||||
|
||||
// What the simulator goes by: up to 4 a part of the window, above it percents.
|
||||
private static int ReadBufferScale(ConfigFile c)
|
||||
{
|
||||
if (!c.Has("gfx.buffer.percent"))
|
||||
return Clamp(c.GetInt("starter.bufferscale", 100), 25, 200);
|
||||
private static int ReadBufferScale(ConfigFile c) =>
|
||||
Clamp(BufferScaleIn(c), 25, GraphicsRules.MaxBufferScale);
|
||||
|
||||
double value = c.GetDouble("gfx.buffer.percent", 100);
|
||||
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
|
||||
// The starter's own percent, or the framebuffer the file sets against its window.
|
||||
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);
|
||||
return tokens.Length > 0 ? tokens[0].ToLowerInvariant() : string.Empty;
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (c.GetInt("maxcabtexturesize", 0) > GraphicsRules.MaxCabTextureSize)
|
||||
keys.Add("maxcabtexturesize");
|
||||
var shadowTune = c.GetTokens("shadowtune");
|
||||
if (shadowTune.Length >= 3 && ParseDouble(shadowTune[2], 0) > GraphicsRules.MaxShadowRange)
|
||||
keys.Add("shadowtune");
|
||||
if (BufferScaleIn(c) > GraphicsRules.MaxBufferScale)
|
||||
keys.UnionWith(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height" });
|
||||
return keys;
|
||||
}
|
||||
|
||||
// The names the simulator takes for Vulkan; every other word is OpenGL to the screen, and stays in the file until changed.
|
||||
// Whichever of the two keys comes later in the file decides, as each sets the mode when the simulator reads it.
|
||||
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c)
|
||||
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c) => c.GetInt("multisampling", 2) switch
|
||||
{
|
||||
var fromMultisampling = c.GetInt("multisampling", 2) switch
|
||||
{
|
||||
<= 0 => AntiAliasingMode.Off,
|
||||
1 => AntiAliasingMode.Msaa2,
|
||||
2 => AntiAliasingMode.Msaa4,
|
||||
_ => AntiAliasingMode.Msaa8
|
||||
};
|
||||
|
||||
if (!c.Has("gfx.antialiasing") ||
|
||||
(c.Has("multisampling") && c.LineOf("multisampling") > c.LineOf("gfx.antialiasing")))
|
||||
return fromMultisampling;
|
||||
|
||||
return FirstToken(c, "gfx.antialiasing") switch
|
||||
{
|
||||
"off" or "no" or "none" or "0" => AntiAliasingMode.Off,
|
||||
"msaax2" => AntiAliasingMode.Msaa2,
|
||||
"msaax4" => AntiAliasingMode.Msaa4,
|
||||
"msaax8" or "msaax16" => AntiAliasingMode.Msaa8,
|
||||
"taa" => AntiAliasingMode.Taa,
|
||||
"dlss" => AntiAliasingMode.Dlss,
|
||||
"dlaa" => AntiAliasingMode.Dlaa,
|
||||
_ => fromMultisampling
|
||||
};
|
||||
}
|
||||
|
||||
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"
|
||||
<= 0 => AntiAliasingMode.Off,
|
||||
1 => AntiAliasingMode.Msaa2,
|
||||
2 => AntiAliasingMode.Msaa4,
|
||||
_ => AntiAliasingMode.Msaa8
|
||||
};
|
||||
|
||||
private static int MultisamplingLevel(AntiAliasingMode mode) => mode switch
|
||||
@@ -484,79 +430,28 @@ public sealed class SettingsSerializer
|
||||
_ => 0
|
||||
};
|
||||
|
||||
private static int ParseFrameGeneration(string value) => value switch
|
||||
{
|
||||
"x2" or "on" or "yes" or "2" => 2,
|
||||
"x3" or "3" => 3,
|
||||
"x4" or "4" => 4,
|
||||
_ => 1
|
||||
};
|
||||
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
||||
|
||||
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,
|
||||
"boost" or "2" => 2,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
// no/low/medium/high(/ultra) or the number of the level; an absent key keeps the simulator's default.
|
||||
private static int ParseLevel(string value, int fallback, int max)
|
||||
{
|
||||
if (value.Length == 0)
|
||||
return fallback;
|
||||
int level = value switch
|
||||
{
|
||||
"low" or "1" => 1,
|
||||
"medium" or "yes" or "true" or "2" => 2,
|
||||
"high" or "3" => 3,
|
||||
"ultra" or "4" => 4,
|
||||
_ => 0
|
||||
};
|
||||
return Math.Min(level, max);
|
||||
string[] tokens = (raw ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||
return tokens.Length >= 2 &&
|
||||
TryParseMouseScale(tokens[0], out _) &&
|
||||
TryParseMouseScale(tokens[1], out double y) &&
|
||||
Math.Abs(y) == SimulatorSettings.MouseScaleY;
|
||||
}
|
||||
|
||||
private static string LevelToken(int level) => level switch
|
||||
{
|
||||
1 => "low",
|
||||
2 => "medium",
|
||||
3 => "high",
|
||||
4 => "ultra",
|
||||
_ => "no"
|
||||
};
|
||||
|
||||
// As the simulator reads it, but a value it does not know keeps its default (medium) rather than turning the probe off.
|
||||
private static int ParseCabProbe(string value) => value switch
|
||||
{
|
||||
"no" or "false" or "off" or "0" => 0,
|
||||
"low" or "1" => 1,
|
||||
"high" or "3" => 3,
|
||||
_ => 2
|
||||
};
|
||||
|
||||
private static int ParseAmbientOcclusion(string value) => value switch
|
||||
{
|
||||
"" => 2,
|
||||
"yes" or "true" or "1" or "gtao" => 2,
|
||||
"ssao" => 1,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
private static bool ParseVolumetricFog(string value) =>
|
||||
value is not ("analytic" or "old" or "no" or "false" or "0");
|
||||
|
||||
private static int ParseFogQuality(string value) => value switch
|
||||
{
|
||||
"low" or "1" => 1,
|
||||
"high" or "3" => 3,
|
||||
"ultra" or "4" => 4,
|
||||
_ => 2
|
||||
};
|
||||
|
||||
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
||||
private static bool TryParseMouseScale(string token, out double scale) =>
|
||||
double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale) &&
|
||||
double.IsFinite(scale) && scale != 0;
|
||||
|
||||
private static int SensitivityStep(double mouseScale) =>
|
||||
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
|
||||
|
||||
private static double ParseDouble(string s, double 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ using StarterNG.Infrastructure;
|
||||
using StarterNG.Views;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Application.Abstractions;
|
||||
using StarterNG.Domain;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
namespace StarterNG;
|
||||
@@ -40,8 +41,9 @@ public partial class MainWindow : Window
|
||||
private DateTime _openedUtc = DateTime.UtcNow;
|
||||
private DateTime _startedUtc = DateTime.MinValue;
|
||||
private bool _starting;
|
||||
private bool _lookingAtSceneryFiles;
|
||||
private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = TimeSpan.FromSeconds(2) };
|
||||
// Scenery files: looked at when they change, on coming back to the window or from the
|
||||
// simulator, and now and then anyway.
|
||||
private readonly FolderLooks _sceneryLooks;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
@@ -102,29 +104,37 @@ public partial class MainWindow : Window
|
||||
AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel);
|
||||
|
||||
AppServices.Current.State.Changed += UpdateStartButton;
|
||||
Views.Settings.AdvancedModeChanged += UpdateStartButton;
|
||||
// Settings an older starter left are brought into the standard mode, once.
|
||||
SettingsView.MoveToStandardOnce();
|
||||
Opened += (_, _) =>
|
||||
{
|
||||
|
||||
_openedUtc = DateTime.UtcNow;
|
||||
UpdateStartButton();
|
||||
_sceneryFilesTimer.Start();
|
||||
FollowLastRun();
|
||||
};
|
||||
Activated += (_, _) => CheckExternalSettings();
|
||||
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
|
||||
Closed += (_, _) => _sceneryFilesTimer.Stop();
|
||||
Activated += (_, _) =>
|
||||
{
|
||||
CheckExternalSettings();
|
||||
// Back from a build or a download: a new simulator is on the list already.
|
||||
if (SettingsView.IsVisible)
|
||||
SettingsView.RefreshExecutables();
|
||||
};
|
||||
// After the handlers above: back at the window, the settings are checked first.
|
||||
_sceneryLooks = new FolderLooks(this, () => AppServices.Current.Paths.Scenery, LookAtSceneryFilesAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scenery files changed outside the starter are picked up without a reload. Not
|
||||
/// with the simulator running: it is left in peace, and what it changes comes in after it.
|
||||
/// Run through <see cref="_sceneryLooks"/>, one look at a time.
|
||||
/// </summary>
|
||||
private async Task LookAtSceneryFilesAsync()
|
||||
{
|
||||
if (_lookingAtSceneryFiles || AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
|
||||
if (AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
|
||||
return;
|
||||
|
||||
_lookingAtSceneryFiles = true;
|
||||
try
|
||||
{
|
||||
var services = AppServices.Current;
|
||||
@@ -140,10 +150,6 @@ public partial class MainWindow : Window
|
||||
{
|
||||
Diagnostics.Log("Following the scenery files", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lookingAtSceneryFiles = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -505,6 +511,15 @@ public partial class MainWindow : Window
|
||||
return;
|
||||
}
|
||||
|
||||
// The standard mode edits every consist but starts only in one the player drives.
|
||||
if (!TrainsetDisplay.StartableIn(trainset, AppServices.Current.Settings))
|
||||
{
|
||||
startButton.Content = App.Loc[trainset.Decor ? "StartDecor" : "StartAi"];
|
||||
ToolTip.SetTip(startButton, null);
|
||||
startButton.IsEnabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
bool staffed = HasStartableVehicle(trainset);
|
||||
startButton.Content = staffed ? App.Loc["Start"] : App.Loc["StartNoStaff"];
|
||||
ToolTip.SetTip(startButton, staffed ? null : App.Loc["StartNoStaffConfirm"]);
|
||||
@@ -521,11 +536,34 @@ public partial class MainWindow : Window
|
||||
private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started";
|
||||
|
||||
/// <summary>
|
||||
/// Tells a user whose processor lacks AVX2 that the published simulator will
|
||||
/// not run, and where the instructions for a build of their own are.
|
||||
/// Tells a user whose processor lacks AVX2 that the simulator that would start will
|
||||
/// not run. With a build without AVX2 in the folder, chosen away from by hand, the
|
||||
/// notice offers to go back to the automatic choice, which takes it; with none, it
|
||||
/// says what such a build is called and where the instructions for one's own are.
|
||||
/// </summary>
|
||||
public async Task ShowCpuNoticeAsync()
|
||||
public async Task ShowCpuNoticeAsync(string executable)
|
||||
{
|
||||
var services = AppServices.Current;
|
||||
if (services.Executables.NewestNoAvx2() is { } noAvx2)
|
||||
{
|
||||
var (useIt, quiet) = await MessageBox.ShowNotice(
|
||||
this, string.Format(App.Loc["CpuNoAvx2Chosen"], Path.GetFileName(executable), noAvx2),
|
||||
App.Loc["CpuNoAvx2Title"], App.Loc["CpuNoAvx2UseIt"], App.Loc["DontShowAgain"]);
|
||||
if (useIt)
|
||||
{
|
||||
services.Settings.SelectExeAutomatically = true;
|
||||
services.SettingsStore.Save();
|
||||
SettingsView.ReloadFromSettings();
|
||||
UpdateStartButton();
|
||||
}
|
||||
if (quiet)
|
||||
{
|
||||
services.Settings.CpuNotice = false;
|
||||
services.SettingsStore.Save();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var (open, silence) = await MessageBox.ShowNotice(
|
||||
this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"],
|
||||
App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]);
|
||||
@@ -608,6 +646,9 @@ public partial class MainWindow : Window
|
||||
// would start a second simulator.
|
||||
if (_starting || DateTime.UtcNow - _startedUtc < StartCooldown)
|
||||
return;
|
||||
// A shortcut starts the same way the button does, and only where the button may.
|
||||
if (!freeFly && !startButton.IsEnabled)
|
||||
return;
|
||||
|
||||
_starting = true;
|
||||
try
|
||||
@@ -623,6 +664,29 @@ public partial class MainWindow : Window
|
||||
App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// edits on the settings page not saved: saved, or let go - kept, the starter would write them when it
|
||||
// closes, perhaps while the simulator reads the file
|
||||
if (saveSettings && SettingsView.HasUnsavedChanges)
|
||||
{
|
||||
var save = await MessageBox.Choose(this, App.Loc["StartUnsavedMessage"], App.Loc["UnsavedChanges"],
|
||||
App.Loc["StartUnsavedSave"], App.Loc["StartUnsavedWithout"]);
|
||||
if (save is null)
|
||||
return;
|
||||
if (save == false)
|
||||
SettingsView.DiscardEdits();
|
||||
else
|
||||
{
|
||||
SettingsView.Save();
|
||||
// eu07.ini or the keys' file not written: still there to be saved
|
||||
if (SettingsView.HasUnsavedChanges)
|
||||
{
|
||||
await MessageBox.Show(this, App.Loc["SettingsNotSaved"], App.Loc["UnsavedChanges"],
|
||||
MessageBoxButtons.Ok);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path));
|
||||
|
||||
await FollowStartAsync(() => AppServices.Current.StartSimulation.Execute(freeFly, saveSettings));
|
||||
@@ -713,6 +777,8 @@ public partial class MainWindow : Window
|
||||
FollowLastRun();
|
||||
RestoreFromSimulator();
|
||||
ReportIfCrashed(simulator, executable, started);
|
||||
// What the simulator or its editor wrote while it ran comes in now.
|
||||
_ = _sceneryLooks.LookAsync();
|
||||
}), TaskScheduler.Default);
|
||||
}
|
||||
|
||||
@@ -722,7 +788,8 @@ public partial class MainWindow : Window
|
||||
/// </summary>
|
||||
private static void FollowLastRun()
|
||||
{
|
||||
if (AppServices.Current.Settings.PhysicsLog)
|
||||
var settings = AppServices.Current.Settings;
|
||||
if (settings.PhysicsLog || settings.BlackBox || settings.PhysicsLogTrains)
|
||||
_ = Task.Run(AppServices.Current.Tapes.FollowLastRun);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,12 +10,22 @@ namespace StarterNG;
|
||||
static class Program
|
||||
{
|
||||
|
||||
private static bool _softwareRender;
|
||||
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
// Ahead of everything that could draw: what lies beside the starter is the simulator's.
|
||||
var graphics = SystemGraphicsLibraries.TakeOnWindows();
|
||||
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
|
||||
|
||||
_softwareRender = SoftwareRender.AskedIn(args);
|
||||
|
||||
// Composition root first: everything below, including the crash handlers,
|
||||
// resolves its collaborators from this graph.
|
||||
AppServices.Initialize();
|
||||
if (graphics?.Note is { } note)
|
||||
Diagnostics.Log(note);
|
||||
|
||||
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
|
||||
{
|
||||
@@ -63,9 +73,13 @@ static class Program
|
||||
};
|
||||
}
|
||||
|
||||
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
|
||||
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.WithSoftwareRenderIfAsked()
|
||||
.WithInterFont()
|
||||
.WithDiagnosticsLogging()
|
||||
.AfterSetup(_ => LogUiExceptions());
|
||||
|
||||
@@ -81,15 +81,13 @@
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,3,0,0" />
|
||||
|
||||
<!-- Why the chosen simulator would ignore the setting. Under
|
||||
the explanation, at full strength while the rest dims. -->
|
||||
<TextBlock Name="PART_IdleNote"
|
||||
<!-- A value of eu07.ini the starter cannot read: amber, as the other warnings. -->
|
||||
<TextBlock Name="PART_Unknown"
|
||||
Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"
|
||||
Text="{TemplateBinding IdleNote}"
|
||||
Text="{TemplateBinding UnknownValue}"
|
||||
IsVisible="False"
|
||||
FontSize="12"
|
||||
FontStyle="Italic"
|
||||
Foreground="{StaticResource CarbonFg}"
|
||||
Foreground="#D9A43A"
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,3,0,0" />
|
||||
|
||||
@@ -103,6 +101,13 @@
|
||||
<Style Selector="^:no-key /template/ SelectableTextBlock#PART_ConfigKey">
|
||||
<Setter Property="IsVisible" Value="False" />
|
||||
</Style>
|
||||
<!-- The standard mode: the eu07.ini key means nothing to a player. -->
|
||||
<Style Selector="^.HideKey /template/ SelectableTextBlock#PART_ConfigKey">
|
||||
<Setter Property="IsVisible" Value="False" />
|
||||
</Style>
|
||||
<Style Selector="^:unknown /template/ TextBlock#PART_Unknown">
|
||||
<Setter Property="IsVisible" Value="True" />
|
||||
</Style>
|
||||
<Style Selector="^:no-value /template/ TextBlock#PART_Value">
|
||||
<Setter Property="IsVisible" Value="False" />
|
||||
</Style>
|
||||
@@ -113,24 +118,6 @@
|
||||
<Setter Property="Grid.Column" Value="1" />
|
||||
<Setter Property="Grid.ColumnSpan" Value="2" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ TextBlock#PART_IdleNote">
|
||||
<Setter Property="IsVisible" Value="True" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ TextBlock#PART_Label">
|
||||
<Setter Property="Opacity" Value="0.45" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ ContentPresenter#PART_Content">
|
||||
<Setter Property="Opacity" Value="0.45" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ TextBlock#PART_Value">
|
||||
<Setter Property="Opacity" Value="0.45" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ TextBlock#PART_Description">
|
||||
<Setter Property="Opacity" Value="0.45" />
|
||||
</Style>
|
||||
<Style Selector="^:idle /template/ SelectableTextBlock#PART_ConfigKey">
|
||||
<Setter Property="Opacity" Value="0.45" />
|
||||
</Style>
|
||||
<!-- A checkbox is its own label, so let it take the label column too.
|
||||
Alignment stays Stretch: a bare slider in a labelless row still
|
||||
wants the full width. -->
|
||||
|
||||
@@ -137,7 +137,8 @@
|
||||
HorizontalContentAlignment="Center"
|
||||
Click="AddToWarehouseButton_OnClick"
|
||||
Content="{Binding [AddToWarehouse], Source={x:Static starterNg:App.Loc}}" />
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
|
||||
<!-- The advanced mode's own: the standard mode lists every consist with vehicles. -->
|
||||
<StackPanel Name="consistFilters" DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
|
||||
Margin="2,6,0,0">
|
||||
<CheckBox Name="depotDrivableOnlyCheck" FontSize="12"
|
||||
IsCheckedChanged="ConsistFilter_OnChanged"
|
||||
|
||||
@@ -69,6 +69,13 @@ public partial class Depot : UserControl
|
||||
if (Design.IsDesignMode)
|
||||
return;
|
||||
|
||||
// The standard mode lists other consists and leaves the crew alone.
|
||||
Settings.AdvancedModeChanged += () =>
|
||||
{
|
||||
PopulateSceneryConsists();
|
||||
RebuildConsist();
|
||||
};
|
||||
|
||||
_warehouse = new Warehouse(warehouseList, removeFromWarehouseButton, _hand,
|
||||
() => AppServices.Current.State.CurrentTrainset, ApplyFromWarehouse);
|
||||
_warehouse.SelectionChanged += () =>
|
||||
@@ -77,6 +84,7 @@ public partial class Depot : UserControl
|
||||
EditWarehouseSelection();
|
||||
};
|
||||
_warehouse.Renamed += _warehouseEdit.Renamed;
|
||||
_warehouseEdit.Saved += _warehouse.RefreshEntry;
|
||||
|
||||
_browser = new VehicleBrowser(categoryCombo, classCombo, vehicleListBox, searchBox,
|
||||
hideArchivalCheck, miniPreview, addVehicleButton, _db, _minis, OpenVehicleBase)
|
||||
@@ -597,6 +605,7 @@ public partial class Depot : UserControl
|
||||
|
||||
depotShowAiCheck.IsChecked = AppServices.Current.Settings.ShowAiVehicles;
|
||||
depotDrivableOnlyCheck.IsChecked = AppServices.Current.Settings.DrivableOnly;
|
||||
consistFilters.IsVisible = AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
_listScenery = AppServices.Current.State.CurrentScenery ?? _sceneries.FirstOrDefault();
|
||||
sceneryConsistsTab.Header = App.Loc["SceneryConsists"];
|
||||
@@ -605,12 +614,11 @@ public partial class Depot : UserControl
|
||||
|
||||
if (_listScenery != null)
|
||||
{
|
||||
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
|
||||
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
|
||||
var settings = AppServices.Current.Settings;
|
||||
|
||||
foreach (var trainset in _listScenery.Trainsets)
|
||||
{
|
||||
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, AppServices.Current.State.CurrentTrainset))
|
||||
if (!TrainsetDisplay.ListedIn(trainset, settings, AppServices.Current.State.CurrentTrainset))
|
||||
continue;
|
||||
|
||||
var entry = new ListBoxItem
|
||||
@@ -754,17 +762,29 @@ public partial class Depot : UserControl
|
||||
if (scenery.Trainsets.Count == 0) return;
|
||||
if (await AskTextureRandomizerOpts() is not { } opts) return;
|
||||
|
||||
var editing = _consist.EditingTrainset;
|
||||
// Each consist goes through a consist of its own, off the screen: the strip and the
|
||||
// list are drawn again once at the end, not for every consist on the way, and one
|
||||
// randomizer looks the candidates up for all of them.
|
||||
var work = new Consist(_db, _info);
|
||||
var rnd = TextureRandomizer(opts);
|
||||
var changed = new HashSet<Trainset>(ReferenceEqualityComparer.Instance);
|
||||
foreach (var trainset in scenery.Trainsets)
|
||||
{
|
||||
_consist.LoadFrom(trainset);
|
||||
if (ApplyTextureRandomizer(opts))
|
||||
WriteBackToScenery();
|
||||
work.LoadFrom(trainset);
|
||||
if (work.Count == 0 || rnd.Apply(work, texture => work.MakeDynamic(texture, scenery)) <= 0)
|
||||
continue;
|
||||
work.AutoConnectAll();
|
||||
trainset.Vehicles = work.Flatten();
|
||||
changed.Add(trainset);
|
||||
}
|
||||
if (changed.Count == 0)
|
||||
return;
|
||||
|
||||
if (editing != null)
|
||||
if (_consist.EditingTrainset is { } editing && changed.Contains(editing))
|
||||
_consist.LoadFrom(editing);
|
||||
RebuildConsist();
|
||||
RefreshConsistListLabels();
|
||||
if (AppServices.Current.State.CurrentTrainset is { } current && changed.Contains(current))
|
||||
AppServices.Current.State.NotifyChanged();
|
||||
}
|
||||
|
||||
private async Task<TextureRandomizerDialog.Options?> AskTextureRandomizerOpts() =>
|
||||
@@ -776,19 +796,21 @@ public partial class Depot : UserControl
|
||||
{
|
||||
if (_consist.Count == 0) return false;
|
||||
|
||||
var rnd = new TexRandomizer(_db, _rng)
|
||||
{
|
||||
WithoutArchival = opts.WithoutArchival,
|
||||
RevisionTolerance = opts.RevisionTolerance,
|
||||
RevYear = opts.RevYear
|
||||
};
|
||||
if (rnd.Apply(_consist, NewVehicle) <= 0)
|
||||
if (TextureRandomizer(opts).Apply(_consist, NewVehicle) <= 0)
|
||||
return false;
|
||||
|
||||
_consist.AutoConnectAll();
|
||||
return true;
|
||||
}
|
||||
|
||||
private TexRandomizer TextureRandomizer(TextureRandomizerDialog.Options opts) =>
|
||||
new(_db, _rng)
|
||||
{
|
||||
WithoutArchival = opts.WithoutArchival,
|
||||
RevisionTolerance = opts.RevisionTolerance,
|
||||
RevYear = opts.RevYear
|
||||
};
|
||||
|
||||
private void RandomOrderButton_OnClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) =>
|
||||
_consist.RandomizeOrder(_rng);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Linq;
|
||||
using Avalonia;
|
||||
using Avalonia.Automation;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Documents;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
@@ -536,8 +537,21 @@ public sealed class VehicleBrowser
|
||||
// mostly by who runs them.
|
||||
private static Control BrowserLabel(VehicleTexture texture, IReadOnlyList<VehicleTexture>? set)
|
||||
{
|
||||
// Clear of the scroll bar, which lies over the right edge of the list.
|
||||
var row = new DockPanel { Margin = new Thickness(0, 0, 10, 0) };
|
||||
// Clear of the scroll bar, which lies over the right edge of the list. The name comes
|
||||
// first: a long operator is cut short to a width of its own, and either ends in "…"
|
||||
// rather than running into the other.
|
||||
var row = new Grid { Margin = new Thickness(0, 0, 10, 0), ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
|
||||
var name = new TextBlock { TextTrimming = TextTrimming.CharacterEllipsis };
|
||||
name.Inlines!.Add(new Run(BrowserName(texture)));
|
||||
if (set is { Count: > 1 })
|
||||
{
|
||||
var count = new Run($" ×{set.Count}");
|
||||
if (Avalonia.Application.Current?.TryGetResource("CarbonFgDim", null, out var dim) == true && dim is IBrush brush)
|
||||
count.Foreground = brush;
|
||||
name.Inlines.Add(count);
|
||||
}
|
||||
row.Children.Add(name);
|
||||
|
||||
string? op = texture.Meta?.Operator;
|
||||
if (!string.IsNullOrWhiteSpace(op) && op != "?")
|
||||
@@ -546,19 +560,14 @@ public sealed class VehicleBrowser
|
||||
{
|
||||
Text = op,
|
||||
Opacity = 0.55,
|
||||
MaxWidth = 110,
|
||||
Margin = new Thickness(8, 0, 0, 0),
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
DockPanel.SetDock(operatorText, Dock.Right);
|
||||
Grid.SetColumn(operatorText, 1);
|
||||
row.Children.Add(operatorText);
|
||||
}
|
||||
|
||||
var name = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
|
||||
name.Children.Add(new TextBlock { Text = BrowserName(texture) });
|
||||
if (set is { Count: > 1 })
|
||||
name.Children.Add(new TextBlock { Text = $"×{set.Count}", Opacity = 0.55 });
|
||||
row.Children.Add(name);
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using StarterNG.Application;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
@@ -116,7 +117,9 @@ public sealed class VehicleCards
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
Margin = new Thickness(0, 1, 0, 2)
|
||||
};
|
||||
controls.Children.Add(DriverButton(item));
|
||||
// Who sits in the cab - the player, the simulator, a passenger or nobody - is for the advanced mode.
|
||||
if (AppServices.Current.Settings.AdvancedSettings)
|
||||
controls.Children.Add(DriverButton(item));
|
||||
controls.Children.Add(FlipButton(item));
|
||||
|
||||
if (item.Grouped && item.Cars.Count > 1)
|
||||
@@ -692,10 +695,13 @@ public sealed class VehicleCards
|
||||
else if (_consist.CanJoin(item, index))
|
||||
menu.AddItem(App.Loc["TipJoin"], () => _consist.Join(item));
|
||||
|
||||
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
|
||||
foreach (var (type, key) in CrewChoices.All)
|
||||
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
|
||||
menu.Items.Add(crew);
|
||||
if (AppServices.Current.Settings.AdvancedSettings)
|
||||
{
|
||||
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
|
||||
foreach (var (type, key) in CrewChoices.All)
|
||||
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
|
||||
menu.Items.Add(crew);
|
||||
}
|
||||
|
||||
// The member the panels show, not always the first car of a unit.
|
||||
menu.AddItem(App.Loc["WagonNumber"] + "…",
|
||||
|
||||
@@ -280,6 +280,8 @@ public sealed class VehicleDetails
|
||||
};
|
||||
driver.MinWidth = 0;
|
||||
driver.HorizontalAlignment = HorizontalAlignment.Stretch;
|
||||
// Shown but not changed in the standard mode: who drives is for the advanced one.
|
||||
driver.IsEnabled = AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
var rows = new StackPanel();
|
||||
rows.Children.Add(Row(App.Loc["CrewLabel"], driver));
|
||||
|
||||
@@ -62,11 +62,7 @@ public sealed class Warehouse
|
||||
var entry = new ListBoxItem
|
||||
{
|
||||
Tag = preset.Name,
|
||||
Content = new TextBlock
|
||||
{
|
||||
Text = preset.Name,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
}
|
||||
Content = EntryContent(preset.Name, preset.Entry)
|
||||
};
|
||||
_list.Items.Add(entry);
|
||||
if (current is not null && string.Equals(current, preset.Name, StringComparison.Ordinal))
|
||||
@@ -81,6 +77,48 @@ public sealed class Warehouse
|
||||
SelectionChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The consist's name, and under it its vehicles as minis - as the scenery's consists
|
||||
/// are listed - so one is told from another without opening it.
|
||||
/// </summary>
|
||||
private static Control EntryContent(string presetName, string entry)
|
||||
{
|
||||
var name = new TextBlock
|
||||
{
|
||||
Text = presetName,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
if (ConsistText.VehiclesFrom(entry) is not { } vehicles)
|
||||
return name;
|
||||
|
||||
var content = new StackPanel
|
||||
{
|
||||
Spacing = 2,
|
||||
Margin = new Thickness(0, 3),
|
||||
Children = { name, TrainsetRow.ScrollingStrip(vehicles) }
|
||||
};
|
||||
// Read by its name, not by every caption under it.
|
||||
Avalonia.Automation.AutomationProperties.SetName(content, presetName);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Redraws one consist's entry after it was edited and saved, so its minis follow the
|
||||
/// edit at once - the rest of the list, its selection and where it is scrolled stay.
|
||||
/// </summary>
|
||||
public void RefreshEntry(string name, string entry)
|
||||
{
|
||||
foreach (var obj in _list.Items)
|
||||
{
|
||||
if (obj is ListBoxItem { Tag: string tag } item &&
|
||||
string.Equals(tag, name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item.Content = EntryContent(tag, entry);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string? SelectedName() => (_list.SelectedItem as ListBoxItem)?.Tag as string;
|
||||
|
||||
public TrainsetPreset? SelectedPreset() => SelectedName() is { } name ? PresetNamed(name) : null;
|
||||
|
||||
31
StarterNG/Views/ExecutableList.cs
Normal file
31
StarterNG/Views/ExecutableList.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace StarterNG.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The simulators offered in the settings after the folder was looked at again: a build
|
||||
/// copied in while the starter runs joins the list, and what was chosen stays chosen, even
|
||||
/// a file picked from elsewhere or one since removed - looking again never changes the choice.
|
||||
/// </summary>
|
||||
public static class ExecutableList
|
||||
{
|
||||
/// <summary>The entries that follow "automatic", and the place of <paramref name="chosen"/> among them.</summary>
|
||||
/// <param name="found">The simulators in the folder now, newest first.</param>
|
||||
/// <param name="chosen">The entry chosen, or null for "automatic" or nothing chosen yet.</param>
|
||||
/// <returns>Entries, and the index of the chosen one in them, -1 when <paramref name="chosen"/> is null.</returns>
|
||||
public static (IReadOnlyList<string> Entries, int Chosen) Refreshed(IReadOnlyList<string> found, string? chosen)
|
||||
{
|
||||
var entries = found.ToList();
|
||||
if (chosen is null)
|
||||
return (entries, -1);
|
||||
|
||||
int at = entries.FindIndex(entry => string.Equals(entry, chosen, StringComparison.OrdinalIgnoreCase));
|
||||
if (at >= 0)
|
||||
return (entries, at);
|
||||
|
||||
entries.Add(chosen);
|
||||
return (entries, entries.Count - 1);
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,98 @@ public static class MessageBox
|
||||
return yes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A warning to read before saying yes: the yes button counts down and only then
|
||||
/// takes a click. Enter and Esc both decline, so nothing is agreed to by habit.
|
||||
/// </summary>
|
||||
public static async Task<bool> ShowDelayed(Window owner, string message, string title, string yesText,
|
||||
int seconds)
|
||||
{
|
||||
var win = FixedDialog(title, 520);
|
||||
|
||||
bool yes = false;
|
||||
var yesBtn = DialogButton($"{yesText} ({seconds})", "Accent", 120, () => { yes = true; win.Close(); });
|
||||
var noBtn = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close());
|
||||
yesBtn.IsEnabled = false;
|
||||
noBtn.IsDefault = true;
|
||||
noBtn.IsCancel = true;
|
||||
ReadMessage(win, noBtn, message);
|
||||
|
||||
int left = seconds;
|
||||
var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
// Only time spent with the warning in front of the player counts: the window active and all of it on a screen.
|
||||
if (!win.IsActive || win.WindowState == WindowState.Minimized || !WhollyOnScreen(win))
|
||||
return;
|
||||
left--;
|
||||
if (left > 0)
|
||||
{
|
||||
yesBtn.Content = $"{yesText} ({left})";
|
||||
return;
|
||||
}
|
||||
timer.Stop();
|
||||
yesBtn.Content = yesText;
|
||||
yesBtn.IsEnabled = true;
|
||||
};
|
||||
win.Closed += (_, _) => timer.Stop();
|
||||
|
||||
win.Content = new StackPanel
|
||||
{
|
||||
Margin = new Avalonia.Thickness(16),
|
||||
Spacing = 16,
|
||||
Children =
|
||||
{
|
||||
new SelectableTextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
|
||||
ButtonRow(yesBtn, noBtn)
|
||||
}
|
||||
};
|
||||
|
||||
timer.Start();
|
||||
await win.ShowDialog(owner);
|
||||
return yes;
|
||||
}
|
||||
|
||||
/// <summary>Whether the whole window, frame and all, lies within the working area of one screen.</summary>
|
||||
internal static bool WhollyOnScreen(Window win)
|
||||
{
|
||||
var size = win.FrameSize ?? win.ClientSize;
|
||||
var rect = new Avalonia.PixelRect(win.Position, Avalonia.PixelSize.FromSize(size, win.RenderScaling));
|
||||
foreach (var screen in win.Screens.All)
|
||||
if (screen.WorkingArea.Contains(rect))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A question with two answers and a way back: true for the first, false for the second, null when cancelled
|
||||
/// or the window is closed - closing it never picks one of the answers.
|
||||
/// </summary>
|
||||
public static async Task<bool?> Choose(Window owner, string message, string title, string firstText,
|
||||
string secondText)
|
||||
{
|
||||
var win = FixedDialog(title, 460);
|
||||
|
||||
bool? answer = null;
|
||||
var first = DialogButton(firstText, "Accent", 80, () => { answer = true; win.Close(); });
|
||||
var second = DialogButton(secondText, "Flat", 80, () => { answer = false; win.Close(); });
|
||||
var cancel = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close());
|
||||
|
||||
win.Content = new StackPanel
|
||||
{
|
||||
Margin = new Avalonia.Thickness(16),
|
||||
Spacing = 16,
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
|
||||
ButtonRow(first, second, cancel)
|
||||
}
|
||||
};
|
||||
|
||||
await win.ShowDialog(owner);
|
||||
return answer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A notice with one action besides closing it, and a box to stop it coming
|
||||
/// back, which counts however the window is closed.
|
||||
|
||||
@@ -45,6 +45,7 @@ public partial class Scenarios : UserControl
|
||||
{
|
||||
InitializeComponent();
|
||||
SyncConsistRowHeight();
|
||||
Settings.AdvancedModeChanged += OnAdvancedModeChanged;
|
||||
|
||||
Sceneries = AppServices.Current.Library.Sceneries;
|
||||
|
||||
@@ -86,6 +87,43 @@ public partial class Scenarios : UserControl
|
||||
state.StartingVehicleName = vehicle;
|
||||
}
|
||||
|
||||
private void OnAdvancedModeChanged()
|
||||
{
|
||||
RefreshVehicleList();
|
||||
RefreshFaultMarks(sceneryList.Items);
|
||||
if (SelectedScenery is { } scenery)
|
||||
PopulateFaults(scenery);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scenery files' mistakes - written wrong, or vehicles the simulator will not
|
||||
/// find - are for those who mend sceneries: shown in the advanced mode only.
|
||||
/// </summary>
|
||||
private static bool ShowsFaults => AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
// The tree's marks put on or taken off where they stand, the selection and what is
|
||||
// unfolded kept.
|
||||
private void RefreshFaultMarks(ItemCollection items)
|
||||
{
|
||||
foreach (var obj in items)
|
||||
{
|
||||
if (obj is not TreeViewItem node)
|
||||
continue;
|
||||
if (node.Tag is int index && index < Sceneries.Count)
|
||||
{
|
||||
string? label = node.Header switch
|
||||
{
|
||||
string text => text,
|
||||
StackPanel { Children: [TextBlock name, ..] } => name.Text,
|
||||
_ => null
|
||||
};
|
||||
if (label is not null)
|
||||
node.Header = SceneryHeader(label, Sceneries[index]);
|
||||
}
|
||||
RefreshFaultMarks(node.Items);
|
||||
}
|
||||
}
|
||||
|
||||
private void BuildSceneryTree()
|
||||
{
|
||||
sceneryList.Items.Clear();
|
||||
@@ -119,7 +157,7 @@ public partial class Scenarios : UserControl
|
||||
/// <summary>The scenery's name, marked when its files hold mistakes.</summary>
|
||||
private object SceneryHeader(string label, Scenery scenery)
|
||||
{
|
||||
if (scenery.Faults.Count == 0)
|
||||
if (!ShowsFaults || scenery.Faults.Count == 0)
|
||||
return label;
|
||||
|
||||
var mark = new Material.Icons.Avalonia.MaterialIcon
|
||||
@@ -257,20 +295,13 @@ public partial class Scenarios : UserControl
|
||||
}
|
||||
|
||||
/// <summary>A consist's label in a list of them, here and on the depot page.</summary>
|
||||
internal static TextBlock TrainsetListContent(Trainset trainset) =>
|
||||
new Avalonia.Controls.TextBlock
|
||||
{
|
||||
Text = TrainsetDisplay.ListLabel(trainset),
|
||||
TextTrimming = Avalonia.Media.TextTrimming.CharacterEllipsis,
|
||||
TextWrapping = Avalonia.Media.TextWrapping.NoWrap
|
||||
};
|
||||
internal static Control TrainsetListContent(Trainset trainset) => TrainsetRow.Build(trainset);
|
||||
|
||||
private void PopulateVehicleList(Scenery scn)
|
||||
{
|
||||
vehicleList.Items.Clear();
|
||||
|
||||
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
|
||||
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
|
||||
var settings = AppServices.Current.Settings;
|
||||
var current = AppServices.Current.State.CurrentTrainset;
|
||||
ListBoxItem? currentRow = null;
|
||||
|
||||
@@ -278,7 +309,7 @@ public partial class Scenarios : UserControl
|
||||
{
|
||||
var trainset = scn.Trainsets[i];
|
||||
|
||||
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, current)) continue;
|
||||
if (!TrainsetDisplay.ListedIn(trainset, settings, current)) continue;
|
||||
|
||||
var listItem = new ListBoxItem
|
||||
{
|
||||
@@ -441,8 +472,9 @@ public partial class Scenarios : UserControl
|
||||
private void PopulateFaults(Scenery scenery)
|
||||
{
|
||||
var faults = scenery.Faults;
|
||||
faultsTab.IsVisible = faults.Count > 0;
|
||||
if (faults.Count == 0)
|
||||
bool shown = ShowsFaults && faults.Count > 0;
|
||||
faultsTab.IsVisible = shown;
|
||||
if (!shown)
|
||||
{
|
||||
if (infoTabs.SelectedItem == faultsTab)
|
||||
infoTabs.SelectedIndex = 0;
|
||||
@@ -1015,6 +1047,11 @@ public partial class Scenarios : UserControl
|
||||
});
|
||||
|
||||
var db = AppServices.Current.Library.Vehicles;
|
||||
// The start goes by the vehicle's name, so of several named alike only the first is the one marked.
|
||||
string? picked = AppServices.Current.State.StartingVehicleName;
|
||||
var pickedVehicle = string.IsNullOrEmpty(picked)
|
||||
? null
|
||||
: trainset.Vehicles.FirstOrDefault(v => string.Equals(v.Name, picked, StringComparison.OrdinalIgnoreCase));
|
||||
foreach (var train in trainset.Vehicles)
|
||||
{
|
||||
|
||||
@@ -1036,9 +1073,7 @@ public partial class Scenarios : UserControl
|
||||
})
|
||||
: MiniTextures.MissingVisual(train.SkinFile, thumbH);
|
||||
|
||||
bool selected = !string.IsNullOrEmpty(train.Name) &&
|
||||
string.Equals(train.Name, AppServices.Current.State.StartingVehicleName,
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
bool selected = ReferenceEquals(train, pickedVehicle);
|
||||
// The vehicle started in gets a frame over its picture as well as the lines above and below:
|
||||
// two thin lines alone were hard to see. Drawn over the picture, it moves no vehicle aside.
|
||||
if (selected)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
@@ -29,49 +28,11 @@ internal static class SettingTexts
|
||||
AntiAliasingMode.Msaa2 => "MSAA x2",
|
||||
AntiAliasingMode.Msaa4 => "MSAA x4",
|
||||
AntiAliasingMode.Msaa8 => "MSAA x8",
|
||||
AntiAliasingMode.Taa => App.Loc["AaTaa"],
|
||||
AntiAliasingMode.Dlss => App.Loc["AaDlss"],
|
||||
AntiAliasingMode.Dlaa => App.Loc["AaDlaa"],
|
||||
_ => App.Loc["MsaaNone"]
|
||||
};
|
||||
|
||||
private static string Level(int level) => App.Loc[level switch
|
||||
{
|
||||
1 => "LevelLow",
|
||||
2 => "LevelMedium",
|
||||
3 => "LevelHigh",
|
||||
4 => "LevelUltra",
|
||||
_ => "LevelOff"
|
||||
}];
|
||||
|
||||
public static string TwoDecimals(double value) => value.ToString("0.00", CultureInfo.CurrentCulture);
|
||||
|
||||
public static string ShadowMapWord(int pixels) => pixels switch
|
||||
{
|
||||
<= 512 => App.Loc["QualityVeryLow"],
|
||||
<= 1024 => App.Loc["QualityLow"],
|
||||
<= 2048 => App.Loc["QualityModerate"],
|
||||
<= 4096 => App.Loc["QualityHigh"],
|
||||
_ => App.Loc["QualityVeryHigh"]
|
||||
};
|
||||
|
||||
public static string ShadowRangeWord(int metres) => metres switch
|
||||
{
|
||||
<= 100 => App.Loc["RangeLow"],
|
||||
<= 150 => App.Loc["RangeModerate"],
|
||||
<= 250 => App.Loc["RangeHigh"],
|
||||
_ => App.Loc["RangeVeryHigh"]
|
||||
};
|
||||
|
||||
public static string CabShadowRangeWord(int metres) => metres switch
|
||||
{
|
||||
<= 10 => App.Loc["RangeVeryLow"],
|
||||
<= 20 => App.Loc["RangeLow"],
|
||||
<= 30 => App.Loc["RangeStandard"],
|
||||
<= 50 => App.Loc["RangeHigh"],
|
||||
_ => App.Loc["RangeVeryHigh"]
|
||||
};
|
||||
|
||||
/// <summary>A rate below one a second reads better as the time between updates.</summary>
|
||||
public static string ReflectionsInterval(double perSecond)
|
||||
{
|
||||
@@ -82,72 +43,4 @@ internal static class SettingTexts
|
||||
? string.Format(App.Loc["EveryMinutes"], (seconds / 60).ToString("0.#", CultureInfo.CurrentCulture))
|
||||
: string.Format(App.Loc["EverySeconds"], seconds.ToString("0.#", CultureInfo.CurrentCulture));
|
||||
}
|
||||
|
||||
/// <summary>What a level sets, in the words and the units of the rows it sets.</summary>
|
||||
public static string PresetSummary(GraphicsPreset p)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
void Add(string label, string value) => lines.Add(App.Loc[label] + ": " + value);
|
||||
string YesNo(bool on) => App.Loc[on ? "Yes" : "No"];
|
||||
string Whole(double value) => value.ToString("0.#", CultureInfo.CurrentCulture);
|
||||
|
||||
Add("MaxTexResolution", p.TextureSize + " px");
|
||||
Add("MaxTexCabResolution", p.CabTextureSize + " px");
|
||||
Add("TexFilteringQuality", Anisotropy(p.Anisotropy));
|
||||
Add("AntiAliasing", AntiAliasing(p.AntiAliasing));
|
||||
Add("DynamicLights", p.DynamicLights.ToString(CultureInfo.CurrentCulture));
|
||||
Add("SmokeParticlesMultiplier", Fidelity(p.SmokeFidelity));
|
||||
Add("RenderShadows", YesNo(p.Shadows));
|
||||
if (p.Shadows)
|
||||
{
|
||||
Add("ShadowsResolution", p.ShadowMap + " px");
|
||||
Add("ShaderRange", SimulatorSettings.ShadowReach(p.ShadowRange, p.ShadowMap, legacyRenderer: false) + " m");
|
||||
Add("ShadowDisplay", App.Loc[p.ShadowRank switch { 1 => "CSROnlyImportant", 2 => "CSRLimited", _ => "CSRAll" }]);
|
||||
}
|
||||
Add("ReflectionsCubeMap", YesNo(p.EnvMap));
|
||||
if (p.EnvMap)
|
||||
{
|
||||
Add("ReflectionsDetails", App.Loc[p.ReflectionsFidelity switch { 0 => "RDTerrain", 1 => "RDTerrainModels", _ => "RDTerrainModelsVehicles" }]);
|
||||
Add("ReflectionsFramerate", ReflectionsInterval(p.ReflectionsRate));
|
||||
}
|
||||
Add("AdditionalShadersEffects", YesNo(p.ExtraEffects));
|
||||
Add("TrackCurvesQuality", Fidelity(p.SplineFidelity));
|
||||
Add("Ini.basedrawrange", Whole(p.DrawRange) + " m");
|
||||
Add("Ini.heightbase", "×" + p.DistanceFactor.ToString("0.##", CultureInfo.CurrentCulture));
|
||||
Add("BufforResolution", p.BufferScale + "%");
|
||||
Add("Ini." + GraphicsPreset.SleeperKey, Whole(p.SleeperDistance) + " m");
|
||||
Add("RenderRange", "×" + Whole(p.DrawRangeFactor));
|
||||
Add("Ini." + GraphicsPreset.ReflectedInstancesKey, Whole(p.ReflectedInstances) + " m");
|
||||
Add("Ini." + GraphicsPreset.ReflectedVehiclesKey, Whole(p.ReflectedVehicles) + " m");
|
||||
|
||||
var renderer = p.NewRenderer;
|
||||
Add("LightShadows", Level(renderer.LampShadows));
|
||||
Add("ContactShadows", Level(renderer.ContactShadows));
|
||||
Add("AmbientOcclusion", renderer.Occlusion switch { 1 => "SSAO", 2 => "GTAO", _ => App.Loc["LevelOff"] });
|
||||
Add("CabProbe", Level(renderer.CabProbe));
|
||||
Add("Ssr", Level(renderer.ScreenReflections));
|
||||
Add("RayTracing", YesNo(renderer.RayTracing));
|
||||
Add("VolumetricFog", renderer.VolumetricFog ? Level(renderer.FogQuality) : App.Loc["No"]);
|
||||
Add("Clouds", Level(renderer.Clouds));
|
||||
Add("Grass", renderer.Grass ? renderer.GrassDistance + " m" : App.Loc["No"]);
|
||||
Add("Bloom", YesNo(renderer.Bloom));
|
||||
|
||||
if (p.Extras is { } extras)
|
||||
{
|
||||
Add("MotionBlur", YesNo(extras.MotionBlur));
|
||||
Add("ChromaticAberration", YesNo(extras.ChromaticAberration));
|
||||
Add("SmokeDisplay", YesNo(extras.Smoke));
|
||||
Add("PyScreenPriority", App.Loc[extras.PythonUpdateMs <= 200 ? "PyPriorityNormal" : "PyPriorityLowest"]);
|
||||
}
|
||||
if (p.Top is { } top)
|
||||
{
|
||||
lines.Insert(0, App.Loc["PresetUltraNote"]);
|
||||
Add("ShadowAngleLimit", TwoDecimals(top.ShadowAngleLimit));
|
||||
Add("Ini." + GraphicsTop.TargetFpsKey, YesNo(top.TargetFps > 0));
|
||||
Add("Ini." + GraphicsTop.TextureReleaseKey, YesNo(top.TextureRelease > 0));
|
||||
Add("CompressTextures", YesNo(top.CompressTextures));
|
||||
Add("IgnoreIrrelevantTrains", YesNo(top.SkipDecor));
|
||||
}
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,17 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Domain.Settings;
|
||||
using StarterNG.Infrastructure;
|
||||
|
||||
namespace StarterNG.Views;
|
||||
|
||||
// What the graphics and effects categories add to the screen: the controls of the settings the
|
||||
// new renderers read, the dependencies between them (what the simulator only does on Vulkan,
|
||||
// with DLSS, ...), and the import and export of eu07.ini.
|
||||
// What the graphics and effects categories add to the screen: the renderer and the
|
||||
// anti-aliasing, and the import and export of eu07.ini.
|
||||
public partial class Settings
|
||||
{
|
||||
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
|
||||
@@ -24,264 +23,113 @@ public partial class Settings
|
||||
new("*") { Patterns = new[] { "*" } }
|
||||
};
|
||||
|
||||
/// <summary>Set while the dependencies are brought in line, so the changes they make do not recurse.</summary>
|
||||
private bool _updatingGraphics;
|
||||
|
||||
/// <summary>
|
||||
/// What only Vulkan has, as it was when OpenGL got chosen, so that going back to
|
||||
/// Vulkan brings it back instead of leaving it switched off.
|
||||
/// </summary>
|
||||
private (AntiAliasingMode AntiAliasing, int FrameGeneration, int Reflex, bool RayTracing)? _vulkanChoices;
|
||||
|
||||
private string? _dlssProbedFor;
|
||||
private (bool Dlss, bool FrameGeneration) _dlssProbe;
|
||||
|
||||
private static bool DlssPlatform => AppServices.Current.SettingsStore.DlssPlatform;
|
||||
|
||||
private void InitGraphics()
|
||||
{
|
||||
// The notes are worked out here, not bound, so they follow a change of language by hand.
|
||||
App.Loc.LanguageChanged += UpdateGraphicsState;
|
||||
SelectExeCb.SelectionChanged += (_, _) => UpdateGraphicsState();
|
||||
}
|
||||
|
||||
private void ShowGraphics(SimulatorSettings s)
|
||||
{
|
||||
RenderEngineCb.SelectedIndex = s.RenderEngine;
|
||||
VulkanDeviceTb.Text = s.VulkanDevice;
|
||||
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
|
||||
SelectTag(DlssPresetCb, s.DlssPreset);
|
||||
SelectTag(FrameGenerationCb, s.FrameGeneration.ToString(Invariant));
|
||||
SelectTag(ReflexCb, s.Reflex.ToString(Invariant));
|
||||
|
||||
ShadowSdsmCb.IsChecked = s.ShadowSdsm;
|
||||
LightsClusteredCb.IsChecked = s.LightsClustered;
|
||||
SelectTag(LightShadowsCb, s.LightShadows.ToString(Invariant));
|
||||
SelectTag(ContactShadowsCb, s.ContactShadows.ToString(Invariant));
|
||||
SelectTag(AmbientOcclusionCb, s.AmbientOcclusion.ToString(Invariant));
|
||||
SelectOrAddTag(AoQualityCb, $"{s.AoSlices} {s.AoSteps}", $"{s.AoSlices} / {s.AoSteps}");
|
||||
AoLightingCb.IsChecked = s.AoLighting;
|
||||
SelectTag(CabProbeCb, s.CabProbe.ToString(Invariant));
|
||||
CabProbeIntervalNud.Value = s.CabProbeInterval;
|
||||
CabProbeBounceSlider.Value = s.CabProbeBounce;
|
||||
CabProbeReflectionsCb.IsChecked = s.CabProbeReflections;
|
||||
|
||||
SelectTag(SsrCb, s.Ssr.ToString(Invariant));
|
||||
RayTracingCb.IsChecked = s.RayTracing;
|
||||
RayTracingRangeSlider.Value = s.RayTracingRange;
|
||||
|
||||
VolumetricFogCb.IsChecked = s.VolumetricFog;
|
||||
SelectTag(FogQualityCb, s.FogQuality.ToString(Invariant));
|
||||
SelectTag(CloudsCb, s.Clouds.ToString(Invariant));
|
||||
CloudShadowsCb.IsChecked = s.CloudShadows;
|
||||
|
||||
BloomCb.IsChecked = s.Bloom;
|
||||
AutoExposureCb.IsChecked = s.AutoExposure;
|
||||
|
||||
GrassCb.IsChecked = s.Grass;
|
||||
GrassDistanceSlider.Value = s.GrassDistance;
|
||||
GrassDensitySlider.Value = s.GrassDensity;
|
||||
string particles = s.PrecipitationParticles.ToString(Invariant);
|
||||
SelectOrAddTag(PrecipitationCb, particles, particles);
|
||||
_fullscreenAsRead = s.Fullscreen;
|
||||
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
|
||||
ShowMonitor(s.FullscreenMonitor);
|
||||
UpdateDisplayRows();
|
||||
}
|
||||
|
||||
private void CaptureGraphics(SimulatorSettings s)
|
||||
{
|
||||
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
|
||||
s.VulkanDevice = VulkanDeviceTb.Text?.Trim() ?? "";
|
||||
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
|
||||
s.DlssPreset = SelectedTag(DlssPresetCb) ?? "default";
|
||||
s.FrameGeneration = TagInt(FrameGenerationCb, 1);
|
||||
s.Reflex = TagInt(ReflexCb, 0);
|
||||
s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
|
||||
|
||||
s.ShadowSdsm = IsChecked(ShadowSdsmCb);
|
||||
s.LightsClustered = IsChecked(LightsClusteredCb);
|
||||
s.LightShadows = TagInt(LightShadowsCb, 2);
|
||||
s.ContactShadows = TagInt(ContactShadowsCb, 0);
|
||||
s.AmbientOcclusion = TagInt(AmbientOcclusionCb, 2);
|
||||
var ao = (SelectedTag(AoQualityCb) ?? "3 4").Split(' ');
|
||||
s.AoSlices = ao.Length > 0 && int.TryParse(ao[0], NumberStyles.Integer, Invariant, out int slices) ? slices : 3;
|
||||
s.AoSteps = ao.Length > 1 && int.TryParse(ao[1], NumberStyles.Integer, Invariant, out int steps) ? steps : 4;
|
||||
s.AoLighting = IsChecked(AoLightingCb);
|
||||
s.CabProbe = TagInt(CabProbeCb, 2);
|
||||
s.CabProbeInterval = (int)(CabProbeIntervalNud.Value ?? 4);
|
||||
s.CabProbeBounce = CabProbeBounceSlider.Value;
|
||||
s.CabProbeReflections = IsChecked(CabProbeReflectionsCb);
|
||||
|
||||
s.Ssr = TagInt(SsrCb, 2);
|
||||
s.RayTracing = IsChecked(RayTracingCb);
|
||||
s.RayTracingRange = (int)RayTracingRangeSlider.Value;
|
||||
|
||||
s.VolumetricFog = IsChecked(VolumetricFogCb);
|
||||
s.FogQuality = TagInt(FogQualityCb, 2);
|
||||
s.Clouds = TagInt(CloudsCb, 2);
|
||||
s.CloudShadows = IsChecked(CloudShadowsCb);
|
||||
|
||||
s.Bloom = IsChecked(BloomCb);
|
||||
s.AutoExposure = IsChecked(AutoExposureCb);
|
||||
|
||||
s.Grass = IsChecked(GrassCb);
|
||||
s.GrassDistance = (int)GrassDistanceSlider.Value;
|
||||
s.GrassDensity = GrassDensitySlider.Value;
|
||||
s.PrecipitationParticles = TagInt(PrecipitationCb, 65536);
|
||||
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
|
||||
s.FullscreenWindowed = mode == BorderlessMode;
|
||||
// Borderless overrides fullscreen in the simulator, so the file's own word for it stays.
|
||||
s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode;
|
||||
}
|
||||
|
||||
private void OnBackendChanged()
|
||||
// ── How the simulator shows: full screen, borderless or in a window ──────
|
||||
|
||||
private const string FullscreenMode = "fullscreen";
|
||||
private const string BorderlessMode = "borderless";
|
||||
private const string WindowMode = "window";
|
||||
|
||||
/// <summary>fullscreen as the file has it, kept where borderless makes it of no account.</summary>
|
||||
private bool _fullscreenAsRead;
|
||||
|
||||
/// <summary>
|
||||
/// The mode the two keys make (application.cpp): fullscreenwindowed takes the monitor's
|
||||
/// own size and turns full screen on whatever fullscreen says.
|
||||
/// </summary>
|
||||
private static string DisplayModeOf(bool fullscreen, bool windowed) =>
|
||||
windowed ? BorderlessMode : fullscreen ? FullscreenMode : WindowMode;
|
||||
|
||||
/// <summary>A borderless screen takes the monitor's size; a window can't be put on a monitor.</summary>
|
||||
private void UpdateDisplayRows()
|
||||
{
|
||||
if (_loading || _updatingGraphics)
|
||||
return;
|
||||
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
|
||||
Dim(ResolutionRow, mode == BorderlessMode);
|
||||
Dim(MonitorRow, mode == WindowMode);
|
||||
}
|
||||
|
||||
_updatingGraphics = true;
|
||||
try
|
||||
{
|
||||
if (!SettingReach.IsVulkan(SelectedRenderer()))
|
||||
{
|
||||
var s = Trial();
|
||||
_vulkanChoices ??= (s.AntiAliasing, s.FrameGeneration, s.Reflex, s.RayTracing);
|
||||
if (GraphicsRules.IsDlss(s.AntiAliasing))
|
||||
SelectTag(AntiAliasingCb, "taa");
|
||||
FrameGenerationCb.SelectedIndex = 0;
|
||||
ReflexCb.SelectedIndex = 0;
|
||||
RayTracingCb.IsChecked = false;
|
||||
}
|
||||
else if (_vulkanChoices is { } kept)
|
||||
{
|
||||
if (GraphicsRules.IsDlss(kept.AntiAliasing) && DlssPlatform && SelectedTag(AntiAliasingCb) == "taa")
|
||||
SelectTag(AntiAliasingCb, AntiAliasingTag(kept.AntiAliasing));
|
||||
SelectTag(FrameGenerationCb, kept.FrameGeneration.ToString(Invariant));
|
||||
SelectTag(ReflexCb, kept.Reflex.ToString(Invariant));
|
||||
RayTracingCb.IsChecked = kept.RayTracing;
|
||||
_vulkanChoices = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_updatingGraphics = false;
|
||||
}
|
||||
/// <summary>The whole row greyed out, its label and description too, as a disabled check box is.</summary>
|
||||
private static void Dim(Control row, bool off)
|
||||
{
|
||||
row.IsEnabled = !off;
|
||||
row.Opacity = off ? 0.45 : 1;
|
||||
}
|
||||
|
||||
UpdateGraphicsState();
|
||||
private ComboBoxItem? _primaryMonitorItem;
|
||||
|
||||
private IReadOnlyList<DisplayMonitor>? _monitors;
|
||||
|
||||
/// <summary>The monitors attached, read once.</summary>
|
||||
private IReadOnlyList<DisplayMonitor> MonitorList => _monitors ??= Monitors.List(AppServices.Current.Environment);
|
||||
|
||||
/// <summary>
|
||||
/// The monitor the simulator will show on (application.cpp): a full screen, borderless or
|
||||
/// not, goes to the one chosen, or the primary one when that is not connected; a window
|
||||
/// opens where the system puts it, as a rule the primary one. Null where no monitor could be read.
|
||||
/// </summary>
|
||||
private DisplayMonitor? SimulatorMonitor()
|
||||
{
|
||||
string? chosen = SelectedTag(DisplayModeCb) == WindowMode ? null : SelectedTag(MonitorCb);
|
||||
DisplayMonitor? primary = null;
|
||||
foreach (var m in MonitorList)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(chosen) && m.Id == chosen)
|
||||
return m;
|
||||
if (m.Primary)
|
||||
primary ??= m;
|
||||
}
|
||||
return primary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings the graphics controls in line with one another the way the simulator
|
||||
/// treats them, and says why something is off.
|
||||
/// The monitors found, listed once, with the primary one first; a monitor the file names
|
||||
/// that is not connected now stays on the list under its own name.
|
||||
/// </summary>
|
||||
private void UpdateGraphicsState()
|
||||
private void ShowMonitor(string id)
|
||||
{
|
||||
if (!_built || _loading || _updatingGraphics)
|
||||
return;
|
||||
|
||||
_updatingGraphics = true;
|
||||
try
|
||||
if (_primaryMonitorItem is null)
|
||||
{
|
||||
var s = Trial();
|
||||
bool vulkan = GraphicsRules.IsVulkan(s);
|
||||
bool dlssAllowed = GraphicsRules.DlssAllowed(s, DlssPlatform);
|
||||
|
||||
foreach (var item in AntiAliasingCb.Items.OfType<ComboBoxItem>())
|
||||
if (item.Tag is "dlss" or "dlaa")
|
||||
item.IsEnabled = dlssAllowed;
|
||||
if (GraphicsRules.IsDlss(s.AntiAliasing) && !dlssAllowed)
|
||||
SelectTag(AntiAliasingCb, "taa");
|
||||
|
||||
s = Trial();
|
||||
bool dlss = GraphicsRules.DlssActive(s, DlssPlatform);
|
||||
DlssPresetRow.IsEnabled = dlss;
|
||||
FrameGenerationRow.IsEnabled = dlss;
|
||||
if (!dlss && FrameGenerationCb.SelectedIndex > 0)
|
||||
FrameGenerationCb.SelectedIndex = 0;
|
||||
ReflexRow.IsEnabled = vulkan;
|
||||
if (!vulkan && ReflexCb.SelectedIndex > 0)
|
||||
ReflexCb.SelectedIndex = 0;
|
||||
VulkanDeviceRow.IsEnabled = vulkan;
|
||||
RayTracingRow.IsEnabled = vulkan;
|
||||
if (!vulkan)
|
||||
RayTracingCb.IsChecked = false;
|
||||
|
||||
s = Trial();
|
||||
BufferScaleRow.IsEnabled = GraphicsRules.BufferScaleUsed(s, DlssPlatform);
|
||||
RayTracingRangeRow.IsEnabled = vulkan && s.RayTracing;
|
||||
DynamicLightsRow.IsEnabled = GraphicsRules.DynamicLightsUsed(s);
|
||||
AoQualityRow.IsEnabled = s.AmbientOcclusion > 0;
|
||||
AoLightingRow.IsEnabled = GraphicsRules.AoLightingUsed(s);
|
||||
bool probe = GraphicsRules.CabProbeUsed(s);
|
||||
CabProbeIntervalRow.IsEnabled = probe;
|
||||
CabProbeReflectionsRow.IsEnabled = probe;
|
||||
CabProbeBounceRow.IsEnabled = GraphicsRules.CabProbeLights(s);
|
||||
FogQualityRow.IsEnabled = s.VolumetricFog;
|
||||
CloudShadowsRow.IsEnabled = s.Clouds > 0;
|
||||
GrassDistanceRow.IsEnabled = s.Grass;
|
||||
GrassDensityRow.IsEnabled = s.Grass;
|
||||
|
||||
DlssPresetInfo.Text = App.Loc[(SelectedTag(DlssPresetCb) ?? "default") switch
|
||||
_primaryMonitorItem = new ComboBoxItem { Tag = string.Empty, Content = App.Loc["MonitorPrimary"] };
|
||||
App.Loc.LanguageChanged += () => _primaryMonitorItem.Content = App.Loc["MonitorPrimary"];
|
||||
MonitorCb.Items.Add(_primaryMonitorItem);
|
||||
var monitors = MonitorList;
|
||||
for (int i = 0; i < monitors.Count; i++)
|
||||
{
|
||||
"k" => "DlssPresetInfoK",
|
||||
"j" => "DlssPresetInfoJ",
|
||||
"m" => "DlssPresetInfoM",
|
||||
"l" => "DlssPresetInfoL",
|
||||
_ => "DlssPresetInfoDefault"
|
||||
}];
|
||||
SetNote(RenderEngineNote, App.Loc[vulkan ? "REVulkanNote" : "REOpenGLNote"]);
|
||||
SetNote(AntiAliasingNote, AntiAliasingRemark(s, dlss));
|
||||
SetNote(FrameGenerationNote, FrameGenerationRemark(s, dlss));
|
||||
SetNote(ReflexNote, GraphicsRules.ReflexForced(s, DlssPlatform) ? App.Loc["ReflexForcedNote"] : "");
|
||||
SetNote(AoLightingNote, AoLightingRemark(s));
|
||||
SetNote(CabProbeNote, GraphicsRules.CabProbeUsed(s) && !GraphicsRules.CabProbeLights(s) ? App.Loc["CabProbeReflectionsOnlyNote"] : "");
|
||||
SetNote(SkipPipelineNote, GraphicsRules.TemporalWithoutPipeline(s) ? App.Loc["TemporalNeedsPipelineNote"] : "");
|
||||
var m = monitors[i];
|
||||
MonitorCb.Items.Add(new ComboBoxItem
|
||||
{
|
||||
Tag = m.Id,
|
||||
Content = $"{i + 1}. {m.Name} – {m.Width}×{m.Height}"
|
||||
});
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_updatingGraphics = false;
|
||||
}
|
||||
}
|
||||
|
||||
private string AntiAliasingRemark(SimulatorSettings s, bool dlss)
|
||||
{
|
||||
if (!DlssPlatform && GraphicsRules.IsVulkan(s))
|
||||
return App.Loc["DlssNoPlatformNote"];
|
||||
if (GraphicsRules.TemporalWithoutPipeline(s))
|
||||
return App.Loc["TemporalNeedsPipelineNote"];
|
||||
if (dlss && !DlssLibraries(s).Dlss)
|
||||
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: false));
|
||||
return "";
|
||||
if (IndexOfTag(MonitorCb, id) < 0)
|
||||
MonitorCb.Items.Add(new ComboBoxItem { Tag = id, Content = id });
|
||||
SelectTag(MonitorCb, id);
|
||||
}
|
||||
|
||||
private static string AoLightingRemark(SimulatorSettings s)
|
||||
{
|
||||
if (!GraphicsRules.AoLightingUsed(s) || !s.AoLighting)
|
||||
return "";
|
||||
if (s.SkipPipeline)
|
||||
return App.Loc["AoNeedsPipelineNote"];
|
||||
return GraphicsRules.AoLightingAddsDepthPrepass(s) ? App.Loc["AoLightingPrepassNote"] : "";
|
||||
}
|
||||
|
||||
private string FrameGenerationRemark(SimulatorSettings s, bool dlss)
|
||||
{
|
||||
if (!dlss)
|
||||
return GraphicsRules.IsVulkan(s) ? App.Loc["FrameGenerationNeedsDlssNote"] : "";
|
||||
if (s.FrameGeneration > 1 && !DlssLibraries(s).FrameGeneration)
|
||||
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: true));
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>Looked up once per simulator picked: the search for it reads the installation's directory.</summary>
|
||||
private (bool Dlss, bool FrameGeneration) DlssLibraries(SimulatorSettings s)
|
||||
{
|
||||
string key = s.SelectExeAutomatically ? "\u0001auto" : s.ExecutablePath;
|
||||
if (_dlssProbedFor != key)
|
||||
{
|
||||
var executables = AppServices.Current.Executables;
|
||||
_dlssProbe = executables.DlssLibraries(executables.Resolve(s, out _));
|
||||
_dlssProbedFor = key;
|
||||
}
|
||||
return _dlssProbe;
|
||||
}
|
||||
|
||||
private static string DlssLibraryName(bool frameGeneration) =>
|
||||
AppServices.Current.Environment.IsWindows
|
||||
? (frameGeneration ? "nvngx_dlssg.dll" : "nvngx_dlss.dll")
|
||||
: (frameGeneration ? "libnvidia-ngx-dlssg.so" : "libnvidia-ngx-dlss.so");
|
||||
|
||||
private async void ImportIniButton_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
@@ -303,7 +151,6 @@ public partial class Settings
|
||||
return;
|
||||
}
|
||||
|
||||
_vulkanChoices = null;
|
||||
ApplyToUi();
|
||||
// What came from the other file is a choice to save, not a value the screen could not show.
|
||||
_shownUnlikeSettings = new Dictionary<string, ShownValue>();
|
||||
@@ -328,9 +175,8 @@ public partial class Settings
|
||||
return;
|
||||
|
||||
// The edits on screen go into the export as they would into a save, but the
|
||||
// user's own eu07.ini is not written.
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
if (!AppServices.Current.SettingsStore.ExportTo(path))
|
||||
// user's own eu07.ini is not written, nor the settings held: the edits stay the page's, not saved.
|
||||
if (!AppServices.Current.SettingsStore.ExportTo(path, Trial()))
|
||||
{
|
||||
await MessageBox.Show(owner, string.Format(App.Loc["ExportIniFailed"], path), App.Loc["ExportIni"],
|
||||
MessageBoxButtons.Ok);
|
||||
@@ -338,7 +184,6 @@ public partial class Settings
|
||||
}
|
||||
|
||||
SaveStatus.Text = string.Format(App.Loc["ExportIniDone"], Path.GetFileName(path));
|
||||
ToolTip.SetTip(SaveStatus, path);
|
||||
}
|
||||
|
||||
private static void SetNote(TextBlock note, string text)
|
||||
@@ -376,9 +221,6 @@ public partial class Settings
|
||||
AntiAliasingMode.Msaa2 => "msaax2",
|
||||
AntiAliasingMode.Msaa4 => "msaax4",
|
||||
AntiAliasingMode.Msaa8 => "msaax8",
|
||||
AntiAliasingMode.Taa => "taa",
|
||||
AntiAliasingMode.Dlss => "dlss",
|
||||
AntiAliasingMode.Dlaa => "dlaa",
|
||||
_ => "off"
|
||||
};
|
||||
|
||||
@@ -387,9 +229,6 @@ public partial class Settings
|
||||
"msaax2" => AntiAliasingMode.Msaa2,
|
||||
"msaax4" => AntiAliasingMode.Msaa4,
|
||||
"msaax8" => AntiAliasingMode.Msaa8,
|
||||
"taa" => AntiAliasingMode.Taa,
|
||||
"dlss" => AntiAliasingMode.Dlss,
|
||||
"dlaa" => AntiAliasingMode.Dlaa,
|
||||
_ => AntiAliasingMode.Off
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
<TextBlock x:Name="SaveStatus" ctl:Announcer.Changes="True" VerticalAlignment="Center" Opacity="0.8" Text="" />
|
||||
<Button x:Name="ChangesButton" Classes="Flat" Click="ChangesButton_OnClick"
|
||||
Content="{Binding [IniChangesButton], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="DefaultsButton" Classes="Flat" Click="DefaultsButton_OnClick"
|
||||
Content="{Binding [RestoreDefaults], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="ResetButton" Classes="Flat" Click="ResetButton_OnClick"
|
||||
Content="{Binding [Reset], Source={x:Static starterNg:App.Loc}}" />
|
||||
<Button x:Name="SaveButton" Classes="Flat" Click="SaveButton_OnClick"
|
||||
@@ -44,7 +46,7 @@
|
||||
PlaceholderText="{Binding [Search], Source={x:Static starterNg:App.Loc}}"
|
||||
TextChanged="SettingsSearch_OnTextChanged" />
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
|
||||
<StackPanel x:Name="ProfilePanel" DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
|
||||
<TextBlock Classes="FieldLabel"
|
||||
Text="{Binding [SettingsProfile], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch"
|
||||
@@ -67,6 +69,10 @@
|
||||
HorizontalContentAlignment="Center"
|
||||
Content="{Binding [ExportIni], Source={x:Static starterNg:App.Loc}}"
|
||||
Click="ExportIniButton_OnClick" />
|
||||
<!-- Kept out of the way on purpose: turning it on asks first, at length. -->
|
||||
<Button x:Name="AdvancedModeBtn" Classes="Flat" HorizontalAlignment="Stretch"
|
||||
HorizontalContentAlignment="Center" Margin="0,14,0,0" FontSize="11" Opacity="0.7"
|
||||
Click="AdvancedModeBtn_OnClick" />
|
||||
</StackPanel>
|
||||
|
||||
<ListBox x:Name="CategoryList" AutomationProperties.LandmarkType="Navigation" AutomationProperties.Name="{Binding [SettingsCategories], Source={x:Static starterNg:App.Loc}}" Classes="SettingsNav" SelectedIndex="0"
|
||||
@@ -131,9 +137,6 @@
|
||||
<ComboBox x:Name="ChangeLanguageCb"
|
||||
SelectionChanged="LanguageComboBox_OnSelectionChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fullscreen">
|
||||
<CheckBox x:Name="FullscreenCb" Content="{Binding [Fullscreen], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="inactivepause">
|
||||
<CheckBox x:Name="PauseInactiveCb" Content="{Binding [PauseSimInactive], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -142,7 +145,7 @@
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="mousescale" x:Name="CursorSensitivityRow"
|
||||
Label="{Binding [CursorSensitivity], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
|
||||
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="3" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="3"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
@@ -208,17 +211,10 @@
|
||||
<ComboBoxItem Content="{Binding [REFull], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REOld], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [RESimp], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REExperimental], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Content="{Binding [REVulkan], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="RenderEngineNote" Classes="SettingNote" IsVisible="False" />
|
||||
<!-- Amber like the UART warnings: this one stops the simulator. -->
|
||||
<TextBlock x:Name="RenderEngineWarning" IsVisible="False" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource CarbonAccentBright}"
|
||||
Text="{Binding [REExperimentalWarning], Source={x:Static starterNg:App.Loc}}" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GpuRow" ConfigKey="starter.gpu" Label="{Binding [GpuChoice], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingRow Advanced="True" x:Name="GpuRow" ConfigKey="starter.gpu" Label="{Binding [GpuChoice], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="GpuCb" Classes="Localized" SelectedIndex="0"
|
||||
SelectionChanged="GpuCb_OnSelectionChanged">
|
||||
<ComboBoxItem Content="{Binding [GpuDiscrete], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -231,10 +227,9 @@
|
||||
<ctl:SettingRow ConfigKey="gfx.extraeffects">
|
||||
<CheckBox x:Name="AdditionalShadersCb" Content="{Binding [AdditionalShadersEffects], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.skippipeline" Description="{Binding [SkipPipelineDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingRow ConfigKey="gfx.skippipeline" Advanced="True" Description="{Binding [SkipPipelineDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<CheckBox x:Name="SkipPipelineCb" Content="{Binding [SkipPipeline], Source={x:Static starterNg:App.Loc}}" />
|
||||
<TextBlock x:Name="SkipPipelineNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="usevbo" Description="{Binding [RenderVBODesc], Source={x:Static starterNg:App.Loc}}">
|
||||
@@ -249,17 +244,27 @@
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [GfxColImage], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="width, height" Label="{Binding [Resolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<!-- fullscreen and fullscreenwindowed as the simulator reads them together; see DisplayModeOf. -->
|
||||
<ctl:SettingRow ConfigKey="fullscreen, fullscreenwindowed" Label="{Binding [DisplayMode], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [DisplayModeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="DisplayModeCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="fullscreen" Content="{Binding [DisplayModeFullscreen], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="borderless" Content="{Binding [DisplayModeBorderless], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="window" Content="{Binding [DisplayModeWindow], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="MonitorRow" ConfigKey="fullscreenmonitor" Label="{Binding [FullscreenMonitor], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FullscreenMonitorDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="MonitorCb" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="ResolutionRow" ConfigKey="width, height" Label="{Binding [Resolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="ResolutionCb" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fullscreenwindowed">
|
||||
<CheckBox x:Name="FullscreenWindowedCb" Content="{Binding [FullscreenWindowed], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="BufferScaleRow" ConfigKey="gfx.buffer.percent, starter.bufferscale"
|
||||
<ctl:SettingRow x:Name="BufferScaleRow" Advanced="True" ConfigKey="gfx.framebuffer.width, gfx.framebuffer.height"
|
||||
Label="{Binding [BufforResolution], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [BufforResolutionDesc], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #bufferScale.Value, StringFormat='{}{0:0}%'}">
|
||||
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="100" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="100" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="fieldofview" Label="{Binding [FieldOfView], Source={x:Static starterNg:App.Loc}}"
|
||||
@@ -268,7 +273,7 @@
|
||||
<ctl:ReadableSlider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
|
||||
IsSnapToTickEnabled="True" Value="45" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.antialiasing, multisampling"
|
||||
<ctl:SettingRow ConfigKey="multisampling"
|
||||
Label="{Binding [AntiAliasing], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [AntiAliasingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
@@ -277,18 +282,9 @@
|
||||
<ComboBoxItem Tag="msaax2" Content="MSAA x2" />
|
||||
<ComboBoxItem Tag="msaax4" Content="MSAA x4" />
|
||||
<ComboBoxItem Tag="msaax8" Content="MSAA x8" />
|
||||
<ComboBoxItem Tag="taa" Content="{Binding [AaTaa], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="dlss" Content="{Binding [AaDlss], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="dlaa" Content="{Binding [AaDlaa], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="AntiAliasingNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [GfxColSmoothness], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="vsync" Description="{Binding [VSyncDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="VSyncCb" Content="{Binding [VSync], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -296,10 +292,13 @@
|
||||
Label="{Binding [FpsLimit], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FpsLimitDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="4">
|
||||
<!-- Moves through no limit and Steps.FrameRateLimits; see SliderSteps. -->
|
||||
<!-- Moves through no limit and SliderRanges.FrameRateLimits; see SliderSteps. -->
|
||||
<ctl:ReadableSlider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
|
||||
<!-- The screens found, each with a button to match the limit to it. -->
|
||||
<WrapPanel x:Name="MonitorRates" IsVisible="False" />
|
||||
<!-- Shown with VSync on: the limit and VSync together, see UpdateMonitorRates. -->
|
||||
<TextBlock x:Name="FpsVSyncNote" Classes="FieldHint" TextWrapping="Wrap" IsVisible="False"
|
||||
Text="{Binding [FpsVSyncNote], Source={x:Static starterNg:App.Loc}}" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
@@ -331,13 +330,13 @@
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="maxtexturesize" x:Name="TexResolutionRow"
|
||||
Label="{Binding [MaxTexResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="TextureResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="maxcabtexturesize" x:Name="CabTexResolutionRow"
|
||||
Label="{Binding [MaxTexCabResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="12" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="CabTextureResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
@@ -398,7 +397,7 @@
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="shadowtune" x:Name="ShadowResolutionRow"
|
||||
Label="{Binding [ShadowsResolution], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
|
||||
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="10" Maximum="13" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="12"
|
||||
ValueChanged="shaderResolutionSlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
@@ -406,15 +405,15 @@
|
||||
Label="{Binding [ShaderRange], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ShaderRangeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<!-- The simulator's floor follows the map size: see shaderResolutionSlider_OnValueChanged. -->
|
||||
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
|
||||
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="400" TickFrequency="5"
|
||||
IsSnapToTickEnabled="True" Value="150"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadows.cab.range" x:Name="CabShadowRangeRow"
|
||||
Label="{Binding [CabShadowsRange], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabShadowsRangeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:ReadableSlider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
|
||||
IsSnapToTickEnabled="True" Value="30"
|
||||
<!-- Moves through SliderRanges.CabShadowRanges; see SliderSteps. -->
|
||||
<ctl:ReadableSlider Name="cabShaderSourceRange"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadow.angle.min" x:Name="ShadowAngleLimitRow"
|
||||
@@ -422,7 +421,7 @@
|
||||
Description="{Binding [ShadowAngleLimitDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:ReadableSlider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
|
||||
TickFrequency="0.05" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
|
||||
TickFrequency="0.1" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
|
||||
ValueChanged="QualitySlider_OnValueChanged" />
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Classes="FieldHint"
|
||||
@@ -435,11 +434,11 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection x:Name="LightsSection" Header="{Binding [GfxColLights], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Header="{Binding [GfxColLights], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow x:Name="DynamicLightsRow" Description="{Binding [DynamicLightsDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="dynamiclights" Label="{Binding [DynamicLights], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #DynamicLightsSlider.Value, StringFormat='{}{0:0}'}">
|
||||
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
|
||||
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="1" Maximum="7" TickFrequency="1"
|
||||
IsSnapToTickEnabled="True" Value="7" />
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
@@ -484,7 +483,7 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection x:Name="NatureSection" Header="{Binding [GfxColNature], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Header="{Binding [GfxColNature], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="gfx.smoke" Margin="0,0,0,4">
|
||||
<CheckBox x:Name="SmokeDisplayCb" Content="{Binding [SmokeDisplay], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -554,6 +553,12 @@
|
||||
<ctl:SettingRow ConfigKey="livetraction" Description="{Binding [PowerOverheadLineOnlyDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="OverheadOnlyCb" Content="{Binding [PowerOverheadLineOnly], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveBlackBoxDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="blackbox">
|
||||
<CheckBox x:Name="BlackBoxCb" Content="{Binding [SaveBlackBox], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveTrainTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog.trains">
|
||||
<CheckBox x:Name="TrainTapesCb" Content="{Binding [SaveTrainTapes], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow Description="{Binding [SaveSpeedometerTapesDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="physicslog">
|
||||
<CheckBox x:Name="SpeedometerTapesCb" Content="{Binding [SaveSpeedometerTapes], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
@@ -671,7 +676,7 @@
|
||||
<StackPanel Tag="advanced" IsVisible="False">
|
||||
<TextBlock Classes="CategoryCaption" IsVisible="False"
|
||||
Text="{Binding [Advanced], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ctl:SettingsSection Header="{Binding [AdvancedResources], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Advanced="True" Header="{Binding [AdvancedResources], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow ConfigKey="compresstex" Description="{Binding [CompressTexturesDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="CompressTexCb" Content="{Binding [CompressTextures], Source={x:Static starterNg:App.Loc}}" />
|
||||
@@ -709,7 +714,7 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<ctl:SettingsSection Header="{Binding [AdvancedLogTools], Source={x:Static starterNg:App.Loc}}">
|
||||
<ctl:SettingsSection Advanced="True" Header="{Binding [AdvancedLogTools], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<ctl:SettingRow Description="{Binding [OpenLogToolsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<Button x:Name="OpenLogToolsButton" Classes="Flat" Cursor="Hand"
|
||||
@@ -720,198 +725,6 @@
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
|
||||
<!-- What only the new simulator reads; an older one passes over these keys. -->
|
||||
<ctl:SettingsSection Header="{Binding [GfxColNewRenderer], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel>
|
||||
<TextBlock Classes="SettingNote" Margin="0,0,0,11"
|
||||
Text="{Binding [GfxNewRendererNote], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ctl:SettingRow x:Name="VulkanDeviceRow" ConfigKey="gfx.vulkan.device"
|
||||
Label="{Binding [VulkanDevice], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [VulkanDeviceDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<TextBox x:Name="VulkanDeviceTb" PlaceholderText="{Binding [VulkanDeviceAuto], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="DlssPresetRow" ConfigKey="gfx.dlss.preset"
|
||||
Label="{Binding [DlssPreset], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [DlssPresetDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="DlssPresetCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="default" Content="{Binding [DlssPresetDefault], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="k" Content="{Binding [DlssPresetK], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="j" Content="{Binding [DlssPresetJ], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="m" Content="{Binding [DlssPresetM], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="l" Content="{Binding [DlssPresetL], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="DlssPresetInfo" Classes="FieldHint" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="FrameGenerationRow" ConfigKey="gfx.framegeneration"
|
||||
Label="{Binding [FrameGeneration], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [FrameGenerationDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="FrameGenerationCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="x2" />
|
||||
<ComboBoxItem Tag="3" Content="x3" />
|
||||
<ComboBoxItem Tag="4" Content="x4" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="FrameGenerationNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="ReflexRow" ConfigKey="gfx.reflex"
|
||||
Label="{Binding [Reflex], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ReflexDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="ReflexCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [ReflexOn], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [ReflexBoost], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="ReflexNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="RayTracingRow" ConfigKey="gfx.raytracing" Description="{Binding [RayTracingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="RayTracingCb" Content="{Binding [RayTracing], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="RayTracingRangeRow" ConfigKey="gfx.raytracing.range"
|
||||
Label="{Binding [RayTracingRange], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #RayTracingRangeSlider.Value, StringFormat='{}{0:0} m'}">
|
||||
<ctl:ReadableSlider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.ssr" Label="{Binding [Ssr], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [SsrDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="SsrCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.lights.clustered" Description="{Binding [LightsClusteredDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="LightsClusteredCb" Content="{Binding [LightsClustered], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.lights.shadows" Label="{Binding [LightShadows], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [LightShadowsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="LightShadowsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.contactshadows" Label="{Binding [ContactShadows], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [ContactShadowsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="ContactShadowsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.shadow.sdsm" Description="{Binding [ShadowSdsmDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="ShadowSdsmCb" Content="{Binding [ShadowSdsm], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.ao" Label="{Binding [AmbientOcclusion], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [AmbientOcclusionDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="AmbientOcclusionCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="SSAO" />
|
||||
<ComboBoxItem Tag="2" Content="GTAO" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="AoLightingRow" ConfigKey="gfx.postfx.ao.lighting" Description="{Binding [AoLightingDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<CheckBox x:Name="AoLightingCb" Content="{Binding [AoLighting], Source={x:Static starterNg:App.Loc}}" />
|
||||
<TextBlock x:Name="AoLightingNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="AoQualityRow" ConfigKey="gfx.postfx.ao.quality" Label="{Binding [AmbientOcclusionQuality], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="AoQualityCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="2 3" Content="{Binding [QualityLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3 4" Content="{Binding [QualityNormal], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4 6" Content="{Binding [QualityHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="6 8" Content="{Binding [QualityVeryHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.cabprobe" Label="{Binding [CabProbe], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabProbeDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<StackPanel Spacing="6">
|
||||
<ComboBox x:Name="CabProbeCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
<TextBlock x:Name="CabProbeNote" Classes="SettingNote" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeIntervalRow" ConfigKey="gfx.cabprobe.interval"
|
||||
Label="{Binding [CabProbeInterval], Source={x:Static starterNg:App.Loc}}">
|
||||
<NumericUpDown x:Name="CabProbeIntervalNud" Minimum="1" Maximum="120" Value="4" Increment="1" FormatString="0" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeBounceRow" ConfigKey="gfx.cabprobe.bounce"
|
||||
Label="{Binding [CabProbeBounce], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CabProbeBounceDesc], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #CabProbeBounceSlider.Value, StringFormat='{}{0:0.0}'}">
|
||||
<ctl:ReadableSlider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CabProbeReflectionsRow" ConfigKey="gfx.cabprobe.reflections" Description="{Binding [CabProbeReflectionsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="CabProbeReflectionsCb" Content="{Binding [CabProbeReflections], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.fog" Description="{Binding [VolumetricFogDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="VolumetricFogCb" Content="{Binding [VolumetricFog], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="FogQualityRow" ConfigKey="gfx.fog.quality" Label="{Binding [FogQuality], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="FogQualityCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4" Content="{Binding [LevelUltra], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.clouds" Label="{Binding [Clouds], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [CloudsDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="CloudsCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="0" Content="{Binding [LevelOff], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="1" Content="{Binding [LevelLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="2" Content="{Binding [LevelMedium], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="3" Content="{Binding [LevelHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="4" Content="{Binding [LevelUltra], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="CloudShadowsRow" ConfigKey="gfx.clouds.shadows">
|
||||
<CheckBox x:Name="CloudShadowsCb" Content="{Binding [CloudShadows], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.bloom">
|
||||
<CheckBox x:Name="BloomCb" Content="{Binding [Bloom], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.postfx.autoexposure" Description="{Binding [AutoExposureDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<CheckBox x:Name="AutoExposureCb" Content="{Binding [AutoExposure], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.grass" Margin="0,0,0,4">
|
||||
<CheckBox x:Name="GrassCb" Content="{Binding [Grass], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GrassDistanceRow" ConfigKey="gfx.grass.distance, gfx.grass.fadedistance"
|
||||
Label="{Binding [GrassDistance], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #GrassDistanceSlider.Value, StringFormat='{}{0:0} m'}">
|
||||
<ctl:ReadableSlider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow x:Name="GrassDensityRow" ConfigKey="gfx.grass.density"
|
||||
Label="{Binding [GrassDensity], Source={x:Static starterNg:App.Loc}}"
|
||||
ValueText="{Binding #GrassDensitySlider.Value, StringFormat='{}{0:0.00}'}">
|
||||
<ctl:ReadableSlider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
|
||||
</ctl:SettingRow>
|
||||
<ctl:SettingRow ConfigKey="gfx.precipitation.particles" Label="{Binding [Precipitation], Source={x:Static starterNg:App.Loc}}"
|
||||
Description="{Binding [PrecipitationDesc], Source={x:Static starterNg:App.Loc}}">
|
||||
<ComboBox x:Name="PrecipitationCb" Classes="Localized" SelectedIndex="0">
|
||||
<ComboBoxItem Tag="16384" Content="{Binding [QualityVeryLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="32768" Content="{Binding [QualityLow], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="65536" Content="{Binding [QualityNormal], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="131072" Content="{Binding [QualityHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
<ComboBoxItem Tag="262144" Content="{Binding [QualityVeryHigh], Source={x:Static starterNg:App.Loc}}" />
|
||||
</ComboBox>
|
||||
</ctl:SettingRow>
|
||||
</StackPanel>
|
||||
</ctl:SettingsSection>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
|
||||
@@ -39,6 +39,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private readonly SliderSteps _anisotropy;
|
||||
|
||||
private readonly SliderSteps _drawRangeFactor;
|
||||
private readonly SliderSteps _cabShadows;
|
||||
|
||||
// False while the layout loads: the handlers it names fire as it sets their controls'
|
||||
// values, before the fields of the controls are there, and do nothing until this is set.
|
||||
@@ -50,6 +51,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
public event Action? ThumbnailSizeChanged;
|
||||
|
||||
/// <summary>The standard or the advanced mode was chosen; the scenario screen follows it.</summary>
|
||||
public static event Action? AdvancedModeChanged;
|
||||
|
||||
/// <summary>Thumbnail size the other tabs were last drawn at.</summary>
|
||||
private bool _drawnThumbs = AppServices.Current.Settings.LargeThumbnails;
|
||||
|
||||
@@ -57,14 +61,14 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_fpsLimit = new SliderSteps(FpsLimitSlider, Steps.FrameRateLimits);
|
||||
_reflections = new SliderSteps(reflectionsFramerate, Steps.ReflectionUpdates);
|
||||
_fpsLimit = new SliderSteps(FpsLimitSlider, SliderRanges.FrameRateLimits);
|
||||
_reflections = new SliderSteps(reflectionsFramerate, SliderRanges.ReflectionUpdates);
|
||||
_anisotropy = new SliderSteps(TexFilteringSlider, Steps.Anisotropy);
|
||||
_drawRangeFactor = new SliderSteps(RenderRangeSlider, Steps.DrawRangeFactors);
|
||||
_drawRangeFactor = new SliderSteps(RenderRangeSlider, SliderRanges.DrawRangeFactors);
|
||||
_cabShadows = new SliderSteps(cabShaderSourceRange, SliderRanges.CabShadowRanges);
|
||||
_built = true;
|
||||
|
||||
SettingsPathText.Text = AppServices.Current.SettingsStore.LoadedFrom;
|
||||
ToolTip.SetTip(SettingsPathText, AppServices.Current.SettingsStore.LoadedFrom);
|
||||
|
||||
this.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
@@ -104,17 +108,38 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
App.Loc.LanguageChanged += _keyRows.UpdateTexts;
|
||||
|
||||
FeedbackCb.SelectionChanged += FeedbackCb_OnSelectionChanged;
|
||||
SelectExeCb.SelectionChanged += (_, _) => UpdateIdleNotes();
|
||||
FullscreenWindowedCb.IsCheckedChanged += (_, _) => UpdateIdleNotes();
|
||||
App.Loc.LanguageChanged += UpdateIdleNotes;
|
||||
App.Loc.LanguageChanged += UpdateGpuNote;
|
||||
// targetfps decides whether the draw range factor does anything.
|
||||
_keyRows.Moved += key =>
|
||||
// What decides whether the simulator starts and draws at all is changed only on purpose.
|
||||
AskBeforeChange(RenderAngleVulkanCb);
|
||||
AskBeforeChange(AdditionalShadersCb);
|
||||
AskBeforeChange(SkipPipelineCb);
|
||||
AskBeforeChange(RenderVBOCb);
|
||||
// Ignoring the gamepad is the recommended default; reading it has been trouble, so turning it on is asked.
|
||||
GamepadIgnoreCb.IsCheckedChanged += async (_, _) =>
|
||||
{
|
||||
if (string.Equals(key.Key, "targetfps", StringComparison.OrdinalIgnoreCase))
|
||||
UpdateIdleNotes();
|
||||
if (!AsksFirst || IsChecked(GamepadIgnoreCb) || TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
if (!await MessageBox.Show(owner, App.Loc["ConfirmGamepadUse"], App.Loc["GamepadSignalIgnore"],
|
||||
MessageBoxButtons.YesNo))
|
||||
Revert(() => GamepadIgnoreCb.IsChecked = true);
|
||||
};
|
||||
InitGraphics();
|
||||
RenderEngineCb.SelectionChanged += async (_, e) =>
|
||||
{
|
||||
if (!AsksFirst || e.RemovedItems.Count == 0)
|
||||
return;
|
||||
object? previous = e.RemovedItems[0];
|
||||
if (!await ConfirmRenderingChange(App.Loc["RenderEngine"]))
|
||||
Revert(() => RenderEngineCb.SelectedItem = previous);
|
||||
};
|
||||
// Coming to the page or to the list is when a new build is looked for.
|
||||
SelectExeCb.GotFocus += (_, _) => RefreshExecutables();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == IsVisibleProperty && IsVisible)
|
||||
RefreshExecutables();
|
||||
};
|
||||
App.Loc.LanguageChanged += UpdateGpuNote;
|
||||
App.Loc.LanguageChanged += UpdateAdvancedModeButton;
|
||||
App.Loc.LanguageChanged += UpdateUnknownValues;
|
||||
MotionBlurCb.IsCheckedChanged += (_, _) => UpdateDependentRows();
|
||||
ReflectionsCubeMapCb.IsCheckedChanged += (_, _) => UpdateDependentRows();
|
||||
|
||||
@@ -235,9 +260,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
App.Loc["ProfileSaveAs"], MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// Written beside the user's own eu07.ini, which stays as it is.
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
bool saved = AppServices.Current.SettingsStore.ExportTo(path);
|
||||
// Written beside the user's own eu07.ini, which stays as it is; the edits stay the page's, not saved
|
||||
bool saved = AppServices.Current.SettingsStore.ExportTo(path, Trial());
|
||||
PopulateProfileCombo();
|
||||
int idx = FindComboIndexByContent(ProfileCb, Path.GetFileNameWithoutExtension(path));
|
||||
if (idx >= 0) ProfileCb.SelectedIndex = idx;
|
||||
@@ -246,16 +270,33 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
|
||||
private void PopulateExeCombo()
|
||||
{
|
||||
string? current = (SelectExeCb.SelectedItem as ComboBoxItem)?.Content?.ToString();
|
||||
int index = SelectExeCb.SelectedIndex;
|
||||
string? chosen = index > 0 ? (SelectExeCb.SelectedItem as ComboBoxItem)?.Content?.ToString() : null;
|
||||
var (entries, at) = ExecutableList.Refreshed(AppServices.Current.Executables.ListCandidates(), chosen);
|
||||
|
||||
// The same files as shown: left alone, so a reader on the list hears nothing change.
|
||||
var shown = SelectExeCb.Items.Skip(1).Select(item => (item as ComboBoxItem)?.Content?.ToString() ?? "");
|
||||
if (SelectExeCb.Items.Count > 0 && shown.SequenceEqual(entries, StringComparer.Ordinal))
|
||||
return;
|
||||
|
||||
SelectExeCb.Items.Clear();
|
||||
SelectExeCb.Items.Add(new ComboBoxItem { Content = App.Loc["SelectEXEAuto"] });
|
||||
foreach (string exe in AppServices.Current.Executables.ListCandidates())
|
||||
foreach (string exe in entries)
|
||||
SelectExeCb.Items.Add(new ComboBoxItem { Content = exe });
|
||||
if (current is not null)
|
||||
{
|
||||
int idx = FindComboIndexByContent(SelectExeCb, current);
|
||||
SelectExeCb.SelectedIndex = idx >= 0 ? idx : 0;
|
||||
}
|
||||
if (index >= 0)
|
||||
SelectExeCb.SelectedIndex = at >= 0 ? at + 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks at the simulator folder again, so a build copied in while the starter runs is
|
||||
/// on the list without reopening anything. The choice stays as it was and is no edit:
|
||||
/// nothing waits for Save after it. Not while the list is open under the user's hand.
|
||||
/// </summary>
|
||||
public void RefreshExecutables()
|
||||
{
|
||||
if (SelectExeCb.IsDropDownOpen)
|
||||
return;
|
||||
WhileLoading(PopulateExeCombo);
|
||||
}
|
||||
|
||||
private async void BrowseExeButton_OnClick(object? sender, RoutedEventArgs e) =>
|
||||
@@ -316,7 +357,13 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SelectExeCb.SelectedIndex = index;
|
||||
}
|
||||
|
||||
public void ReloadFromSettings() => ApplyToUi();
|
||||
/// <summary>The settings read again from the file: the page shows them, no edit of its own left.</summary>
|
||||
public void ReloadFromSettings()
|
||||
{
|
||||
ApplyToUi();
|
||||
_dirty = false;
|
||||
UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while a cab-control binding is waiting for a keypress. The window's own
|
||||
@@ -329,6 +376,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
WhileLoading(() =>
|
||||
{
|
||||
SpeedometerTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLog;
|
||||
BlackBoxCb.IsChecked = AppServices.Current.Settings.BlackBox;
|
||||
TrainTapesCb.IsChecked = AppServices.Current.Settings.PhysicsLogTrains;
|
||||
SimLogsCb.IsChecked = AppServices.Current.Settings.DebugLog;
|
||||
});
|
||||
|
||||
@@ -367,9 +416,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
|
||||
// A reloaded file may name another simulator, or start a server.
|
||||
RefreshDerivedRows();
|
||||
UpdateUnknownValues();
|
||||
UpdateGpuNote();
|
||||
NoteShownValues();
|
||||
UpdateGraphicsState();
|
||||
UpdatePresetMarks();
|
||||
}
|
||||
|
||||
@@ -379,7 +428,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
private void ShowValues(SimulatorSettings s)
|
||||
{
|
||||
FullscreenCb.IsChecked = s.Fullscreen;
|
||||
// First, or a value outside the standard ranges would be moved into them on the way in.
|
||||
ApplyRanges(s);
|
||||
PauseInactiveCb.IsChecked = s.PauseWhenInactive;
|
||||
PauseStartCb.IsChecked = s.PauseOnStart;
|
||||
CursorSensitivitySlider.Value = s.CursorSensitivity;
|
||||
@@ -425,7 +475,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
_reflections.Value = s.ReflectionsFramerate;
|
||||
shaderResolutionSlider.Value = Log2(s.ShadowMapResolution, 12);
|
||||
shaderRange.Value = s.ShadowProjectionRange;
|
||||
cabShaderSourceRange.Value = s.CabShadowsRange;
|
||||
_cabShadows.Value = s.CabShadowsRange;
|
||||
ShadowDisplayCb.SelectedIndex = Math.Clamp(s.ShadowRankCutoff - 1, 0, 2);
|
||||
ReflectionsDetailsCb.SelectedIndex = s.ReflectionsFidelity;
|
||||
fovSlider.Value = s.FieldOfView;
|
||||
@@ -433,7 +483,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
RenderScreensThreadCb.IsChecked = s.PythonThreadedUpload;
|
||||
_fpsLimit.Value = s.FpsLimitEnabled ? s.FpsLimit : 0;
|
||||
ShadowAngleLimitSlider.Value = s.ShadowAngleLimit;
|
||||
FullscreenWindowedCb.IsChecked = s.FullscreenWindowed;
|
||||
RenderAngleVulkanCb.IsChecked = s.RenderAngleVulkan;
|
||||
|
||||
TrackCurvesSlider.Value = s.SplineFidelity;
|
||||
@@ -441,6 +490,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
PantographBreakCb.IsChecked = s.EnableTraction;
|
||||
OverheadOnlyCb.IsChecked = s.LiveTraction;
|
||||
SpeedometerTapesCb.IsChecked = s.PhysicsLog;
|
||||
BlackBoxCb.IsChecked = s.BlackBox;
|
||||
TrainTapesCb.IsChecked = s.PhysicsLogTrains;
|
||||
SimLogsCb.IsChecked = s.DebugLog;
|
||||
KeepLogsCb.IsChecked = s.MultipleLogs;
|
||||
DisplaySimulationCb.IsChecked = s.DisplaySimulation;
|
||||
@@ -462,6 +513,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
AutoCloseStarterCb.IsChecked = s.AutoCloseStarter;
|
||||
LargeThumbnailsCb.IsChecked = s.LargeThumbnails;
|
||||
AutoExpandTreeCb.IsChecked = s.AutoExpandSceneryTree;
|
||||
UpdateAdvancedModeButton();
|
||||
ReadyOverrideCb.SelectedIndex = (int)s.ReadyOverride;
|
||||
|
||||
CompressTexCb.IsChecked = s.CompressTextures;
|
||||
@@ -483,7 +535,15 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
private void ShowAsEdits(SimulatorSettings s)
|
||||
{
|
||||
ShowValues(s);
|
||||
_showingEdits = true;
|
||||
try
|
||||
{
|
||||
ShowValues(s);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_showingEdits = false;
|
||||
}
|
||||
RefreshDerivedRows();
|
||||
}
|
||||
|
||||
@@ -491,9 +551,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private void RefreshDerivedRows()
|
||||
{
|
||||
UpdateQualityCaptions();
|
||||
UpdateIdleNotes();
|
||||
UpdateDependentRows();
|
||||
UpdateGraphicsState();
|
||||
}
|
||||
|
||||
// ── Levels of detail ─────────────────────────────────────────────────────
|
||||
@@ -516,8 +574,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var (section, group) in new[]
|
||||
{
|
||||
(DrawRangeSection, GraphicsGroup.DrawRange), (TexturesSection, GraphicsGroup.Textures),
|
||||
(ShadowsSection, GraphicsGroup.Shadows), (LightsSection, GraphicsGroup.Lights),
|
||||
(ReflectionsSection, GraphicsGroup.Reflections), (NatureSection, GraphicsGroup.Nature)
|
||||
(ShadowsSection, GraphicsGroup.Shadows), (ReflectionsSection, GraphicsGroup.Reflections)
|
||||
})
|
||||
{
|
||||
var levels = new ComboBox();
|
||||
@@ -540,7 +597,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var (preset, button) in _presetButtons)
|
||||
{
|
||||
button.Content = App.Loc[preset.NameKey];
|
||||
ToolTip.SetTip(button, SettingTexts.PresetSummary(preset));
|
||||
}
|
||||
|
||||
_markingLevels = true;
|
||||
@@ -550,7 +606,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var level in GraphicsPreset.All)
|
||||
levels.Items.Add(new ComboBoxItem { Content = App.Loc[level.NameKey], Tag = level });
|
||||
levels.PlaceholderText = App.Loc["PresetCustom"];
|
||||
ToolTip.SetTip(levels, App.Loc["GfxGroupLevelTip"]);
|
||||
}
|
||||
_markingLevels = false;
|
||||
|
||||
@@ -574,8 +629,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
var trial = Trial();
|
||||
var applied = _presetMemory.Apply(preset, trial);
|
||||
ShowAsEdits(trial);
|
||||
foreach (string key in applied.RowKeys)
|
||||
_keyRows.Show(key, trial.Extra[key]);
|
||||
|
||||
// Chosen as a whole, its values are choices, not ones the screen could not show.
|
||||
ForgetShown(applied.ChosenKeys);
|
||||
@@ -649,8 +702,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (_cards.Count == 0)
|
||||
return;
|
||||
|
||||
CardText.Text = CardLine(_cards[0]);
|
||||
ToolTip.SetTip(CardText, string.Join(Environment.NewLine, _cards.Select(CardLine)));
|
||||
CardText.Text = string.Join(Environment.NewLine, _cards.Select(CardLine));
|
||||
}
|
||||
|
||||
// ── The screens' refresh rates, for the frame rate limit ─────────────────
|
||||
@@ -659,38 +711,51 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
|
||||
private void BuildMonitorRates()
|
||||
{
|
||||
var displays = AppServices.Current.Displays.List();
|
||||
if (displays.Count == 0)
|
||||
return;
|
||||
|
||||
MonitorRates.IsVisible = true;
|
||||
UpdateMonitorRates(displays);
|
||||
App.Loc.LanguageChanged += () => UpdateMonitorRates(displays);
|
||||
VSyncCb.IsCheckedChanged += (_, _) => UpdateMonitorRates();
|
||||
DisplayModeCb.SelectionChanged += (_, _) =>
|
||||
{
|
||||
UpdateDisplayRows();
|
||||
UpdateMonitorRates();
|
||||
};
|
||||
MonitorCb.SelectionChanged += (_, _) => UpdateMonitorRates();
|
||||
App.Loc.LanguageChanged += UpdateMonitorRates;
|
||||
UpdateMonitorRates();
|
||||
}
|
||||
|
||||
private void UpdateMonitorRates(IReadOnlyList<Display> displays)
|
||||
/// <summary>
|
||||
/// The rate of the monitor the simulator will show on, with a button to match the limit
|
||||
/// to it. VSync already holds the frames to that rate, so with it on there is no button:
|
||||
/// fpslimit paces frames by its own clock (framepacer.h), not the refresh, so no limit
|
||||
/// of it lines up with the monitor.
|
||||
/// </summary>
|
||||
private void UpdateMonitorRates()
|
||||
{
|
||||
bool vsync = IsChecked(VSyncCb);
|
||||
FpsVSyncNote.IsVisible = vsync;
|
||||
MonitorRates.Children.Clear();
|
||||
foreach (var display in displays)
|
||||
|
||||
int hz = SimulatorMonitor()?.RefreshRate ?? 0;
|
||||
MonitorRates.IsVisible = hz > 0;
|
||||
if (hz == 0)
|
||||
return;
|
||||
|
||||
MonitorRates.Children.Add(new TextBlock
|
||||
{
|
||||
string screen = string.IsNullOrEmpty(display.Name)
|
||||
? string.Format(App.Loc["MonitorRate"], display.RefreshRate)
|
||||
: string.Format(App.Loc["MonitorRateNamed"], display.Name, display.RefreshRate);
|
||||
MonitorRates.Children.Add(new TextBlock
|
||||
{
|
||||
Text = screen, FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center
|
||||
});
|
||||
var match = new Button
|
||||
{
|
||||
Content = string.Format(App.Loc["MonitorRateUse"], display.RefreshRate),
|
||||
Margin = new Thickness(4, 0, 14, 0)
|
||||
};
|
||||
match.Classes.Add("Outline");
|
||||
match.Classes.Add("SectionReset");
|
||||
int rate = display.RefreshRate;
|
||||
match.Click += (_, _) => _fpsLimit.Value = rate;
|
||||
MonitorRates.Children.Add(match);
|
||||
}
|
||||
Text = string.Format(App.Loc["MonitorRate"], hz),
|
||||
FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center
|
||||
});
|
||||
if (vsync)
|
||||
return;
|
||||
|
||||
var match = new Button
|
||||
{
|
||||
Content = string.Format(App.Loc["MonitorRateUse"], hz),
|
||||
Margin = new Thickness(4, 0, 14, 0)
|
||||
};
|
||||
match.Classes.Add("Outline");
|
||||
match.Classes.Add("SectionReset");
|
||||
match.Click += (_, _) => _fpsLimit.Value = hz;
|
||||
MonitorRates.Children.Add(match);
|
||||
}
|
||||
|
||||
// ── Sections back to the simulator's own values ──────────────────────────
|
||||
@@ -741,13 +806,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// <summary>Puts the section's rows at the simulator's own values, as edits waiting for Save.</summary>
|
||||
private void ResetSection(SettingsSection section)
|
||||
{
|
||||
var keys = ResettableKeys(section);
|
||||
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys));
|
||||
foreach (string key in keys)
|
||||
_keyRows.ShowDefault(key);
|
||||
|
||||
// Put back by hand, a value is a choice like any other.
|
||||
ForgetShown(keys);
|
||||
ShowDefaults(ResettableKeys(section));
|
||||
Announcer.Say(this, ScreenReaderNames.PickerText(ScreenReaderNames.TextOf(section.Header), App.Loc["DefaultsRestored"]));
|
||||
}
|
||||
|
||||
@@ -798,7 +857,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private string SelectedRenderer() =>
|
||||
SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
|
||||
|
||||
private RendererKind SelectedRendererKind() => SettingReach.KindOf(SelectedRenderer());
|
||||
private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer());
|
||||
|
||||
/// <summary>
|
||||
/// Writes the pending edits on this screen into the settings, so a save from
|
||||
@@ -816,7 +875,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
var language = ChangeLanguageCb.SelectedItem as ComboBoxItem;
|
||||
s.Language = language?.Content?.ToString() ?? App.Loc.CurrentLanguage;
|
||||
s.LanguageCode = language?.Tag as string ?? App.Loc.CurrentLangCode;
|
||||
s.Fullscreen = IsChecked(FullscreenCb);
|
||||
s.PauseWhenInactive = IsChecked(PauseInactiveCb);
|
||||
s.PauseOnStart = IsChecked(PauseStartCb);
|
||||
s.CursorSensitivity = (int)CursorSensitivitySlider.Value;
|
||||
@@ -856,7 +914,7 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
s.ReflectionsFramerate = _reflections.Value;
|
||||
s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value;
|
||||
s.ShadowProjectionRange = (int)shaderRange.Value;
|
||||
s.CabShadowsRange = (int)cabShaderSourceRange.Value;
|
||||
s.CabShadowsRange = (int)_cabShadows.Value;
|
||||
s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
|
||||
s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
|
||||
s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75);
|
||||
@@ -868,7 +926,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
if (fpsLimit > 0)
|
||||
s.FpsLimit = fpsLimit;
|
||||
s.ShadowAngleLimit = ShadowAngleLimitSlider.Value;
|
||||
s.FullscreenWindowed = IsChecked(FullscreenWindowedCb);
|
||||
s.RenderAngleVulkan = IsChecked(RenderAngleVulkanCb);
|
||||
|
||||
s.SplineFidelity = (int)TrackCurvesSlider.Value;
|
||||
@@ -876,6 +933,8 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
s.EnableTraction = IsChecked(PantographBreakCb);
|
||||
s.LiveTraction = IsChecked(OverheadOnlyCb);
|
||||
s.PhysicsLog = IsChecked(SpeedometerTapesCb);
|
||||
s.BlackBox = IsChecked(BlackBoxCb);
|
||||
s.PhysicsLogTrains = IsChecked(TrainTapesCb);
|
||||
s.DebugLog = IsChecked(SimLogsCb);
|
||||
s.MultipleLogs = IsChecked(KeepLogsCb);
|
||||
s.DisplaySimulation = IsChecked(DisplaySimulationCb);
|
||||
@@ -1025,6 +1084,10 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
CaptureInto(AppServices.Current.Settings);
|
||||
var store = AppServices.Current.SettingsStore;
|
||||
store.Save();
|
||||
// The file had changes from elsewhere, kept with these: show them.
|
||||
if (store.LastSaveMerged)
|
||||
ApplyToUi();
|
||||
UpdateUnknownValues();
|
||||
KeyboardConfig.Instance.Save();
|
||||
RedrawThumbnailsIfNeeded();
|
||||
// Not saved, it is still there to be saved.
|
||||
@@ -1033,12 +1096,51 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SaveStatus.Text = App.Loc[store.LastSaveFailed ? "SettingsNotSaved" : "SettingsSaved"];
|
||||
}
|
||||
|
||||
// ── Rendering changes, each confirmed ──────────────────────────────────
|
||||
|
||||
/// <summary>Set while a preset, a reset or a profile puts values on the screen: those are not clicks to confirm.</summary>
|
||||
private bool _showingEdits;
|
||||
|
||||
/// <summary>Set while a refused change is put back, which is no change to ask about.</summary>
|
||||
private bool _reverting;
|
||||
|
||||
private bool AsksFirst => _built && !_loading && !_showingEdits && !_reverting;
|
||||
|
||||
private void AskBeforeChange(CheckBox box) =>
|
||||
box.IsCheckedChanged += async (_, _) =>
|
||||
{
|
||||
if (!AsksFirst)
|
||||
return;
|
||||
if (!await ConfirmRenderingChange(ScreenReaderNames.TextOf(box.Content)))
|
||||
Revert(() => box.IsChecked = !box.IsChecked);
|
||||
};
|
||||
|
||||
private async Task<bool> ConfirmRenderingChange(string? setting)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return true;
|
||||
return await MessageBox.Show(owner, string.Format(App.Loc["ConfirmRenderingChange"], setting),
|
||||
App.Loc["GfxColRendering"], MessageBoxButtons.YesNo);
|
||||
}
|
||||
|
||||
private void Revert(Action putBack)
|
||||
{
|
||||
_reverting = true;
|
||||
try
|
||||
{
|
||||
putBack();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reverting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderEngineCb_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (!_built)
|
||||
return;
|
||||
|
||||
OnBackendChanged();
|
||||
RefreshDerivedRows();
|
||||
}
|
||||
|
||||
@@ -1094,43 +1196,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
return exes.FullPath(exes.Resolve(pick, out _));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dims the rows the simulator to be started would ignore and says why. Follows
|
||||
/// the simulator and renderer picked here, before they are saved.
|
||||
/// </summary>
|
||||
private void UpdateIdleNotes()
|
||||
{
|
||||
string exe = TargetExecutable();
|
||||
var settings = AppServices.Current.Settings;
|
||||
var target = new SimulatorTarget(
|
||||
AppServices.Current.Executables.IsWindowsBuild(exe),
|
||||
SelectedRenderer(),
|
||||
settings.NetworkServer,
|
||||
_keyRows.NumberIfSet("targetfps", settings),
|
||||
settings.FpsAverage,
|
||||
IsChecked(FullscreenWindowedCb));
|
||||
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
row.IdleNote = string.IsNullOrEmpty(row.ConfigKey)
|
||||
? null
|
||||
: IdleText(SettingReach.Why(row.ConfigKey, target));
|
||||
|
||||
RenderEngineWarning.IsVisible = SelectedRendererKind() == RendererKind.Experimental;
|
||||
}
|
||||
|
||||
private static string? IdleText(IdleReason reason) => reason switch
|
||||
{
|
||||
IdleReason.WindowsBuildOnly => App.Loc["IdleWindowsBuildOnly"],
|
||||
IdleReason.LegacyRendererOnly => App.Loc["IdleLegacyRendererOnly"],
|
||||
IdleReason.ModernRendererOnly => App.Loc["IdleModernRendererOnly"],
|
||||
IdleReason.OpenGlRenderersOnly => App.Loc["IdleOpenGlRenderersOnly"],
|
||||
IdleReason.NeedsNetworkServer => App.Loc["IdleNeedsNetworkServer"],
|
||||
IdleReason.NeedsFrameRateTarget => App.Loc["IdleNeedsFrameRateTarget"],
|
||||
IdleReason.MonitorModeInstead => App.Loc["IdleMonitorMode"],
|
||||
IdleReason.VulkanOnly => App.Loc["IdleVulkanOnly"],
|
||||
_ => null
|
||||
};
|
||||
|
||||
private void RedrawThumbnailsIfNeeded()
|
||||
{
|
||||
bool large = AppServices.Current.Settings.LargeThumbnails;
|
||||
@@ -1152,6 +1217,18 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
Announcer.Say(this, App.Loc["SettingsRestored"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page's own edits let go, and the keys': the page shows the settings as held. Not read again from the file
|
||||
/// as "Restore" does - what other pages set and not yet saved (a filter of the depot, the window maximized) stays.
|
||||
/// </summary>
|
||||
public void DiscardEdits()
|
||||
{
|
||||
ApplyToUi();
|
||||
_keyBindings.Reload();
|
||||
_dirty = false;
|
||||
UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>The list as <see cref="ResolutionChoices"/> has it for the monitors there are now, with the size selected.</summary>
|
||||
private void SelectResolution(int width, int height)
|
||||
{
|
||||
@@ -1238,7 +1315,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
private void UpdateShadowResolution()
|
||||
{
|
||||
int resolution = ShowPixels(ShadowResolutionRow, shaderResolutionSlider);
|
||||
ToolTip.SetTip(shaderResolutionSlider, SettingTexts.ShadowMapWord(resolution));
|
||||
|
||||
// Below this the simulator would raise the range anyway.
|
||||
shaderRange.Minimum = SimulatorSettings.ShadowRangeFloor(resolution);
|
||||
@@ -1293,6 +1369,158 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
/// </summary>
|
||||
private void UpdateFeedbackDetailVisibility() => ApplyFilter();
|
||||
|
||||
/// <summary>
|
||||
/// The mode is the player's way of using the starter, not a setting of the simulator: it is
|
||||
/// kept straight away, as the language is, and the scenario screen follows it.
|
||||
/// </summary>
|
||||
private async void AdvancedModeBtn_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
|
||||
var settings = AppServices.Current.Settings;
|
||||
if (!settings.AdvancedSettings)
|
||||
{
|
||||
if (!await MessageBox.ShowDelayed(owner, App.Loc["AdvancedModeWarning"], App.Loc["AdvancedMode"],
|
||||
App.Loc["AdvancedModeOn"], 20))
|
||||
return;
|
||||
|
||||
settings.AdvancedSettings = true;
|
||||
AppServices.Current.SettingsStore.Save();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await MessageBox.Show(owner, App.Loc["AdvancedModeOffConfirm"], App.Loc["AdvancedMode"],
|
||||
MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
// Leaving the mode leaves nothing of it behind: what only it shows goes back to the
|
||||
// simulator's own values, and the page is saved with them.
|
||||
ShowDefaults(AdvancedKeys());
|
||||
settings.AdvancedSettings = false;
|
||||
Save();
|
||||
}
|
||||
|
||||
AdvancedModeChanged?.Invoke();
|
||||
UpdateAdvancedModeButton();
|
||||
ApplyFilter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once, on the first start of this starter, for the settings an older one left: the
|
||||
/// standard mode, what only the advanced one shows at the simulator's own values, and
|
||||
/// every slider's value within its range, saved. eu07.ini is copied aside first.
|
||||
/// </summary>
|
||||
public void MoveToStandardOnce()
|
||||
{
|
||||
var settings = AppServices.Current.Settings;
|
||||
var store = AppServices.Current.SettingsStore;
|
||||
if (settings.MovedToStandard || store.LoadFailed)
|
||||
return;
|
||||
|
||||
store.KeepCopy(".before-standard");
|
||||
_clamping = true;
|
||||
try
|
||||
{
|
||||
ShowDefaults(AdvancedKeys());
|
||||
}
|
||||
finally
|
||||
{
|
||||
_clamping = false;
|
||||
}
|
||||
// A value moved into its slider is saved as moved, not left as the file had it.
|
||||
ForgetShown(SliderKeys());
|
||||
|
||||
bool wasAdvanced = settings.AdvancedSettings;
|
||||
settings.AdvancedSettings = false;
|
||||
settings.MovedToStandard = true;
|
||||
Save();
|
||||
|
||||
if (wasAdvanced)
|
||||
AdvancedModeChanged?.Invoke();
|
||||
UpdateAdvancedModeButton();
|
||||
ApplyFilter();
|
||||
}
|
||||
|
||||
/// <summary>Puts <paramref name="keys"/> at the simulator's own values, as edits waiting for Save.</summary>
|
||||
private void ShowDefaults(IReadOnlyCollection<string> keys)
|
||||
{
|
||||
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys));
|
||||
foreach (string key in keys)
|
||||
_keyRows.ShowDefault(key);
|
||||
// Put back by hand, a value is a choice like any other.
|
||||
ForgetShown(keys);
|
||||
}
|
||||
|
||||
/// <summary>The keys of the rows set with a slider.</summary>
|
||||
private HashSet<string> SliderKeys()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
if (row.GetLogicalDescendants().OfType<Slider>().Any())
|
||||
foreach (string key in (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
keys.Add(key);
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every setting of the page at the simulator's own values, the ones only the advanced mode
|
||||
/// shows too, as edits waiting for Save; the key bindings have a button of their own.
|
||||
/// </summary>
|
||||
private async void DefaultsButton_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
if (!await MessageBox.Show(owner, App.Loc["AllDefaultsConfirm"], App.Loc["RestoreDefaults"],
|
||||
MessageBoxButtons.YesNo))
|
||||
return;
|
||||
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var section in SettingsStack.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
keys.UnionWith(ResettableKeys(section));
|
||||
ShowDefaults(keys);
|
||||
SaveStatus.Text = App.Loc["DefaultsRestored"];
|
||||
}
|
||||
|
||||
/// <summary>The keys of every row only the advanced mode shows.</summary>
|
||||
private HashSet<string> AdvancedKeys()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var section in SettingsStack.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
{
|
||||
if (section.Advanced && !string.IsNullOrEmpty(section.ToggleKey))
|
||||
keys.Add(section.ToggleKey);
|
||||
foreach (var row in section.GetLogicalDescendants().OfType<SettingRow>())
|
||||
if (section.Advanced || row.Advanced)
|
||||
foreach (string key in (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
keys.Add(key);
|
||||
}
|
||||
keys.ExceptWith(KeptOnReset);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private bool Advanced => AppServices.Current.Settings.AdvancedSettings;
|
||||
|
||||
/// <summary>Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it.</summary>
|
||||
private void UpdateUnknownValues()
|
||||
{
|
||||
var unreadable = AppServices.Current.SettingsStore.UnreadableValues();
|
||||
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
|
||||
{
|
||||
var keys = (row.ConfigKey ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var found = keys.Where(unreadable.ContainsKey)
|
||||
.Select(key => keys.Length > 1 ? key + " " + unreadable[key] : unreadable[key])
|
||||
.ToList();
|
||||
row.UnknownValue = found.Count > 0 ? string.Format(App.Loc["UnknownIniValue"], string.Join(", ", found)) : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateAdvancedModeButton() =>
|
||||
AdvancedModeBtn.Content = App.Loc[Advanced ? "AdvancedModeOff" : "AdvancedModeMenu"];
|
||||
|
||||
private bool ConditionAllows(SettingRow row)
|
||||
{
|
||||
if (ReferenceEquals(row, GpuRow))
|
||||
@@ -1354,6 +1582,11 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
SettingsScroll.IsVisible = !bindings;
|
||||
PresetBar.IsVisible = category is "graphics" or "effects" && !searching;
|
||||
|
||||
// The standard mode keeps to what a player needs; a search still finds everything,
|
||||
// since whoever types a setting's name is looking for it.
|
||||
bool advanced = Advanced;
|
||||
bool everything = advanced || searching;
|
||||
|
||||
if (bindings)
|
||||
{
|
||||
_keyBindings.RebuildList();
|
||||
@@ -1371,12 +1604,17 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
foreach (var section in panel.GetLogicalDescendants().OfType<SettingsSection>())
|
||||
{
|
||||
bool anyInSection = false;
|
||||
if (section.Level is Control level)
|
||||
level.IsVisible = advanced;
|
||||
|
||||
foreach (var row in section.GetLogicalDescendants().OfType<SettingRow>())
|
||||
{
|
||||
bool visible = ConditionAllows(row) &&
|
||||
// A value the starter cannot read is shown in either mode, so it can be put right.
|
||||
bool standard = (!section.Advanced && !row.Advanced) || !string.IsNullOrEmpty(row.UnknownValue);
|
||||
bool visible = ConditionAllows(row) && (everything || standard) &&
|
||||
(!searching || TextMatch.Contains(RowSearchText(row), query));
|
||||
row.IsVisible = visible;
|
||||
row.Classes.Set("HideKey", !advanced);
|
||||
anyInSection |= visible;
|
||||
if (visible && searching)
|
||||
_shownCount++;
|
||||
@@ -1394,11 +1632,17 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
caption.IsVisible = searching;
|
||||
|
||||
if (CategoryItem(tag) is { } item)
|
||||
{
|
||||
item.Classes.Set("NoHits", searching && !anyRow);
|
||||
// A category with nothing for the standard mode leaves the list.
|
||||
item.IsVisible = everything || anyRow;
|
||||
}
|
||||
}
|
||||
|
||||
if (searching)
|
||||
SettingsScroll.Offset = new Vector(0, 0);
|
||||
else if (CategoryList.SelectedItem is ListBoxItem { IsVisible: false })
|
||||
CategoryList.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
private ListBoxItem? CategoryItem(string tag) =>
|
||||
@@ -1463,9 +1707,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
case NumericUpDown nud:
|
||||
nud.ValueChanged += (_, _) => OnControlChanged();
|
||||
break;
|
||||
case TextBox box when ReferenceEquals(box, VulkanDeviceTb):
|
||||
box.TextChanged += (_, _) => OnControlChanged();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1478,7 +1719,6 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
{
|
||||
MarkDirty();
|
||||
QueuePresetMarks();
|
||||
UpdateGraphicsState();
|
||||
}
|
||||
|
||||
private void MarkDirty()
|
||||
@@ -1490,9 +1730,12 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
UpdateSaveState();
|
||||
}
|
||||
|
||||
/// <summary>Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells.</summary>
|
||||
public bool HasUnsavedChanges => _dirty || KeyboardConfig.Instance.Dirty;
|
||||
|
||||
private void UpdateSaveState()
|
||||
{
|
||||
bool dirty = _dirty || KeyboardConfig.Instance.Dirty;
|
||||
bool dirty = HasUnsavedChanges;
|
||||
SaveButton.Classes.Set("Accent", dirty);
|
||||
SaveStatus.Text = dirty ? App.Loc["UnsavedChanges"] : string.Empty;
|
||||
}
|
||||
@@ -1506,6 +1749,31 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
return 200;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old starter's ranges (<see cref="SliderRanges"/>), in either mode, with the value
|
||||
/// <paramref name="s"/> has along with them: one from the file or a level outside them is
|
||||
/// shown as it is, so opening and saving the settings never moves it - as SliderSteps does.
|
||||
/// </summary>
|
||||
private void ApplyRanges(SimulatorSettings s)
|
||||
{
|
||||
// Clamping, the ranges stay as they are and a value past them is moved in.
|
||||
bool widen = !_clamping;
|
||||
int minTexture = Log2(SliderRanges.MinTextureSize, 9), minShadow = Log2(SliderRanges.MinShadowMap, 10);
|
||||
textureResolutionSlider.Minimum = widen ? Math.Min(minTexture, Log2(s.MaxTextureSize, 12)) : minTexture;
|
||||
shaderResolutionSlider.Minimum = widen ? Math.Min(minShadow, Log2(s.ShadowMapResolution, 12)) : minShadow;
|
||||
DynamicLightsSlider.Minimum = widen
|
||||
? Math.Min(SliderRanges.MinDynamicLights, s.DynamicLights)
|
||||
: SliderRanges.MinDynamicLights;
|
||||
CursorSensitivitySlider.Maximum = widen
|
||||
? Math.Max(SliderRanges.MaxCursorSensitivity, s.CursorSensitivity)
|
||||
: SliderRanges.MaxCursorSensitivity;
|
||||
foreach (var steps in new[] { _fpsLimit, _reflections, _anisotropy, _drawRangeFactor, _cabShadows })
|
||||
steps.Clamps = _clamping;
|
||||
}
|
||||
|
||||
/// <summary>Set while values are put on the screen moved into the sliders' ranges, not widening them.</summary>
|
||||
private bool _clamping;
|
||||
|
||||
private static int Log2(int value, int fallback)
|
||||
{
|
||||
if (value <= 0) return fallback;
|
||||
@@ -1545,11 +1813,9 @@ public partial class Settings : UserControl, ISettingsCapture
|
||||
int reach = SimulatorSettings.ShadowReach(metres, 1 << (int)shaderResolutionSlider.Value,
|
||||
SelectedRendererKind() != RendererKind.Modern);
|
||||
ShadowRangeRow.ValueText = reach == metres ? $"{metres} m" : $"{metres} m → {reach} m";
|
||||
ToolTip.SetTip(shaderRange, SettingTexts.ShadowRangeWord(reach));
|
||||
|
||||
int cabMetres = (int)cabShaderSourceRange.Value;
|
||||
int cabMetres = (int)_cabShadows.Value;
|
||||
CabShadowRangeRow.ValueText = cabMetres <= 0 ? App.Loc["RangeDisabled"] : $"{cabMetres} m";
|
||||
ToolTip.SetTip(cabShaderSourceRange, SettingTexts.CabShadowRangeWord(cabMetres));
|
||||
|
||||
ReflectionsFramerateRow.ValueText = SettingTexts.ReflectionsInterval(_reflections.Value);
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ internal sealed class SimulatorKeyRows
|
||||
// Marks the input as one of these rows, which tell about their own changes.
|
||||
input.Tag = key;
|
||||
|
||||
var setting = new SettingRow { ConfigKey = key.Key, Content = input };
|
||||
var setting = new SettingRow { ConfigKey = key.Key, Content = input, Advanced = !SimulatorKeys.Standard.Contains(key.Key) };
|
||||
var row = new Row(key, setting, input);
|
||||
_rows.Add(row);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user