From 4575f61cc8d8919571a72c9023b7cd584c81cba1 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 15:52:38 +0200
Subject: [PATCH 001/104] whois: add lookahead mode for the timetable entry
after the next stop
Dispatcher scripts that route trains at a station based on where they
go afterwards (e.g. a big terminal throat with several outbound
directions) have no way to read that: whois +40 only exposes the
current/next timetable entry (NextStop()/IsStop()), which while the
train is at that very station is that station itself.
Adds flags::whois_ahead (bit 6, previously unused) plus
TTrainParameters::StationNameAhead(Offset)/StationIsStopAhead(Offset),
returning the raw TimeTable[] entry Offset positions past StationIndex
(name and whether it's a booked stop, "none"/false past the end of the
timetable). The new whois branch calls both with Offset=1, mirroring
the existing +40 branch's UpdateValues()/WriteLog() shape.
Logic-verified with an isolated harness mirroring the touched types
(TTrainParameters/TController/TMemCell shapes and the exact function
bodies); not yet build-tested against the full engine locally - relying
on CI for that.
---
world/Event.cpp | 31 ++++++++++++++++++++++++++++++-
world/Event.h | 1 +
world/mtable.cpp | 16 ++++++++++++++++
world/mtable.h | 4 ++++
4 files changed, 51 insertions(+), 1 deletion(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index eb679e720..e47dbea23 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,13 +1018,42 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
+ // +64: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_name ) {
+ if( m_input.flags & flags::whois_ahead ) {
+ // +64
+ // the timetable entry one past the next stop, and whether the train stops there
+ auto const *owner { (
+ m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
+ m_activator->Mechanik :
+ m_activator->ctOwner ) };
+ auto const aheadname { (
+ owner != nullptr ?
+ owner->TrainTimetable().StationNameAhead( 1 ) :
+ "none" ) };
+ auto const aheadstop { (
+ owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
+ 1 :
+ 0 ) };
+
+ targetcell->UpdateValues(
+ aheadname, // station after the next one
+ 0, // unused
+ aheadstop, // stop there or passthrough
+ m_input.flags & ( flags::text | flags::value1 | flags::value2 ) );
+
+ WriteLog(
+ "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - "
+ + "[station after next: " + aheadname + "], "
+ + "[X], "
+ + "[stop there: " + ( aheadstop != 0 ? "yes" : "no" ) + "]" );
+ }
+ else if( m_input.flags & flags::whois_name ) {
// +32 or +40
// next station name
if( m_input.flags & flags::mode_alt ) {
diff --git a/world/Event.h b/world/Event.h
index 52ee3468d..55be65de1 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,6 +37,7 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
+ whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
diff --git a/world/mtable.cpp b/world/mtable.cpp
index cec54f870..75e6c8ad0 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,6 +77,22 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
+std::string TTrainParameters::StationNameAhead( int Offset ) const
+{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return "none";
+ return TimeTable[idx].StationName;
+}
+
+bool TTrainParameters::StationIsStopAhead( int Offset ) const
+{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return false;
+ return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+}
+
bool TTrainParameters::IsMaintenance() const {
if( StationIndex <= StationCount )
diff --git a/world/mtable.h b/world/mtable.h
index c58d120ff..701b0c6ca 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,6 +70,10 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
+ // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
+ std::string StationNameAhead( int Offset ) const;
+ // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
+ bool StationIsStopAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 5705062cd29826b9bb1386eb2ccfa5be258a3204 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 20:28:28 +0200
Subject: [PATCH 002/104] whois: select the lookahead mode via +48 instead of a
new bit
Per review: +48 (whois_name | whois_load, mode_alt clear) was an
unused combination of the existing mode bits - use that instead of
claiming a new bit 6. +56 (same, with mode_alt set) stays free for a
future mode. No new flags::* entry needed; mtable.h/.cpp unchanged.
---
world/Event.cpp | 8 +++++---
world/Event.h | 1 -
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index e47dbea23..ebfc73958 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,15 +1018,17 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
- // +64: station after the next one, unused, stop there or passthrough
+ // +48: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_ahead ) {
- // +64
+ if( ( m_input.flags & ( flags::whois_name | flags::whois_load | flags::mode_alt ) )
+ == ( flags::whois_name | flags::whois_load ) ) {
+ // +48 (the whois_name | whois_load combination was unused; +56, same with mode_alt
+ // set, stays free for a future mode)
// the timetable entry one past the next stop, and whether the train stops there
auto const *owner { (
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
diff --git a/world/Event.h b/world/Event.h
index 55be65de1..52ee3468d 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,7 +37,6 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
- whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
From 93463a3850e50f8818d12c042a6ef7e3639b84f3 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 21:24:01 +0200
Subject: [PATCH 003/104] whois: consolidate the two lookahead accessors into
one
Per review: StationNameAhead()/StationIsStopAhead() duplicated the same
bounds check for no reason. Replaced with a single
TimeTableEntryAhead(Offset) returning the TMTableLine itself; the whois
branch reads .StationName/.Ah off it directly.
---
world/Event.cpp | 12 +++++-------
world/mtable.cpp | 17 +++++------------
world/mtable.h | 7 +++----
3 files changed, 13 insertions(+), 23 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index ebfc73958..319ad0591 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1034,14 +1034,12 @@ whois_event::run_() {
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
m_activator->Mechanik :
m_activator->ctOwner ) };
- auto const aheadname { (
+ auto const *entry { (
owner != nullptr ?
- owner->TrainTimetable().StationNameAhead( 1 ) :
- "none" ) };
- auto const aheadstop { (
- owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
- 1 :
- 0 ) };
+ &owner->TrainTimetable().TimeTableEntryAhead( 1 ) :
+ nullptr ) };
+ auto const aheadname { ( entry != nullptr ? entry->StationName : "none" ) };
+ auto const aheadstop { ( entry != nullptr && entry->Ah >= 0 ? 1 : 0 ) };
targetcell->UpdateValues(
aheadname, // station after the next one
diff --git a/world/mtable.cpp b/world/mtable.cpp
index 75e6c8ad0..dd84b6c23 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,20 +77,13 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
-std::string TTrainParameters::StationNameAhead( int Offset ) const
-{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+TMTableLine const &TTrainParameters::TimeTableEntryAhead( int Offset ) const
+{ // wpis rozkladu Offset pozycji za aktualnym (bez pomijania przelotow);
+ // poza zakresem 1..StationCount zwraca techniczny wpis zerowy
int const idx { StationIndex + Offset };
if( ( idx < 1 ) || ( idx > StationCount ) )
- return "none";
- return TimeTable[idx].StationName;
-}
-
-bool TTrainParameters::StationIsStopAhead( int Offset ) const
-{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
- int const idx { StationIndex + Offset };
- if( ( idx < 1 ) || ( idx > StationCount ) )
- return false;
- return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+ return TimeTable[0];
+ return TimeTable[idx];
}
diff --git a/world/mtable.h b/world/mtable.h
index 701b0c6ca..2d20a27bb 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,10 +70,9 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
- // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
- std::string StationNameAhead( int Offset ) const;
- // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
- bool StationIsStopAhead( int Offset ) const;
+ // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount
+ // zwraca techniczny wpis zerowy (TimeTable[0], StationName=="nowhere", Ah==-1)
+ TMTableLine const &TimeTableEntryAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 36d4f16c01abd9404c7e3b59547260f33191b0ba Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sun, 27 Sep 2026 17:50:07 +0200
Subject: [PATCH 004/104] Brake force table: take the rapid step threshold from
the distributor
TMoverParameters::BrakeForceR() halves the force of a vehicle set to R
below 40 km/h. That is one approximation for every distributor, but a
NESt3/ESt4 distributor with a rapid relay engages the step above 70 km/h
and keeps it down to 50 km/h (TNESt3::GetPF, RapidStatus), and below
that its cylinder pressure is divided by the relay's own multiplier
(TRapid, RapidMult). For a vehicle braking from speed the full force
therefore lasts down to 50 km/h, not 40. The AI builds its consist brake
table (fBrake_a0/a1) from BrakeForceR(), so between 40 and 50 km/h it
expected twice the force the wagons actually deliver.
Add TBrake::GetRapidRatio(), which keeps the old approximation as the
default, and override it in TNESt3 with the relay's threshold and
multiplier. The brake itself is unchanged; only the prediction is.
---
McZapkie/Mover.cpp | 4 ++--
McZapkie/Oerlikon_ESt.cpp | 11 +++++++++++
McZapkie/Oerlikon_ESt.h | 2 ++
McZapkie/hamulce.h | 5 +++++
4 files changed, 20 insertions(+), 2 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 83c918e24..a58878ab4 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -5166,8 +5166,8 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity)
press = MaxBrakePress[3];
if (DynamicBrakeType == dbrake_automatic)
ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02);
- if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1 && velocity < 40)
- ratio = ratio / 2;
+ if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1)
+ ratio *= Hamulec->GetRapidRatio(velocity);
if (TrainType == dt_DMU && velocity < 30.0)
{
ratio -= 0.3;
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index 9559d3052..d8d5b3da8 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -324,6 +324,17 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
RapidStaly = false;
}
+double TNESt3::GetRapidRatio(double const Vel) const
+{
+ // ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
+ if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ return 1.0;
+ }
+ // a braking vehicle comes from above, so the step is still engaged down to the speed
+ // at which GetPF() drops it, not the one at which it engages
+ return ( Vel < 50.0 ? 1.0 / PrzekRapid->GetRapidMult() : 1.0 );
+}
+
double TNESt3::GetCRP()
{
return CntrlRes->P();
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index c12691851..180c47206 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -117,6 +117,7 @@ class TRapid : public TPrzekladnik {
public:
void SetRapidParams(double mult, double size);
void SetRapidStatus(bool rs);
+ double GetRapidMult() const { return RapidMult; }
void Update(double dt) /*override*/;
inline TRapid() :
TPrzekladnik()
@@ -213,6 +214,7 @@ class TNESt3 : public TBrake {
virtual double GetPF( double const PP, double const dt, double const Vel ) /*override*/; // przeplyw miedzy komora wstepna i PG
void EStParams(double i_crc); // parametry charakterystyczne dla ESt
virtual double GetCRP() /*override*/;
+ double GetRapidRatio(double const Vel) const override;
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP); // napelniacz sterujacego
diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h
index a05a36359..11b8bdfb3 100644
--- a/McZapkie/hamulce.h
+++ b/McZapkie/hamulce.h
@@ -442,6 +442,11 @@ class TBrake
/// Sets the rapid step ratio. Default no-op; overridden where supported.
/// Rapid ratio.
virtual void SetRM(double const RMR) {}; // ustalenie przelozenia rapida
+ /// Share of the full cylinder pressure the distributor delivers at the given speed
+ /// while the vehicle is slowing down through it, for a vehicle set to R. Used only to predict
+ /// the brake force; the default is the approximation BrakeForceR() has always used.
+ /// Vehicle velocity [km/h].
+ virtual double GetRapidRatio(double const Vel) const { return Vel < 40.0 ? 0.5 : 1.0; }
/// Sets the velocity threshold for the rapid step.
/// Velocity threshold (same unit as Vel passed to GetPF).
virtual void SetRV(double const RVR)
From 92bd7ef827196e0ae7f3dfa6e5cbabf93eb87390 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 005/104] AI braking: hold the speed on a descent
Two changes that only work together: the first on its own lets a heavy
freight train brake less on a descent than it needs (in testing an
ET42 with 30 loaded wagons overran the stop signal by 16-48 m at 20 per
mille), the second makes the hold on a descent what it should be.
The comparison that decides whether the AI may skip its reaction time
between two brake steps stays on the brake-only demand, as before: it
is about how much brake is asked for, and a heavy train in G approaching
a stop on a descent needs its brake built up at once. Compared in the
resultant frame, that train built up its brake one step per reaction
time and overran the signal (16 copies of the ET42 train, x20:
22 of 32 overruns with the comparison moved, 0 of 48 with it kept).
1. Compare the measured deceleration in the same frame.
Going downhill, adjust_desired_speed_for_current_speed() subtracts the
gravity component from AccDesired, so that IncBrake() sizes the handle
position for what the brake alone has to deliver. control_braking_force()
then compares that brake-only value with AbsAccS, which is the resultant
acceleration and already contains the gravity. On a 20 per mille descent
the two differ by about 0.2 m/s2, so the AI asked for more braking than
the target needed and then released, and repeated that.
Keep the subtracted part in fAccDesiredGravity and add it back wherever
AccDesired is compared with AbsAccS. It is zero everywhere else (flat,
uphill, braking test), so the behaviour there does not change.
2. Hold the speed with one continuous law.
On a descent the AI looks ahead to decide whether it will exceed the
target speed. The look-ahead was (1 - a0) * 30 / 3.6 s, a few seconds,
while a pneumatic brake in G takes tens of seconds to apply or to
release; the AI therefore acted on an estimate the train had already
left behind. The demand then jumped between the braking threshold above
the target and a lerp towards full acceleration below it, and with the
brake that slow this turned into long alternating applications and
releases.
- look ahead for half the brake application time while the train is
speeding up and half the release time while it is slowing down
(brake_response_horizon), never less than before;
- use one law on both sides of the target, proportional to the
predicted difference, and hold a band just below the limit that widens
with the gradient (pneumatic up to 3 km/h, EP/electric up to 1.5 km/h);
- once below a lower limit ahead, hold that limit instead of speeding up
towards the line speed and braking again.
---
vehicle/Driver.cpp | 101 ++++++++++++++++++++++++++++++++++-----------
vehicle/Driver.h | 1 +
2 files changed, 77 insertions(+), 25 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9a6de8596..5b61b6dd1 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7483,6 +7483,25 @@ TController::adjust_desired_speed_for_limits() {
}
}
+// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time
+// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G
+// is tens of seconds; never shorter than the look-ahead the AI has always used
+static double
+brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) {
+
+ auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 };
+ if( Brakesystem == TBrakeSystem::Pneumatic ) {
+ auto const isrelease { Acceleration < 0.0 };
+ horizon = std::max(
+ horizon,
+ 0.5 * (
+ Vehicle->BrakeDelayFlag > bdelay_G ?
+ Vehicle->BrakeDelay[ isrelease ? 0 : 1 ] :
+ Vehicle->BrakeDelay[ isrelease ? 2 : 3 ] ) );
+ }
+ return horizon;
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7496,6 +7515,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
// gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze
// normalna jazda
AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01;
+ fAccDesiredGravity = 0.0;
auto const vel { DirectionalVel() };
@@ -7654,35 +7674,57 @@ TController::adjust_desired_speed_for_current_speed() {
if( fAccGravity > 0.025 ) {
// going sharply downhill we may need to start braking sooner than usual
// try to estimate increase of current velocity before engaged brakes start working
- auto const speedestimate = vel + ( 1.0 - fBrake_a0[ 0 ] ) * 30.0 * AbsAccS;
- if( speedestimate > VelDesired ) {
- // jesli jedzie za szybko do AKTUALNEGO
- if( VelDesired == 0.0 ) {
- // jesli stoj, to hamuj, ale i tak juz za pozno :)
- AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
- }
- else {
- // if it looks like we'll exceed maximum speed start thinking about slight slowing down
- AccDesired = std::min( AccDesired, -0.05 + fAccThreshold );
- // HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
- && fBrake_a0[0] > 0.2 ) {
- AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
- }
- }
+ // look ahead for as long as the brake takes to respond, since that is how long the
+ // present acceleration will last whatever is done with the handle now; a pneumatic
+ // brake applies and releases on its own time scale, which in G is tens of seconds
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ auto const speedestimate = vel + 3.6 * horizon * AbsAccS;
+ // already below a lower limit ahead, the train has no business speeding up towards it
+ auto holdlimit { VelDesired };
+ if( ( VelNext > 0.0 )
+ && ( VelNext < holdlimit )
+ && ( vel <= VelNext + fVelPlus )
+ && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) {
+ holdlimit = VelNext;
+ }
+ // hold a band just below the limit; the steeper the descent the harder the train pulls
+ // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille)
+ // an electro-pneumatic or electric brake responds at once and needs far less room
+ auto const holdspeed { holdlimit - (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
+ std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
+ if( ( speedestimate > VelDesired )
+ && ( VelDesired == 0.0 ) ) {
+ // jesli stoj, to hamuj, ale i tak juz za pozno :)
+ AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
}
else {
- // stop accelerating when close enough to target speed
+ // one continuous law on both sides of the target, proportional to the predicted
+ // difference: a demand that jumps to the braking threshold above the target and to
+ // full acceleration below it alternates, with a brake that responds in seconds,
+ // between a hard application and a full release
AccDesired = std::min(
AccDesired, // but don't override decceleration for VelNext
- std::lerp( // ease off as you close to the target velocity
- EU07_AI_NOACCELERATION, AccPreferred,
- std::clamp( VelDesired - speedestimate, 0.0, fVelMinus ) / fVelMinus ) );
+ std::clamp(
+ EU07_AI_NOACCELERATION - 0.04 * ( speedestimate - holdspeed ),
+ -0.05 + fAccThreshold,
+ std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
+ // HACK: for cargo trains with high braking threshold ensure we cross that threshold
+ if( true == IsCargoTrain
+ && fBrake_a0[0] > 0.2
+ && speedestimate > holdlimit ) {
+ AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
+ }
}
// final tweaks
if( vel > EU07_AI_NOMOVEMENT ) {
// going downhill also take into account impact of gravity
AccDesired -= fAccGravity;
+ // from here on AccDesired is what the brake alone has to deliver, which is what
+ // IncBrake() sizes the handle position for; AbsAccS already contains the gravity,
+ // so the comparisons with it have to add this part back
+ fAccDesiredGravity = fAccGravity;
// HACK: if the max allowed speed was exceeded something went wrong; brake harder
AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 );
}
@@ -7773,6 +7815,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 1: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 1 ) {
ForcePNBrake = true;
@@ -7783,6 +7826,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 2: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 2 ) {
DBT_BrakingTime = ElapsedTime;
@@ -7794,6 +7838,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 3: {
AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 );
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( vel <= DBT_VelocityRelease ) {
DynamicBrakeTest = 4;
@@ -7980,6 +8025,10 @@ void TController::control_braking_force() {
}
}
+ // AbsAccS is the resultant acceleration, gravity included, so it is compared with the
+ // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
+ auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
+
if( is_emu() && !ForcePNBrake ) {
// właściwie, to warunek powinien być na działający EP
// Ra: to dobrze hamuje EP w EZT
@@ -7991,13 +8040,13 @@ void TController::control_braking_force() {
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > AccDesired + accmargin
+ && ( AbsAccS > accdesiredresultant + accmargin
|| BrakeCtrlPosition < 0 ) ) {
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
- if( AbsAccS < AccDesired - 0.05 ) {
+ if( AbsAccS < accdesiredresultant - 0.05 ) {
// jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo
// TBD: check if the condition isn't redundant with the DecBrake() code
if( BrakeCtrlPosition >= 0 ) {
@@ -8013,10 +8062,12 @@ void TController::control_braking_force() {
} // type & dt_ezt
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
- if( ( AccDesired < fAccGravity - 0.1 && AbsAccS > AccDesired + fBrake_a1[0] ) // regular braking
+ if( ( accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + fBrake_a1[0] ) // regular braking
|| ( fAccGravity < -0.05 && velocity < -0.1 ) ) { // also brake if uphill and slipping back
// u góry ustawia się hamowanie na fAccThreshold
if( fBrakeTime < 0.0
+ // the size of the brake demand decides whether to skip the reaction time, so the brake-only part
+ // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow)
|| AccDesired < fAccGravity - 0.5
|| BrakeCtrlPosition <= 0 ) {
// jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował
@@ -8033,8 +8084,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( AccDesired < fAccGravity - 0.05
- && AccDesired - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
+ if ( accdesiredresultant < fAccGravity - 0.05
+ && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index e7c4fac00..c493afc8a 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -387,6 +387,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
double VelLimit = -1.0; // predkość zadawana przez event jednokierunkowego ograniczenia prędkości // -1: brak ograniczenia prędkości
From ce87aa0e090d4b5fba7042588df6e5e71895d5a1 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 006/104] AI braking: plan approaches from the consist brake,
stop 8-15 m short
The new braking curve below plans the stop at the signal itself unless
the stopping point moves with it (in testing, trains stopped 0-3 m past
the signal), so both go in one change.
1. The braking curve.
The braking curve towards a lower speed or a stop assumed a constant
deceleration from the present speed over the whole distance. A pneumatic
brake does not work like that:
- it acts on the state the train is in once it has applied; while the
train is still speeding up (downhill), plan from the speed it will have
reached by then, over the distance left by then;
- cast iron blocks grip harder as the train slows, so a constant
deceleration plan asks for too much at the start and then releases;
follow the shape of the consist brake table (fBrake_a0/a1) over speed
instead (shaped_braking_demand), over the distance left once the brake
has had its fill time;
- no power while the train is still above the speed it is braking for.
IncBrake() only adds braking when the brake table says the present
position is not enough. When the table overestimates the consist (see
the previous rapid step fix, or a descent), the train keeps slowing too
little with the handle held. After the full fill time with the handle
unchanged, believe the train rather than the table (fBrakeHeldTime).
When the AI asks for no braking and the train is still slowing down more
than that, release. With the gentler plan above the demand eases off
early, and without this a heavy freight train in G came to a stand a few
hundred metres before a W4 with its brake still on (seen in testing).
2. The stopping window.
In train running the final approach to a stop signal began at
fMaxProximityDist (15-40 m, cargo 25-50 m), aimed at half of
fMinProximityDist (10-15 m, cargo 20-25 m), and set VelDesired = 0,
which asks for hard braking whatever the distance left. Where a train
came to a stand depended on how it entered that phase: on the test
sceneries anywhere from 1 to 45 m short of the signal on the flat and
25-42 m uphill for heavy freight.
For train running only (a W4 stop point, shunting and coupling keep the
old margins and the old final approach):
- stop 8-15 m short of the signal whatever the length of the train, aim
at the middle of that window (stopping_margin) both with the braking
curve and in the final approach, and ask there only for what the
distance left takes, following the consist brake table;
- start the final approach 50 m out (cargo 60 m) whether the train is
moving or standing; it used to be 15-40 m while moving and 50 m once
stopped, and with the gentler final approach above a train that came
to a stand between the two released to creep closer and, uphill,
rolled back and tried again;
- uphill, while the gradient alone would bring the train to a stand short
of the window, keep it rolling at no more than the speed the gradient
can take off by then, with power if needed;
- uphill, put the train brake on as the train comes to a stand, keep it
on while it stands, and apply it for real if the train rolls back. This
is done at the very end of pick_optimal_speed(): the adjustments made
before it assume a train moving forward and can raise the demand back
to "no braking" (with the rule placed earlier, EMUs rolled back up to
90 m in testing). The EMU branch of
control_braking_force() gets the "slipping back" condition the wagon
branch has always had.
3. Known limitation.
Heavy trains of wagons with the ESt3AL2 distributor (413S, 601W and
alike) respond more slowly than the AI expects: with the present brake
model the distributor fills the AL2 relay chamber, whose capacity is set
to 2 in TNESt3::SetSize (Przekladniki[i]->CreateCap(i)), through
orifices sized for about 1 l, so these wagons need 34 s to reach 95 %
cylinder pressure in G against 21 s for a plain ESt3. On a 20 per mille
descent an ET22 with 20 loaded 413S wagons overran the stop signal by up
to 6.5 m in 6 of 24 runs at x20 with this change. With the relay chamber
at 1 l and the release orifices at about 80 % of their diameter, as the
author of the brake model suggested, none of them did (0 of 16).
---
vehicle/Driver.cpp | 217 ++++++++++++++++++++++++++++++++++++++++-----
vehicle/Driver.h | 7 ++
2 files changed, 200 insertions(+), 24 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5b61b6dd1..09b607b69 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3122,6 +3122,17 @@ bool TController::IncBrake()
}
}
}
+ else if( BrakeCtrlPosition > 0.0
+ && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
+ && fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] ) ) {
+ // the table says the present position is enough, but the brake has had its full fill
+ // time since the handle last moved and the train is still not slowing down as asked:
+ // believe the train rather than the table
+ OK = BrakeLevelAdd( BrakingLevelIncrease );
+ }
else
OK = false;
}
@@ -3781,6 +3792,7 @@ void TController::BrakeLevelSet(double b)
if (BrakeCtrlPosition == b)
return; // nie przeliczać, jak nie ma zmiany
BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX);
+ fBrakeHeldTime = 0.0;
}
bool TController::BrakeLevelAdd(double b)
@@ -5911,6 +5923,7 @@ TController::update_timers( double dt ) {
ElapsedTime += dt;
WaitingTime += dt;
fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca
+ fBrakeHeldTime += dt;
if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) {
// brake charging timeout starts after charging ends
BrakeChargingCooldown += dt;
@@ -6659,12 +6672,27 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
- fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( true == IsAtPassengerStop ) {
+ // a stop point keeps the margins its W4 parameters (head or middle of the consist,
+ // platform length) were set up against
+ fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
+ fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( IsCargoTrain ) {
+ fMinProximityDist += 10.0;
+ }
+ }
+ else {
+ // a train stops 8-15 m short of the signal whatever its length; closer than the lower
+ // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out
+ fMinProximityDist = 8.0;
+ // the final approach begins far enough out to slow from the coasting speed down to the window,
+ // and at the same distance whether the train is moving or standing, so it does not flip
+ // between creeping closer and holding still when it comes to a stand short of the window
+ fMaxProximityDist = 50.0;
+ }
if( IsCargoTrain ) {
- // increase distances for cargo trains to take into account slower reaction to brakes
- fMinProximityDist += 10.0;
+ // start the final approach earlier for cargo trains, their brakes react more slowly
fMaxProximityDist += 10.0;
/*
if( IsHeavyCargoTrain ) {
@@ -6683,7 +6711,7 @@ TController::determine_proximity_ranges() {
if( mvOccupied->Vel < 0.1 ) {
// jak stanie za daleko, to niech nie dociąga paru metrów
- fMaxProximityDist = 50.0;
+ fMaxProximityDist = std::max( fMaxProximityDist, 50.0 );
}
if( iDrivigFlags & moveLate ) {
@@ -7314,6 +7342,26 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
+ if( ( true == is_train() )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( VelNext == 0.0 )
+ && ( ActualProximityDist <= fMaxProximityDist )
+ && ( fAccGravity < -0.025 ) ) {
+ // uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
+ // brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
+ // stands, and is applied for real if the train has started to roll back. done last, so that none of
+ // the adjustments above, made for a train moving forward, can undo it
+ auto const vel { DirectionalVel() };
+ if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
+ VelDesired = 0.0;
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( vel < 0.0 )
+ || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) ) {
+ AccDesired = std::min( AccDesired, fAccGravity - 0.15 );
+ }
+ }
+
// if the route ahead is blocked we might need to head the other way
check_route_behind( 1000 ); // NOTE: legacy scan range value
}
@@ -7502,6 +7550,55 @@ brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brak
return horizon;
}
+// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand
+static double
+uphill_stopping_distance( double const Velocity, double const Gravity ) {
+ return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) );
+}
+
+// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m]
+static double
+uphill_coasting_speed( double const Distance, double const Gravity ) {
+ return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) );
+}
+
+// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train
+// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the
+// consist brake table says it does (cast iron blocks grip harder as the train slows)
+static double
+shaped_braking_demand(
+ double const Velocity, double const Target, double const Distance, double const Gravity,
+ double const Vmax, double const *Brakea0, double const *Brakea1, int const Tablesize ) {
+
+ auto const fullbraking = [&]( double const Kmh ) {
+ auto const index { std::clamp( static_cast( Tablesize * Kmh / std::max( 1.0, Vmax ) ), 1, Tablesize ) };
+ return std::max( 0.01, Brakea0[ index ] + 12.0 * Brakea1[ index ] ); };
+ auto const travel = [&]( double const Ratio ) {
+ auto const steps { 24 };
+ auto const step { ( Velocity - Target ) / steps };
+ auto distance { 0.0 };
+ for( auto i { 0 }; i < steps; ++i ) {
+ auto const kmh { Target + ( i + 0.5 ) * step };
+ auto const deceleration { Ratio * fullbraking( kmh ) - Gravity };
+ if( deceleration <= 0.001 ) {
+ return std::numeric_limits::max();
+ }
+ distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration;
+ }
+ return distance; };
+
+ auto low { 0.0 };
+ auto high { 3.0 };
+ if( travel( high ) > Distance ) {
+ return Gravity - high * fullbraking( Velocity );
+ }
+ for( auto i { 0 }; i < 30; ++i ) {
+ auto const middle { 0.5 * ( low + high ) };
+ ( travel( middle ) > Distance ? low : high ) = middle;
+ }
+ return Gravity - high * fullbraking( Velocity );
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7552,9 +7649,33 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else {
// hamowanie tak, aby stanąć
- VelDesired = VelNext;
- AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
- AccDesired = std::min( AccDesired, fAccThreshold );
+ if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
+ VelDesired = VelNext;
+ AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
+ AccDesired = std::min( AccDesired, fAccThreshold );
+ }
+ else {
+ // a train keeps its desired speed until the lower edge of the stopping window (a desired
+ // speed of 0 here asks for hard braking whatever the distance left), aims at the middle
+ // of the window, and asks only for what that takes
+ auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
+ AccDesired = (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ // cast iron blocks grip harder as the train comes to a stand
+ shaped_braking_demand(
+ vel, VelNext, stoppingroom, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize ) :
+ ( VelNext * VelNext - vel * vel ) / ( 25.92 * stoppingroom ) );
+ if( ( fAccGravity < -0.025 )
+ && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > stopping_margin() ) ) {
+ // uphill the gradient alone would bring the train to a stand short of the
+ // middle of the stopping window; keep it rolling at the present speed until that changes,
+ // but no faster than the gradient alone can take off by the middle of the window
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
+ }
+ }
}
}
else {
@@ -7578,17 +7699,57 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) >= ActualProximityDist - fMaxProximityDist ) {
// don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
// ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
- auto const brakingpointoffset = VelNext * braking_distance_multiplier( VelNext );
- AccDesired = std::min(
- AccDesired,
- ( VelNext * VelNext - vel * vel )
- / ( 25.92
- * std::max(
- ActualProximityDist - brakingpointoffset,
- std::min(
- ActualProximityDist,
- brakingpointoffset ) )
- + 0.1 ) ); // najpierw hamuje mocniej, potem zluzuje
+ auto const brakingpointoffset = (
+ ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
+ stopping_margin() : // the same stopping point as the final approach
+ VelNext * braking_distance_multiplier( VelNext ) );
+ // a pneumatic brake acts on the state the train will be in once it has responded; while the
+ // train is still speeding up, plan the deceleration from there, so more is asked for at once
+ auto velocity { vel };
+ auto distance { ActualProximityDist };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AbsAccS > 0.0 ) ) {
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ velocity = vel + 3.6 * horizon * AbsAccS;
+ distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( vel + velocity ) * 0.5 / 3.6 * horizon );
+ }
+ auto const brakingroom {
+ std::max(
+ distance - brakingpointoffset,
+ std::min(
+ distance,
+ brakingpointoffset ) ) };
+ auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) {
+ // follow the shape of the consist brake force over speed rather than assume a constant
+ // deceleration, over the distance left once the brake has had time to fill (while the
+ // train is still speeding up, the prediction above has taken that off already)
+ auto room { brakingroom };
+ if( ( AbsAccS <= 0.0 )
+ && ( ( VelNext > 0.0 ) || ( BrakeCtrlPosition <= 0.0 ) ) ) { // for a stop, only while the brake is still to be applied
+ room = std::max(
+ 0.5 * brakingroom,
+ brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
+ }
+ deceleration = shaped_braking_demand(
+ velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize );
+ }
+ AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
+ if( vel > VelNext ) {
+ if( deceleration < fAccGravity - 0.001 ) {
+ // no power while still above the speed being braked for
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( fAccGravity < -0.025 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > brakingpointoffset ) ) {
+ // uphill the gradient alone slows the train down more than it is asked to;
+ // keep it rolling at the present speed until that changes
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
+ }
+ }
}
}
}
@@ -7959,7 +8120,13 @@ void TController::control_tractive_force() {
if( ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance
fMaxProximityDist) ? // other vehicle types keep wider margin
true :
- velocity + 1.0 < VelNext ) {
+ ( velocity + 1.0 < VelNext )
+ // uphill, a train told to hold its speed on the way to a stop needs the power to do it
+ || ( ( VelNext == 0.0 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( AccDesired >= 0.0 )
+ && ( fAccGravity < -0.025 )
+ && ( ActualProximityDist > fMinProximityDist ) ) ) {
// ...to można przyspieszyć
increase_tractive_force();
}
@@ -8039,9 +8206,10 @@ void TController::control_braking_force() {
auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) };
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
- if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > accdesiredresultant + accmargin
- || BrakeCtrlPosition < 0 ) ) {
+ if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
+ && ( AbsAccS > accdesiredresultant + accmargin
+ || BrakeCtrlPosition < 0 ) )
+ || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
@@ -8084,7 +8252,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( accdesiredresultant < fAccGravity - 0.05
+ if ( ( accdesiredresultant < fAccGravity - 0.05
+ || AccDesired >= EU07_AI_NOACCELERATION ) // no braking asked for, yet the train is slowing down more than that
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index c493afc8a..0e65a4b94 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -353,6 +353,12 @@ private:
void control_tractive_force();
void increase_tractive_force();
void control_braking_force();
+ // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
+ // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
+ double stopping_margin() const {
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ fMinProximityDist + 3.5 :
+ 0.5 * fMinProximityDist; }
void apply_independent_brake_only();
void check_route_ahead( double const Range );
void check_route_behind( double const Range );
@@ -387,6 +393,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From 4f2dfd93186f218f20c499ef20572b9fa5b30b83 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Tue, 29 Sep 2026 09:47:51 +0200
Subject: [PATCH 007/104] Drop redundant comparisons with true/false
In the conditions this PR adds; no change in behaviour.
---
McZapkie/Oerlikon_ESt.cpp | 2 +-
vehicle/Driver.cpp | 6 +++---
vehicle/Driver.h | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index d8d5b3da8..8705000a4 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -327,7 +327,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
double TNESt3::GetRapidRatio(double const Vel) const
{
// ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
- if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ if( ( PrzekRapid == nullptr ) || RapidStaly ) {
return 1.0;
}
// a braking vehicle comes from above, so the step is still engaged down to the speed
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 09b607b69..d75500dbe 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6672,7 +6672,7 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- if( true == IsAtPassengerStop ) {
+ if( IsAtPassengerStop ) {
// a stop point keeps the margins its W4 parameters (head or middle of the consist,
// platform length) were set up against
fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
@@ -7342,7 +7342,7 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
- if( ( true == is_train() )
+ if( is_train()
&& ( ( OrderCurrentGet() & Obey_train ) != 0 )
&& ( VelNext == 0.0 )
&& ( ActualProximityDist <= fMaxProximityDist )
@@ -7872,7 +7872,7 @@ TController::adjust_desired_speed_for_current_speed() {
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
+ if( IsCargoTrain
&& fBrake_a0[0] > 0.2
&& speedestimate > holdlimit ) {
AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 0e65a4b94..fefa950ca 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -356,7 +356,7 @@ private:
// how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
// otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
double stopping_margin() const {
- return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ?
fMinProximityDist + 3.5 :
0.5 * fMinProximityDist; }
void apply_independent_brake_only();
From 504d69b26a1be53aa4e6121685eda395ff10e47c Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 10 Oct 2026 23:39:19 +0200
Subject: [PATCH 008/104] AI braking: keep braking for a lower speed inside the
proximity range
Inside the proximity range only a stop had a final approach of its own;
for a lower speed ahead that branch set nothing, so AccDesired stayed at
the preferred acceleration. With the range at 50 m, which this PR uses so
that trains stop 8-15 m short of a signal, the AI stopped braking within
the last 50 m before a speed restriction and even took power: EMUs reached
a 20 km/h restriction at 25 km/h. On master the range is 15-40 m, which
kept this mostly out of sight.
A lower speed ahead now keeps the braking curve right up to where it
begins. Stops are unchanged.
Measured in real time on current master (with #199), with a 20 km/h
restriction one coach long, two runs of 32 consists each: over 22 km/h in
the restriction on the flat 9 on master, 15 before this change, 1 after
(a 36WEa at 22.1 km/h); on the 20 per mille descent 15, 0 and 0. Stops
8-15 m short of the signal stay as they were (flat 57 and 55 of 64,
descent 44 and 42), no overruns.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index c0e78b7cd..a5272b392 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7518,7 +7518,10 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else if (ActualProximityDist > fMinProximityDist) {
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
- if (ActualProximityDist < fMaxProximityDist) {
+ // only a stop has a final approach of its own inside the proximity range; a lower speed ahead
+ // keeps the braking curve below right up to where it begins, or the train would stop braking
+ // (and even take power) that far out
+ if( ( VelNext == 0.0 ) && ( ActualProximityDist < fMaxProximityDist ) ) {
// jak minął już maksymalny dystans po prostu hamuj (niski stopień)
// ma stanąć, a jest w drodze hamowania albo ma jechać
/*
From 86069c5eaba8700ff7f8b38bf4ee562421e85889 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 7 Jul 2026 01:45:05 +0200
Subject: [PATCH 009/104] utilities: XYZtoRGB: Use sRGB colorspace
It used Adobe RGB matrix depite of nothing else using Adobe RGB in
the pipeline.
---
utilities/color.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/utilities/color.h b/utilities/color.h
index be853a3d4..bbf17e096 100644
--- a/utilities/color.h
+++ b/utilities/color.h
@@ -15,9 +15,9 @@ glm::vec3
XYZtoRGB( glm::vec3 const &XYZ ) {
// M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html
- float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f };
+// float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f };
// m^-1 for sRGB:
-// float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f };
+ float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f };
return glm::vec3{
XYZ.x*mi[ 0 ][ 0 ] + XYZ.y*mi[ 1 ][ 0 ] + XYZ.z*mi[ 2 ][ 0 ],
From 842b768803c0499048360680ae5f6d6437c98609 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 7 Jul 2026 01:45:59 +0200
Subject: [PATCH 010/104] simulationenvironment: Adjust turbidity values
Turbidity 3 breaks the model at night. Adjust the values to have them
work well all the time and to maximize variation between cloud states.
---
simulation/simulationenvironment.cpp | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp
index 14ad2353c..0c1ec44b4 100644
--- a/simulation/simulationenvironment.cpp
+++ b/simulation/simulationenvironment.cpp
@@ -68,15 +68,15 @@ world_environment::compute_weather() const {
Global.AirTemperature > 1 ? "rain:" :
"snow:";
- Global.fTurbidity = Global.Overcast <= 0.10 ? 3 :
+ Global.fTurbidity = Global.Overcast <= 0.10 ? 4 :
Global.Overcast <= 0.20 ? 4 :
Global.Overcast <= 0.30 ? 5 :
Global.Overcast <= 0.40 ? 5 :
- Global.Overcast <= 0.50 ? 5 :
- Global.Overcast <= 0.60 ? 5 :
- Global.Overcast <= 0.70 ? 6 :
- Global.Overcast <= 0.80 ? 7 :
- Global.Overcast <= 0.90 ? 8 :
+ Global.Overcast <= 0.50 ? 6 :
+ Global.Overcast <= 0.60 ? 6 :
+ Global.Overcast <= 0.70 ? 7 :
+ Global.Overcast <= 0.80 ? 8 :
+ Global.Overcast <= 0.90 ? 9 :
9;
}
From ba405858e16a88ec5c0c9acb4dc0086dad13bfdd Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 27 Oct 2026 01:00:52 +0100
Subject: [PATCH 011/104] opengl33renderer: Fix up the sizes of Sun and Moon
Although the used value makes some physical sense, it fails to take
FoV effect into account, leading to both Sun and Moon becoming
comically tiny. Revert the sizes to the ones used by the legacy
renderer, which makes them appear much more plausible.
---
rendering/opengl33renderer.cpp | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index d20454c35..9d4318981 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -2028,12 +2028,12 @@ bool opengl33_renderer::Render(world_environment *Environment)
glm::vec4 color(suncolor.x, suncolor.y, suncolor.z, std::clamp(1.5f - Global.Overcast, 0.f, 1.f) * fogfactor);
auto const sunvector = Environment->m_sun.getDirection();
- /*float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
+ float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0325f,
0.0275f,
- std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );*/
+ std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
- model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), 0.00463f /* size */);
+ model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(0.0f, 1.0f, 1.0f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
@@ -2104,14 +2104,13 @@ bool opengl33_renderer::Render(world_environment *Environment)
moonu = 0.0f;
}
- /*
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0160f,
0.0135f,
- std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );*/
+ std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
- model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), 0.00451f /* size */);
+ model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(moonu, moonv, 0.333f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
From 6b82f1471aaf38b7417f28c018aa3e1e958416fc Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 12:36:11 +0100
Subject: [PATCH 012/104] AI braking: take power off when holding the speed
uphill near a stop
Within fMaxProximityDist of a stop, going uphill, the AI holds its speed
with AccDesired = min(0, AccPreferred). control_tractive_force only cut
the power uphill when AccDesired < 0, so an AccDesired of exactly 0 kept
the controller where it was. A consist that came into that range under
power kept full power and crept up to the signal.
Holding the speed uphill on the way to a stop now asks for no speeding
up: power comes off once the train is faster than AccDesired allows.
With the current brake valves this rarely shows: on a 10 per mille climb,
four real-time runs of 32 consists each, the E186 with 25 empty 408W drew
power in 0-14 samples of the last 50 m before and 0-8 after, no overruns
either way. It surfaced once the AI predicted the ESt3 brake closer to
what the valve delivers, where the same train crept to 12 km/h from 40 m
out and overran the signal; with this change it stopped short in all runs.
---
vehicle/Driver.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 2c59ddcda..436cdb7f6 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8099,7 +8099,9 @@ void TController::control_tractive_force() {
}
else if( velocity > VelDesired + SpeedCtrlMargin
|| ( fAccGravity < -0.01 ?
- AccDesired < 0.0 :
+ AccDesired < 0.0
+ // holding the speed uphill on the way to a stop asks for no speeding up
+ || ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ) :
AbsAccS > AccDesired + 10.05 )
|| IsAnyCouplerStretched ) {
// jak za bardzo przyspiesza albo prędkość przekroczona
From 1f3cf4fe56ee33fe38accd7903eaee401cd2d2a7 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 16:02:06 +0100
Subject: [PATCH 013/104] AI braking: don't let the running brake test override
a stop ahead
adjust_desired_speed_for_braking_test runs after the target speed was
worked out and overwrites AccDesired. In its third phase it holds the
deceleration near fAccThreshold until the speed has dropped by 8 km/h.
On a 20 per mille descent that application barely holds the speed, so
the phase can last minutes, and a stop signal coming up meanwhile is
ignored. In one real-time run an E186 with 19 container wagons started
the test 1290 m before a stop signal, lost 7 km/h by the signal and
overran it by 274 m after the emergency application.
While the test runs the AI now uses whichever of the two asks for the
harder braking: the test may brake harder than the route needs, never
softer.
Measured in real time, four runs of 32 consists each on a 20 per mille
descent, on the flat and on the descent with half the rail adhesion:
the test no longer runs within 600 m of a stop signal (before: down to
414 m on this branch, and 14 m with the overrun above in a build with
other brake changes), no overruns, stops 8-15 m short of the signal 86,
117 and 83 of 128 (before 90, 117 and 78).
---
vehicle/Driver.cpp | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 436cdb7f6..6d6c1532e 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7927,6 +7927,10 @@ TController::adjust_desired_speed_for_braking_test() {
if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well?
auto const vel { DirectionalVel() };
+ // what the route ahead asks for; the test may brake harder than that, never softer
+ auto const routeaccdesired { AccDesired };
+ auto const routeaccdesiredgravity { fAccDesiredGravity };
+ auto const routeveldesired { VelDesired };
switch( DynamicBrakeTest ) {
case 0: {
@@ -7993,6 +7997,14 @@ TController::adjust_desired_speed_for_braking_test() {
break;
}
}
+ // a stop or a restriction coming up while the test runs takes precedence
+ if( ( DynamicBrakeTest >= 1 )
+ && ( DynamicBrakeTest <= 3 )
+ && ( routeaccdesired < AccDesired ) ) {
+ AccDesired = routeaccdesired;
+ fAccDesiredGravity = routeaccdesiredgravity;
+ VelDesired = std::min( VelDesired, routeveldesired );
+ }
}
void
From 18bc7e06bfe58a4efff593dc3245a27289605ed3 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 16:43:16 +0100
Subject: [PATCH 014/104] AI braking: move the uphill power-off check into its
own function
The condition added for holding the speed uphill near a stop pushed the
cognitive complexity of control_tractive_force() to 26, over the 25
SonarCloud allows. It now lives in is_too_fast_uphill(); the behaviour
is unchanged.
---
vehicle/Driver.cpp | 13 ++++++++-----
vehicle/Driver.h | 1 +
2 files changed, 9 insertions(+), 5 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 6d6c1532e..2311ffacf 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8110,11 +8110,7 @@ void TController::control_tractive_force() {
cue_action( driver_hint::mastercontrollersetzerospeed );
}
else if( velocity > VelDesired + SpeedCtrlMargin
- || ( fAccGravity < -0.01 ?
- AccDesired < 0.0
- // holding the speed uphill on the way to a stop asks for no speeding up
- || ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ) :
- AbsAccS > AccDesired + 10.05 )
+ || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 )
|| IsAnyCouplerStretched ) {
// jak za bardzo przyspiesza albo prędkość przekroczona
// dodany wyjatek na "pelna w przod"
@@ -8126,6 +8122,13 @@ void TController::control_tractive_force() {
SpeedSet(); // ciągla regulacja prędkości
}
+bool TController::is_too_fast_uphill() const {
+
+ if( AccDesired < 0.0 ) { return true; }
+ // holding the speed uphill on the way to a stop asks for no speeding up
+ return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 );
+}
+
void TController::increase_tractive_force() {
if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index af97b4a1e..11a01517f 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -358,6 +358,7 @@ private:
void control_motor_connectors();
void control_tractive_force();
void increase_tractive_force();
+ bool is_too_fast_uphill() const;
void control_braking_force();
// how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
// otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
From bb43f559e8ede590142d5383e4686e8d3d563f6c Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 17:01:21 +0100
Subject: [PATCH 015/104] ESt3: spring preload, minimum stage, releaser time
and AL2 timing
Corrections to the TNESt3 distributor, checked against the ESt3 data
and acceptance requirements (orange book tables 3-5, 3-7 and 3-9) and
discussed with youBy:
- The main control device settles at (control reservoir - pipe - 0.21)
times the ratio instead of using a 0.05 bar offset. The 0.21 bar is the
spring preload; without it the first stage came 0.2 bar of pipe drop
too early. BVM is derived from the same offset, so a full service drop
still gives MaxBP.
- When the valve brakes it gives at least the minimum stage of 0.28 bar
(acceptance tests 12 and 22 require 0.25-0.30 bar); when the target
drops to zero the cylinder vents completely.
- The automatic releaser vents the 15 l control reservoir from 5.0 to
0.4 bar in about 23 s (test 27: 23 +/- 3 s) instead of 5.6 s.
- 12" cylinder fill nozzle dTN is 1.62, not 1.65 (typo).
- With the AL2 relay the impulse chamber is 1 l and the cylinder nozzles
are scaled so that the fill and release times meet table 3-9; before,
the AL2 timings had been set by eye.
On a valve test bench running the acceptance procedures, the number of
results out of tolerance drops from 77 to 40. The remaining ones need
parts that are not modelled yet (accelerator venting, ZP/ZS filling,
intermediate chamber).
---
McZapkie/Oerlikon_ESt.cpp | 44 +++++++++++++++++++++++++++++----------
McZapkie/Oerlikon_ESt.h | 1 +
2 files changed, 34 insertions(+), 11 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index eb3a9ad4b..f37dc69f9 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -16,6 +16,11 @@ Copyright (C) 2007-2014 Maciej Cierniak
#include "Oerlikon_ESt.h"
#include "utilities/utilities.h"
+// wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar]
+static double const dPSprezyny = 0.21;
+// najmniejszy stopien hamowania w cylindrze [bar] (tablica 3-9, proby 12 i 22: 0,25-0,30)
+static double const pStopnia = 0.28;
+
double d2A( double const d )
{
return d * d * 0.7854 / 1000.0;
@@ -218,10 +223,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr
CheckReleaser(dt);
// luzowanie
+ double const cel{ CelBCP( CVP, VVP ) };
if ((BrakeStatus & b_hld) == b_off)
dV =
PF(0.0, BCP, Nozzles[dTO] * nastG + (1.0 - nastG) * Nozzles[dOO])
- * dt * (0.1 + 4.9 * std::min(0.2, BCP - ((CVP - 0.05 - VVP) * BVM + 0.1)));
+ * dt * (0.1 + 4.9 * std::min(0.2, BCP - (cel > 0.0 ? cel + 0.1 : 0.0))); // bez stopnia luzuje do zera
else
dV = 0.0;
// BrakeCyl.Flow(-dV);
@@ -229,7 +235,7 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr
if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP )
dV =
PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) )
- * dt * (0.1 + 4.9 * std::min( 0.2, (CVP - 0.05 - VVP) * BVM - BCP ) );
+ * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) );
else
dV = 0;
// BrakeCyl.Flow(-dV);
@@ -313,7 +319,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
Miedzypoj->CreateCap(5.0);
Miedzypoj->CreatePress(PP);
- BVM = 1.0 / (HPP - 0.05 - LPP) * MaxBP;
+ BVM = 1.0 / (HPP - dPSprezyny - LPP) * MaxBP;
BrakeDelayFlag = BDF;
@@ -345,6 +351,13 @@ double TNESt3::GetCRP()
// return Miedzypoj.P;
}
+double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze
+{
+ double const cel{ ( CVP - dPSprezyny - VVP ) * BVM };
+ // gdy zawor hamuje, nie daje mniej niz najmniejszy stopien
+ return ( cel > 0.0 ? std::max( cel, pStopnia ) : cel );
+}
+
void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad rozrzadczy
{
double const VVP{ ValveRes->P() };
@@ -355,14 +368,14 @@ void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad r
Przys_blok = false;
// sprawdzanie stanu
- // if ((BrakeStatus and 1)=1)and(BCP>0.25)then
- if (VVP + 0.01 + BCP / BVM < CVP - 0.05 && Przys_blok)
+ double const cel{ CelBCP( CVP, VVP ) };
+ if (BCP < cel - 0.01 * BVM && Przys_blok)
BrakeStatus |= b_on | b_hld; // hamowanie stopniowe;
- else if (VVP - 0.01 + (BCP - 0.1) / BVM > CVP - 0.05)
+ else if (BCP - 0.1 > cel + 0.01 * BVM)
BrakeStatus &= ~( b_on | b_hld ); // luzowanie;
- else if (VVP + BCP / BVM > CVP - 0.05)
+ else if (BCP > cel)
BrakeStatus &= ~b_on; // zatrzymanie napelaniania;
- else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania
+ else if (BCP - 0.1 < cel && BCP > 0.25) // zatrzymanie luzowania
BrakeStatus |= b_hld;
if( ( BrakeStatus & b_hld ) == 0 )
@@ -391,7 +404,7 @@ void TNESt3::CheckReleaser(double const dt) // odluzniacz
// odluzniacz automatyczny
if ((BrakeStatus & b_rls) == b_rls)
{
- CntrlRes->Flow(PF(CVP, 0, 0.02) * dt);
+ CntrlRes->Flow(PF(CVP, 0, 0.0049) * dt); // ZS 15 l z 5,0 do 0,4 bar w 23 s (proba odbioru nr 27)
if (CVP < VVP + 0.3 || false == autom)
BrakeStatus &= ~b_rls;
}
@@ -560,7 +573,7 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
{ // dON,dOO,dTN,dTO,dP,dS
Nozzles[dON] = 3.7;
Nozzles[dOO] = 2.50;
- Nozzles[dTN] = 1.65;
+ Nozzles[dTN] = 1.62;
Nozzles[dTO] = 1.39;
Nozzles[dP] = 2.65;
Nozzles[dPd] = 1.80;
@@ -649,6 +662,14 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
Nozzles[dSd] = 1.1;
Nozzles[dSm] = 0.9;
+ if( PrzekCiagly != nullptr ) {
+ // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9
+ Nozzles[dON] *= 0.914;
+ Nozzles[dTN] *= 0.885;
+ Nozzles[dOO] *= 0.82;
+ Nozzles[dTO] *= 0.8;
+ }
+
// przeliczanie z mm^2 na l/m
for (auto &nozzle : Nozzles)
{
@@ -657,7 +678,8 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
for (int i = 1; i < 4; ++i)
{
Przekladniki[i]->BrakeRes = BrakeRes;
- Przekladniki[i]->CreateCap(i);
+ // komora impulsowa przekladnika AL2 ma 1 l
+ Przekladniki[i]->CreateCap( ( Przekladniki[i] == PrzekCiagly ) ? 1.0 : i );
Przekladniki[i]->CreatePress(BrakeCyl->P());
if (i < 3)
Przekladniki[i]->Next = Przekladniki[i + 1];
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index 9cdffe7bc..01aefb7f2 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -196,6 +196,7 @@ class TNESt3 : public TBrake {
void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt
double GetCRP() override;
double GetRapidRatio(double const Vel) const override;
+ double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP) const; // napelniacz sterujacego
From 6374e2d32e7ef00bb938d7b79763b1aae1d57779 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 17:01:32 +0100
Subject: [PATCH 016/104] AI braking: predict the ESt3 brake force from the
distributor characteristic
---
McZapkie/Mover.cpp | 1 +
McZapkie/Oerlikon_ESt.cpp | 11 +++++++++++
McZapkie/Oerlikon_ESt.h | 1 +
McZapkie/hamulce.h | 4 ++++
4 files changed, 17 insertions(+)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 429c2df17..2b2275112 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -5091,6 +5091,7 @@ void TMoverParameters::ComputeTotalForce(double dt)
double TMoverParameters::BrakeForceR(double ratio, double velocity)
{
double press = 0;
+ ratio = Hamulec->GetBrakeRatio(ratio);
if (MBPM > 2)
{
press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass));
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index f37dc69f9..1e7a5be66 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -351,6 +351,17 @@ double TNESt3::GetCRP()
// return Miedzypoj.P;
}
+double TNESt3::GetBrakeRatio( double const Ratio ) const // udzial cisnienia w cylindrze dla udzialu spadku w PG
+{
+ if( MaxBP <= 0.0 || BVM <= 0.0 ) {
+ return Ratio;
+ }
+ // pelny spadek sluzbowy w PG (HPP - LPP), odtworzony z przelozenia
+ double const spadek{ MaxBP / BVM + dPSprezyny };
+ double const cel{ ( Ratio * spadek - dPSprezyny ) * BVM };
+ return ( cel > 0.0 ? std::max( cel, pStopnia ) / MaxBP : 0.0 );
+}
+
double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze
{
double const cel{ ( CVP - dPSprezyny - VVP ) * BVM };
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index 01aefb7f2..02d65a285 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -197,6 +197,7 @@ class TNESt3 : public TBrake {
double GetCRP() override;
double GetRapidRatio(double const Vel) const override;
double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze
+ double GetBrakeRatio(double const Ratio) const override; // udzial cisnienia w cylindrze dla udzialu spadku w PG
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP) const; // napelniacz sterujacego
diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h
index 5b5f8933c..37b9b6a4d 100644
--- a/McZapkie/hamulce.h
+++ b/McZapkie/hamulce.h
@@ -421,6 +421,10 @@ class TBrake
double GetVRP() const; // cisnienie komory wstepnej rozdzielacza
/// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS.
virtual double GetCRP(); // cisnienie zbiornika sterujacego
+ /// Share of the full cylinder pressure the distributor settles at for the given share
+ /// of the full service pipe drop. Used only to predict the brake force; the default is proportional.
+ /// Share of the full service brake pipe drop.
+ virtual double GetBrakeRatio(double const Ratio) const { return Ratio; }
///
/// Sets the brake delay (G/P/R/M) selector if requested mode is supported.
///
From 4a256477e0d5b8be8685d7e9944af530b6584136 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Wed, 28 Oct 2026 03:33:33 +0100
Subject: [PATCH 017/104] Train: Handle 3-way light switches in headlighttoggle
actions
This lets them be fully operated with mouse and VR pointers.
---
vehicle/Train.cpp | 76 +++++++++++++++++++++++++++++++++++++----------
1 file changed, 60 insertions(+), 16 deletions(-)
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..e2f8fa86e 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -5234,15 +5234,37 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co
if (Command.action == GLFW_PRESS)
{
// only reacting to press, so the switch doesn't flip back and forth if key is held down
- if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0)
+
+ if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr)
{
- // turn on
- OnCommand_headlightenableleft(Train, Command);
- }
- else
- {
- // turn off
- OnCommand_headlightdisableleft(Train, Command);
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableleft(Train, Command);
+ }
+ else
+ {
+ // turn off
+ OnCommand_headlightdisableleft(Train, Command);
+ }
+ } else {
+ // if the light is controlled by 3-way switch, handle both headlight and redmarker
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 &&
+ (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableleft(Train, Command);
+ }
+ else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left)
+ {
+ // switch to red
+ OnCommand_redmarkerenableleft(Train, Command);
+ }
+ else
+ {
+ // disable
+ OnCommand_redmarkerdisableleft(Train, Command);
+ }
}
}
}
@@ -5317,15 +5339,37 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C
if (Command.action == GLFW_PRESS)
{
// only reacting to press, so the switch doesn't flip back and forth if key is held down
- if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0)
+
+ if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr)
{
- // turn on
- OnCommand_headlightenableright(Train, Command);
- }
- else
- {
- // turn off
- OnCommand_headlightdisableright(Train, Command);
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableright(Train, Command);
+ }
+ else
+ {
+ // turn off
+ OnCommand_headlightdisableright(Train, Command);
+ }
+ } else {
+ // if the light is controlled by 3-way switch, handle both headlight and redmarker
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 &&
+ (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableright(Train, Command);
+ }
+ else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right)
+ {
+ // switch to red
+ OnCommand_redmarkerenableright(Train, Command);
+ }
+ else
+ {
+ // disable
+ OnCommand_redmarkerdisableright(Train, Command);
+ }
}
}
}
From 7e426192b7962f0e2d0c1610e4639fe746b67fd9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 10:05:10 +0100
Subject: [PATCH 018/104] fix(cab): a diesel with only the starter button stops
its engine with the main switch off command (eu07/maszyna#427)
The SM03 had no way to stop its engine. Its fuel pump starts on its own, so the fuel pump switch is ignored; the
engine runs the converter feeding the low voltage circuit, so the battery switch doesn't starve the fuel pump either;
and its cab has only the starter button, for which TTrain::OnCommand_linebreakeropen() kept a legacy branch which
animated the button and returned without opening the circuit. MainSwitch(false) itself stops the engine fine.
The command now opens the circuit on diesels whose cab has only the starter button
(TMoverParameters::MainCircuitOpensWithStarterOnly()), without animating the button, which held down would start
the engine again. Other vehicles with only the button closing the circuit keep ignoring the command.
Tests: tests/unit/test_engine_shutdown.cpp, on a shunter made after the SM03.
---
McZapkie/MOVER.h | 7 +++
tests/unit/data/diesel_shunter.json | 53 +++++++++++++++++++++
tests/unit/test_engine_shutdown.cpp | 74 +++++++++++++++++++++++++++++
vehicle/Train.cpp | 3 +-
4 files changed, 136 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/data/diesel_shunter.json
create mode 100644 tests/unit/test_engine_shutdown.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..79a73f1a0 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2466,6 +2466,13 @@ class TMoverParameters
{
return false == StLinFlag && MainCircuitLampsEnabled();
}
+ // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button
+ // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump
+ // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command
+ bool MainCircuitOpensWithStarterOnly() const
+ {
+ return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric;
+ }
// whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on
bool OilFuelPumpsEnabled() const
{
diff --git a/tests/unit/data/diesel_shunter.json b/tests/unit/data/diesel_shunter.json
new file mode 100644
index 000000000..3cbcdb992
--- /dev/null
+++ b/tests/unit/data/diesel_shunter.json
@@ -0,0 +1,53 @@
+{
+ "_comment": "Diesel shunter with a mechanical gearbox, made after the SM03 (Ls150): the fuel pump starts on its own with the engine, a converter run by the engine feeds the low voltage circuit, the only cab control of the engine is the starter button.",
+ "Param": { "Category": "train", "M": 23200, "Vmax": 25.68, "PWR": 111.855, "SandCap": 200 },
+ "Dimensions": { "L": 6.94, "H": 3.21, "W": 2.97, "Cx": 0.3 },
+ "Wheels": { "D": 0.94, "Tw": 1.435, "AIM": 250, "Axle": "B", "Ad": 2.5, "Bd": 2.5, "Rmin": 50, "BearingType": "Roll" },
+ "Brake": {
+ "BrakeValve": "K", "NBpA": 2, "MBF": 85.0, "MaxBP": 3.5, "LocMaxBP": 5.0, "BCN": 1, "BCR": 0.114, "BCD": 0.12, "BCM": 10.0,
+ "HiPP": 5, "LoPP": 3.5, "Vv": 0.3, "MinCP": 7.0, "MaxCP": 8.0, "CompressorSpeed": 0.0125, "CompressorPower": "Main",
+ "BCS": 0.8, "BSA": 0, "BM": "P10-Bg", "BVV": 40, "BRE": 0.9
+ },
+ "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 3 },
+ "Cntrl": {
+ "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 4, "ASB": "Manual", "LocalBrake": "PneumaticBrake", "ManualBrake": "Yes",
+ "DynamicBrake": "Passive", "MCPN": 9, "SCPN": 7, "AutoRelay": "No", "IniCDelay": 0.5, "SCDelay": 0.1, "BrakeDelays": "P",
+ "BrakeHandle": "Knorr", "LocBrakeHandle": "Knorr", "FuelStart": "Automatic", "ConverterStart": "Automatic"
+ },
+ "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 24, "LMaxCurrent": 100 },
+ "Engine": {
+ "EngineType": "DieselEngine", "Trans": "1:1", "nmin": 900, "nmax": 1500, "nmax_cutoff": 1550, "AIM": 100,
+ "OilMinPressure": 0.343, "OilMaxPressure": 0.686, "WaterCoolingTemperature": 80, "WaterShutters": "yes", "WaterAuxCircuit": "no",
+ "HeatKFO": 160, "HeatKFO2": 180, "HeatKFS": 160, "HeatKFE": 7, "HeatKW": 2, "HeatKV": 0.3, "IsTC": "No", "EUS": 0.35, "EDS": 1.0
+ },
+ "_gears": "rows: gear, ratio, engagement speed, top speed; the even ones neutral",
+ "MotorParamTable": {
+ "minVelfullengage": 3.8, "engageDia": 1, "engageMaxForce": 800, "engagefriction": 1,
+ "rows": [
+ [0, 0, 0, -1],
+ [1, 46.88, -1, 5.73],
+ [2, 0, 0, -1],
+ [3, 28.65, 2.9, 9.42],
+ [4, 0, 0, -1],
+ [5, 17.12, 4.7, 15.69],
+ [6, 0, 0, -1],
+ [7, 10.46, 10.6, 100]
+ ]
+ },
+ "_throttle": "rows: position, fill, speed governor mode; position 0 idles",
+ "DList": {
+ "Size": 9, "Mmax": 784.5, "nMmax": 15, "Mnmax": 686.4, "nmax": 25, "nominalfill": 1, "Mstand": 200.0,
+ "rows": [
+ [0, 0.1, 0],
+ [1, 0.2, 2],
+ [2, 0.3, 2],
+ [3, 0.4, 2],
+ [4, 0.5, 2],
+ [5, 0.6, 2],
+ [6, 0.7, 2],
+ [7, 0.8, 2],
+ [8, 0.9, 2],
+ [9, 1.0, 2]
+ ]
+ }
+}
diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp
new file mode 100644
index 000000000..9230330f4
--- /dev/null
+++ b/tests/unit/test_engine_shutdown.cpp
@@ -0,0 +1,74 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// stopping the engine of a diesel shunter like the SM03 (eu07/maszyna#427): its fuel pump starts on its own with the
+// engine and the engine runs the converter which feeds the low voltage circuit, so neither the fuel pump switch nor the
+// battery switch stop it. the cab has only the starter button, and the command opening the main circuit has to stop it
+
+namespace {
+
+// the shunter with its engine started from the cab and idling
+test::vehicle running_shunter() {
+ test::vehicle shunter{test::definition::load("diesel_shunter")};
+ shunter->CabOccupied = 1;
+ shunter->CabActivisation();
+ shunter->BatterySwitch(true);
+ shunter->OilPumpSwitch(true);
+ shunter.run(20.0); // the oil pressure builds up
+ shunter->MainSwitch(true);
+ shunter.run(15.0);
+ return shunter;
+}
+
+} // namespace
+
+TEST_CASE("engine shutdown: the shunter starts with the starter button") {
+ auto shunter{running_shunter()};
+ REQUIRE(shunter->EngineType == TEngineType::DieselEngine);
+ REQUIRE(shunter->FuelPump.start_type == start_t::automatic);
+ CHECK(shunter->Mains);
+ CHECK(shunter->FuelPump.is_active);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch stop the engine") {
+ auto shunter{running_shunter()};
+ shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch
+ shunter.run(10.0);
+ CHECK(shunter->Mains);
+ shunter->BatterySwitch(false);
+ shunter.run(10.0);
+ CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump
+ CHECK(shunter->Mains);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: the command opening the main circuit stops the engine and it stays stopped") {
+ auto shunter{running_shunter()};
+ REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button
+ CHECK(shunter->MainSwitch(false));
+ shunter.run(20.0);
+ CHECK_FALSE(shunter->Mains);
+ CHECK_FALSE(shunter->FuelPump.is_active);
+ CHECK(shunter->enrot == 0.0);
+}
+
+TEST_CASE("engine shutdown: the engine starts again after it was stopped") {
+ auto shunter{running_shunter()};
+ shunter->MainSwitch(false);
+ shunter.run(20.0);
+ REQUIRE(shunter->enrot == 0.0);
+ shunter->MainSwitch(true);
+ shunter.run(15.0);
+ CHECK(shunter->Mains);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: vehicles without a diesel keep ignoring the command with only the button closing the circuit") {
+ test::vehicle wagon{test::definition::load("wagon")};
+ CHECK_FALSE(wagon->MainCircuitOpensWithStarterOnly());
+ test::vehicle electric{test::definition::load("wagon").set("Engine", "EngineType", "ElectricSeriesMotor")};
+ REQUIRE(electric->EngineType == TEngineType::ElectricSeriesMotor);
+ CHECK_FALSE(electric->MainCircuitOpensWithStarterOnly());
+}
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..1b7d06a8f 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -3702,13 +3702,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman
{
Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch);
}
- else if (Train->ggMainOnButton.SubModel != nullptr)
+ else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly())
{
// NOTE: legacy behaviour, for vehicles equipped only with impulse close switch
// it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress
Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch);
return;
}
+ // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again
// play sound immediately when the switch is hit, not after release
Train->fMainRelayTimer = 0.0f;
From d90edb698033c66ccc93e1c447c53269dbeaa9e9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 14:06:58 +0100
Subject: [PATCH 019/104] fix(cab): on the SU45 and SU46 the open line
contactors lamp lights with the contactors opened by the pressure switch
(eu07/maszyna#263)
On the electric locomotives the lamp of the open line contactors tells the start can be made, so it goes out with the
start cut off by the pressure switch. The diesel-electric SU45 and SU46 (the only diesel-electrics with the lamp) use
it just to show the contactors are open, but it went out the same way: with too low a pressure in the main pipe the
contactors were open and the lamp out. Once the pressure came back with the master controller past the first
position, the contactors stayed open, as they should, and the lamp lit up on a power position, which looked like
the lamp working the other way round.
On the diesel-electrics TMoverParameters::LineContactorsLampLit() now follows the contactors alone; the electric
locomotives and the other main circuit lamps are unchanged.
Tests: tests/unit/test_line_contactors.cpp, on a locomotive made after the SU46.
---
McZapkie/MOVER.h | 8 +++-
tests/unit/data/diesel_electric.json | 46 ++++++++++++++++++
tests/unit/test_line_contactors.cpp | 71 ++++++++++++++++++++++++++++
3 files changed, 124 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/data/diesel_electric.json
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..a34d537f4 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2461,9 +2461,15 @@ class TMoverParameters
{
return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0);
}
- // whether the lamp of the open line contactors is lit, telling the start can be made
+ // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so
+ // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the
+ // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263)
bool LineContactorsLampLit() const
{
+ if (EngineType == TEngineType::DieselElectric)
+ {
+ return false == StLinFlag;
+ }
return false == StLinFlag && MainCircuitLampsEnabled();
}
// whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on
diff --git a/tests/unit/data/diesel_electric.json b/tests/unit/data/diesel_electric.json
new file mode 100644
index 000000000..bef605880
--- /dev/null
+++ b/tests/unit/data/diesel_electric.json
@@ -0,0 +1,46 @@
+{
+ "_comment": "Diesel-electric locomotive made after the SU46 (303D): the line contactors close on the first power position of the master controller, the pressure switch (on by default) opens them with too low a pressure in the main pipe or the brakes applied.",
+ "Param": { "Category": "train", "M": 105000, "Mred": 15000, "Vmax": 120, "PWR": 1400, "SandCap": 400 },
+ "Dimensions": { "L": 18.99, "H": 4.292, "W": 2.904, "Cx": 0.3 },
+ "Wheels": { "D": 1.1, "AIM": 4000, "Tw": 1.435, "Axle": "Co'Co'", "Ad": 1.75, "Bd": 10.3, "Rmin": 100 },
+ "Brake": {
+ "BrakeValve": "LSt", "NBpA": 4, "MBF": 85.0, "MaxBP": 4.4, "LocMaxBP": 4.4, "MaxASBP": 1.3, "RM": 0.71, "BCN": 12, "BCR": 0.114,
+ "BCD": 0.06, "BCM": 5.84, "HiPP": 5, "LoPP": 3.5, "Vv": 0.9, "MinCP": 7, "MaxCP": 8.5, "CompressorSpeed": 0.05, "BCS": 1, "BSA": 2,
+ "BM": "P10-Bgu", "CompressorPower": "Converter", "BVV": 200, "BRE": 0.8
+ },
+ "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 103 },
+ "Cntrl": {
+ "BrakeHandle": "FV4a", "LocBrakeHandle": "FD1", "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 6, "BDelay3": 36, "BDelay4": 32,
+ "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": 15, "SCPN": 4, "AutoRelay": "Yes", "IniCDelay": 0.5, "SCDelay": 0.1,
+ "BrakeDelays": "GPR", "ConverterStart": "Automatic", "ConverterStartDelay": 10
+ },
+ "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 110, "LMaxCurrent": 100 },
+ "Engine": {
+ "AIM": 1.6, "EngineType": "DumbDE", "Trans": "18:62", "Ftmax": 317000, "Flat": 0, "Vhyp": 15.0, "Vadd": 3.8, "Cr": 1.0, "RelayType": 46,
+ "OilMinPressure": 0.055, "OilMaxPressure": 0.6, "WaterMinTemperature": 40, "WaterMaxTemperature": 92, "WaterCoolingTemperature": 76,
+ "HeatKW": 0.068599, "HeatKV": 0.3, "HeatKFE": 1, "HeatKFS": 87.76269, "HeatKFO": 26.72716, "HeatKFO2": 57.72
+ },
+ "Circuit": { "CircuitRes": 0.01, "ImaxLo": 3300, "IminLo": 2500 },
+ "_power": "rows: engine speed [rpm], power [kW], generator voltage limit, current limit, one per master controller position",
+ "WWList": {
+ "Size": 15,
+ "rows": [
+ [696, 0, 0, 0],
+ [696, 0, 0, 0],
+ [696, 80, 350, 1000],
+ [696, 80, 350, 1000],
+ [763, 214, 455, 1400],
+ [830, 321, 500, 1600],
+ [897, 428, 545, 1800],
+ [964, 535, 590, 2000],
+ [1031, 642, 635, 2200],
+ [1098, 748, 680, 2400],
+ [1165, 855, 725, 2600],
+ [1232, 962, 770, 2800],
+ [1299, 1069, 815, 3000],
+ [1366, 1176, 865, 3200],
+ [1433, 1283, 910, 3400],
+ [1500, 1390, 960, 3600]
+ ]
+ }
+}
diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp
index 79c419edf..fd7e24f08 100644
--- a/tests/unit/test_line_contactors.cpp
+++ b/tests/unit/test_line_contactors.cpp
@@ -57,3 +57,74 @@ TEST_CASE("line contactors: the ground relay and overload lamps follow the same
vehicle->MotorConnectorsCheck();
CHECK_FALSE(vehicle->MainCircuitLampsEnabled());
}
+
+// on the diesel-electric SU45 and SU46 (eu07/maszyna#263) the lamp tells just the line contactors are open: lit with the
+// master controller at 0 and with the start cut off by too low a pressure in the main pipe, out on the power positions
+
+namespace {
+
+// the diesel-electric locomotive with its engine running and the brakes released, the master controller at 0
+test::vehicle diesel_electric() {
+ test::vehicle vehicle{test::definition::load("diesel_electric")};
+ vehicle->CabOccupied = 1;
+ vehicle->CabActivisation();
+ vehicle->BatterySwitch(true);
+ vehicle->OilPumpSwitch(true);
+ vehicle->FuelPumpSwitch(true);
+ vehicle.run(20.0); // the oil pressure builds up
+ vehicle.hold_brake_pipe(5.0); // bar
+ vehicle->MainSwitch(true);
+ vehicle.run(30.0);
+ vehicle->DirectionForward();
+ vehicle.run(60.0); // the brakes release
+ return vehicle;
+}
+
+} // namespace
+
+TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") {
+ auto vehicle{diesel_electric()};
+ REQUIRE(vehicle->EngineType == TEngineType::DieselElectric);
+ REQUIRE(vehicle->Mains);
+ REQUIRE_FALSE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+
+ vehicle->IncMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK(vehicle->StLinFlag);
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+
+ vehicle->DecMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+}
+
+TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contactors opened by too low a main pipe pressure") {
+ auto vehicle{diesel_electric()};
+ vehicle->IncMainCtrl(1);
+ vehicle.run(1.0);
+ vehicle->IncMainCtrl(1);
+ vehicle.run(2.0);
+ REQUIRE(vehicle->StLinFlag);
+
+ vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch
+ vehicle.run(10.0);
+ REQUIRE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit()); // it went out here
+ CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off
+
+ // the pressure back, the contactors stay open on the second position and the lamp stays lit, as it should;
+ // they close again only on the first one
+ vehicle.hold_brake_pipe(5.0);
+ vehicle.run(60.0);
+ REQUIRE_FALSE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+ vehicle->DecMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK(vehicle->StLinFlag);
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+}
From 439e892abdaeac36bb76f3df2c8f926f76791477 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:35:35 +0100
Subject: [PATCH 020/104] AI: use the locomotive releaser only when starting
off
The rule "wyluzuj lokomotywe, to szybciej ruszymy" released the
locomotive's own brake whenever power was asked for and the locomotive
cylinder held more than 0.4 bar. It had no speed condition, so it also
fired in motion, at 50-75 km/h, right after an application. On a
locomotive with the EStED distributor (E186) this vented the control
reservoir; with the pipe not yet recharged the locomotive brake then
faded to nothing at the next application.
The rule is meant for starting off, so it now applies only below
1 km/h.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 2311ffacf..8d2a3fac6 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8292,8 +8292,11 @@ void TController::control_releaser() {
}
}
// wyluzuj lokomotywę, to szybciej ruszymy
+ // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
+ // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
if( mvOccupied->BrakePress > 0.4
- && mvOccupied->Hamulec->GetCRP() > 4.9 ) {
+ && mvOccupied->Hamulec->GetCRP() > 4.9
+ && mvOccupied->Vel < 1.0 ) {
actuate = true;
}
// keep engine brakes released during coupling/uncoupling
From fddeea8b0e48e3bda81c3da5c90cb729eb8d3e31 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:35:35 +0100
Subject: [PATCH 021/104] AI: use the locomotive releaser only when starting
off
The rule "wyluzuj lokomotywe, to szybciej ruszymy" released the
locomotive's own brake whenever power was asked for and the locomotive
cylinder held more than 0.4 bar. It had no speed condition, so it also
fired in motion, at 50-75 km/h, right after an application. On a
locomotive with the EStED distributor (E186) this vented the control
reservoir; with the pipe not yet recharged the locomotive brake then
faded to nothing at the next application.
The rule is meant for starting off, so it now applies only below
1 km/h.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..97ec36470 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8057,8 +8057,11 @@ void TController::control_releaser() {
}
}
// wyluzuj lokomotywę, to szybciej ruszymy
+ // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
+ // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
if( mvOccupied->BrakePress > 0.4
- && mvOccupied->Hamulec->GetCRP() > 4.9 ) {
+ && mvOccupied->Hamulec->GetCRP() > 4.9
+ && mvOccupied->Vel < 1.0 ) {
actuate = true;
}
// keep engine brakes released during coupling/uncoupling
From 798fd89dd0fc616967485a06530f9b40a88791e9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 19:16:46 +0200
Subject: [PATCH 022/104] test: scenario tests that run the simulator and check
a vehicle's physicslog
tests/scenarios/run.py builds a test scenery from a game install's scenery
(own trainsets removed, case fragment added), runs eu07 in ghostview with
physicslog on, and checks what the vehicle did: starts, max speed, brakes,
stops. First case: EU07 on td.scn driven by AI on the td/rozklad timetable,
with the Stacja1 exit route set by an event launcher instead of shift+4.
eu07 gets a -ini option: an extra settings file read after eu07.ini,
so a test run can switch to a window and turn on physicslog without touching
the user's config.
Local only: scenery and vehicle data are not in the repo.
---
application/application.cpp | 12 +-
tests/scenarios/.gitignore | 2 +
tests/scenarios/README.md | 66 ++++
tests/scenarios/cases/eu07_td_timetable.json | 15 +
tests/scenarios/cases/eu07_td_timetable.scn | 11 +
tests/scenarios/run.py | 330 +++++++++++++++++++
6 files changed, 435 insertions(+), 1 deletion(-)
create mode 100644 tests/scenarios/.gitignore
create mode 100644 tests/scenarios/README.md
create mode 100644 tests/scenarios/cases/eu07_td_timetable.json
create mode 100644 tests/scenarios/cases/eu07_td_timetable.scn
create mode 100644 tests/scenarios/run.py
diff --git a/application/application.cpp b/application/application.cpp
index 9b7b82853..ee381f98b 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1195,12 +1195,22 @@ int eu07_application::init_settings(int Argc, char *Argv[])
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
}
}
+ else if (token == "-ini")
+ {
+ // extra settings file read on top of eu07.ini, so a run can override a few keys
+ // (window size, physicslog...) without touching the user's own config
+ if (i + 1 < Argc)
+ {
+ Global.LoadIniFile(Argv[++i]);
+ }
+ }
else
{
std::cout << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
- << " [-seed number|word]" << std::endl;
+ << " [-seed number|word]"
+ << " [-ini settingsfile]" << std::endl;
return -1;
}
}
diff --git a/tests/scenarios/.gitignore b/tests/scenarios/.gitignore
new file mode 100644
index 000000000..ea93687fe
--- /dev/null
+++ b/tests/scenarios/.gitignore
@@ -0,0 +1,2 @@
+out/
+__pycache__/
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
new file mode 100644
index 000000000..77edb5a93
--- /dev/null
+++ b/tests/scenarios/README.md
@@ -0,0 +1,66 @@
+# Scenario tests
+
+End-to-end checks that run the real simulator on a scenery and look at what a vehicle
+did: did it start, did it keep to the speed limit, did it brake and stop.
+
+Scenery and vehicle data are not in this repo, so these run against a local game install
+only, not in CI.
+
+## Running
+
+```
+python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna"
+```
+
+Python 3.10+, no extra packages. Options:
+
+- `EU07_GAME_DIR` can replace `--game-dir`.
+- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
+ `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
+- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
+- `--timespeed 4` runs the simulation faster than real time.
+
+Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
+the vehicle's physicslog) land in `tests/scenarios/out//`.
+
+## How it works
+
+For each case the runner:
+
+1. writes `scenery/autotest_.scn` into the game dir: the base scenery with its own
+ trainsets removed, the start time changed if the case says so, and the case's `.scn`
+ fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
+ in for keys the scenery expects a player to press, extra events) before it,
+2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
+ ghostview leaves every train to the AI, and the extra ini turns on `physicslog`,
+ runs in a 1280x720 window and does not pause when the window loses focus,
+3. waits until `physicslog/.dat` covers `duration` seconds, then closes the simulator,
+4. runs the checks on the physicslog.
+
+## Writing a case
+
+`cases/.json`:
+
+| key | meaning |
+| --- | --- |
+| `base_scenery` | scenery file in the game's `scenery/` dir |
+| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
+| `time` | replace the scenery start time, `HH:MM` |
+| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
+| `vehicle` | node name of the vehicle whose physicslog is checked |
+| `duration` | seconds of simulation to record |
+| `timeout` | wall-clock seconds before giving up, loading included |
+| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
+| `checks` | list of checks, below |
+
+Checks (speeds in km/h, times in seconds of physicslog time):
+
+- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
+- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
+- `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar
+ (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0).
+- `stops` `moving_speed`, `stop_speed`, `hold`: after reaching `moving_speed`, stays at or
+ below `stop_speed` for `hold` seconds.
+
+New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
+parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json
new file mode 100644
index 000000000..c12b8ae71
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_timetable.json
@@ -0,0 +1,15 @@
+{
+ "description": "EU07 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "eu07_td_timetable.scn",
+ "vehicle": "autotest_eu07",
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_timetable.scn b/tests/scenarios/cases/eu07_td_timetable.scn
new file mode 100644
index 000000000..c8044e467
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_timetable.scn
@@ -0,0 +1,11 @@
+// added by tests/scenarios/run.py to the base scenery, whose own trainsets were removed:
+// the trainset goes after FirstInit, the launcher before it.
+// the EU07 stands where td.scn keeps its timetable train and gets the same timetable.
+trainset td/rozklad tdo_n1734 0.0 0.1
+node -1 0 autotest_eu07 dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic
+endtrainset
+
+// td.scn sets routes from the keyboard (shift+1..4 run events keyctrl01..04). keyctrl04 is the
+// way out of the track the train stands on: switch zwr02 and the exit signal stacja1_j at 40.
+// a launcher with a positive time fires once at that hour (HHMM), radius -1 means anywhere.
+node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
new file mode 100644
index 000000000..ad1f51ee7
--- /dev/null
+++ b/tests/scenarios/run.py
@@ -0,0 +1,330 @@
+#!/usr/bin/env python3
+"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
+
+A case (cases/.json) names a base scenery from the game install, a fragment
+appended to it (usually a trainset with an AI driver), and checks on the vehicle's
+physics log. The runner:
+
+ 1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
+ trainsets removed, optionally a different start time, and the case fragment appended,
+ 2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
+ settings file (-ini) that turns on physicslog and runs in a window,
+ 3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
+ then closes the simulator,
+ 4. evaluates the checks on the log and prints PASS/FAIL per check.
+
+Scenery and vehicle data are not part of this repo, so this runs against a local game
+install only (--game-dir or EU07_GAME_DIR), not in CI.
+
+Usage:
+ python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" # all cases
+ python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+REPO = HERE.parents[1]
+CASES_DIR = HERE / "cases"
+OUT_DIR = HERE / "out"
+
+# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp.
+# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa.
+COL_TIME = 0
+COL_VELOCITY = 1
+COL_BRAKE_PRESS = 8
+
+# settings layered over the user's eu07.ini for a test run
+TEST_INI = """\
+fullscreen no
+fullscreenwindowed no
+width 1280
+height 720
+inactivepause no
+soundenabled no
+physicslog yes
+multiplelogs no
+timespeed {timespeed}
+"""
+
+
+# ---------------------------------------------------------------- scenery
+
+
+def split_trainsets(text: str) -> tuple[str, str]:
+ """Splits text into (everything else, the trainset ... endtrainset blocks)."""
+ rest, trainsets = [], []
+ inside = False
+ for line in text.splitlines(keepends=True):
+ tokens = line.split("//", 1)[0].split()
+ if not inside and tokens and tokens[0].lower() == "trainset":
+ inside = True
+ if inside:
+ trainsets.append(line)
+ if any(t.lower() == "endtrainset" for t in tokens):
+ inside = False
+ continue
+ rest.append(line)
+ return "".join(rest), "".join(trainsets)
+
+
+def set_start_time(text: str, hhmm: str) -> str:
+ return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+
+
+def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
+ """Writes the case scenery into the game's scenery dir and returns its file name."""
+ scenery_dir = game_dir / "scenery"
+ # sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled
+ text = (scenery_dir / case["base_scenery"]).read_bytes().decode("latin-1")
+ if case.get("strip_trainsets", True):
+ text, _ = split_trainsets(text)
+ if "time" in case:
+ text = set_start_time(text, case["time"])
+ fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
+ # FirstInit binds event launchers to their events and links the tracks. so launchers and
+ # events of the case go in before it (read after it they never fire), trainsets after it
+ # (placed before it they stand on unlinked track and derail at once)
+ before, trainsets = split_trainsets(fragment)
+ header = f"\n// ---- autotest: {case_name} ----\n"
+ firstinit = re.search(r"(?im)^\s*firstinit\b", text)
+ if firstinit:
+ text = text[: firstinit.start()] + header + before + "\n" + text[firstinit.start():]
+ else:
+ text += header + before + "\n"
+ text += header + trainsets + "\n"
+ name = f"autotest_{case_name}.scn"
+ (scenery_dir / name).write_bytes(text.encode("latin-1"))
+ return name
+
+
+# ---------------------------------------------------------------- run
+
+
+def read_physicslog(path: Path) -> list[list[float]]:
+ """Returns rows of numeric columns up to BrakePress; skips the header and partial lines."""
+ rows = []
+ try:
+ lines = path.read_text(errors="replace").splitlines()
+ except FileNotFoundError:
+ return rows
+ for line in lines[1:]:
+ parts = line.split()
+ if len(parts) <= COL_BRAKE_PRESS:
+ continue # line still being written
+ try:
+ rows.append([float(p) for p in parts[: COL_BRAKE_PRESS + 1]])
+ except ValueError:
+ continue
+ return rows
+
+
+@dataclass
+class RunResult:
+ rows: list[list[float]] = field(default_factory=list)
+ exit_code: int | None = None # None: still running when we closed it (the normal end)
+ timed_out: bool = False
+ wall_seconds: float = 0.0
+
+
+def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
+ duration: float, timeout: float) -> RunResult:
+ physicslog.unlink(missing_ok=True)
+ cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ print(" $", " ".join(f'"{c}"' if " " in c else c for c in cmd))
+ started = time.monotonic()
+ proc = subprocess.Popen(cmd, cwd=game_dir)
+ result = RunResult()
+ last_report = 0.0
+ try:
+ while True:
+ time.sleep(1.0)
+ result.rows = read_physicslog(physicslog)
+ sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
+ wall = time.monotonic() - started
+ if wall - last_report >= 15:
+ v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0
+ print(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h")
+ last_report = wall
+ if proc.poll() is not None:
+ result.exit_code = proc.returncode
+ break
+ if sim_t >= duration:
+ break
+ if wall > timeout:
+ result.timed_out = True
+ break
+ finally:
+ if proc.poll() is None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ result.wall_seconds = time.monotonic() - started
+ result.rows = read_physicslog(physicslog)
+ return result
+
+
+# ---------------------------------------------------------------- checks
+
+
+def check_starts(rows, min_speed, within):
+ for r in rows:
+ if r[COL_TIME] > within:
+ break
+ if r[COL_VELOCITY] >= min_speed:
+ return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s"
+ top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0)
+ return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}"
+
+
+def check_max_speed(rows, limit, tolerance=0.0):
+ worst = max(rows, key=lambda r: r[COL_VELOCITY])
+ v, t = worst[COL_VELOCITY], worst[COL_TIME]
+ ok = v <= limit + tolerance
+ return ok, f"top speed {v:.1f} km/h at t={t:.1f}s (limit {limit} +{tolerance})"
+
+
+def _first_moving(rows, moving_speed):
+ return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None)
+
+
+def check_brakes(rows, min_pressure, moving_speed=20):
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, "never moved, so never braked"
+ for r in rows[start:]:
+ if r[COL_BRAKE_PRESS] >= min_pressure:
+ return True, f"brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
+ return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off"
+
+
+def check_stops(rows, moving_speed, stop_speed, hold):
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stopped_at = None
+ for r in rows[start:]:
+ if r[COL_VELOCITY] <= stop_speed:
+ if stopped_at is None:
+ stopped_at = r[COL_TIME]
+ if r[COL_TIME] - stopped_at >= hold:
+ return True, f"came to a stop at t={stopped_at:.1f}s"
+ else:
+ stopped_at = None
+ return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
+
+
+CHECKS = {
+ "starts": check_starts,
+ "max_speed": check_max_speed,
+ "brakes": check_brakes,
+ "stops": check_stops,
+}
+
+
+# ---------------------------------------------------------------- main
+
+
+def find_exe(explicit: str | None) -> Path:
+ if explicit:
+ return Path(explicit).resolve()
+ candidates = sorted(REPO.glob("cmake-build-*/bin/Release/eu07*.exe"), key=lambda p: p.stat().st_mtime)
+ if not candidates:
+ sys.exit("no eu07 executable found under cmake-build-*/bin/Release, pass --exe")
+ return candidates[-1]
+
+
+def count_lines(path: Path) -> int:
+ try:
+ return sum(1 for line in path.read_text(errors="replace").splitlines() if line.strip())
+ except FileNotFoundError:
+ return 0
+
+
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float) -> bool:
+ case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
+ print(f"\n=== {name}: {case.get('description', '')}")
+ out = OUT_DIR / name
+ shutil.rmtree(out, ignore_errors=True)
+ out.mkdir(parents=True)
+
+ scenery = build_scenery(case, game_dir, name)
+ ini = out / "autotest.ini"
+ ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
+ physicslog = game_dir / "physicslog" / f"{case['vehicle']}.dat"
+
+ result = run_simulator(exe, game_dir, scenery, ini, physicslog,
+ float(case["duration"]), float(case.get("timeout", 600)))
+
+ for f in ("log.txt", "errors.txt"):
+ if (game_dir / f).exists():
+ shutil.copy2(game_dir / f, out / f)
+ if physicslog.exists():
+ shutil.copy2(physicslog, out / physicslog.name)
+
+ ok = True
+ sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
+ print(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
+ if result.exit_code is not None:
+ print(f" FAIL simulator exited on its own with code {result.exit_code} (crash?)")
+ ok = False
+ if result.timed_out:
+ print(f" FAIL timed out before {case['duration']}s of simulation")
+ ok = False
+ if not result.rows:
+ print(f" FAIL no physicslog for '{case['vehicle']}' ({physicslog})")
+ return False
+
+ for check in case["checks"]:
+ params = {k: v for k, v in check.items() if k != "type"}
+ passed, detail = CHECKS[check["type"]](result.rows, **params)
+ print(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
+ ok &= passed
+
+ errors = count_lines(out / "errors.txt")
+ if errors:
+ print(f" note errors.txt has {errors} line(s)")
+ if case.get("fail_on_errors") and errors:
+ ok = False
+ return ok
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("cases", nargs="*", help="case names from cases/ (default: all)")
+ ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
+ help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
+ ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
+ ap.add_argument("--timespeed", type=float, default=1.0, help="simulation time multiplier")
+ args = ap.parse_args()
+
+ if not args.game_dir:
+ sys.exit("pass --game-dir or set EU07_GAME_DIR")
+ game_dir = Path(args.game_dir).resolve()
+ exe = find_exe(args.exe)
+ print(f"exe: {exe}\ngame: {game_dir}")
+
+ names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json"))
+ results = {n: run_case(n, exe, game_dir, args.timespeed) for n in names}
+
+ print("\n=== summary")
+ for n, ok in results.items():
+ print(f" {'PASS' if ok else 'FAIL'} {n}")
+ return 0 if all(results.values()) else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
From 6cf8934acb65aec779aea3d0f7a9604f9ef7ec15 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 19:29:10 +0200
Subject: [PATCH 023/104] test: run scenario tests at timespeed 20 by default
eu07_td_timetable now takes about 20 s instead of 4 min. Its speed profile
at 20 and 60 matched a real-time run within a few km/h and seconds; the
physicslog keeps its 0.05 s rows. The runner polls the log every 0.25 s so
it does not overshoot the case duration by a minute of simulation.
---
tests/scenarios/README.md | 5 ++++-
tests/scenarios/run.py | 7 +++++--
2 files changed, 9 insertions(+), 3 deletions(-)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 77edb5a93..c233154d6 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -18,7 +18,10 @@ Python 3.10+, no extra packages. Options:
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
`cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
-- `--timespeed 4` runs the simulation faster than real time.
+- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
+ about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
+ profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
+ `--timespeed 1` to watch a run.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
the vehicle's physicslog) land in `tests/scenarios/out//`.
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index ad1f51ee7..b3736a929 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -149,7 +149,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
last_report = 0.0
try:
while True:
- time.sleep(1.0)
+ time.sleep(0.25) # at timespeed 20 that is 5 s of simulation
result.rows = read_physicslog(physicslog)
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
wall = time.monotonic() - started
@@ -308,7 +308,10 @@ def main() -> int:
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
- ap.add_argument("--timespeed", type=float, default=1.0, help="simulation time multiplier")
+ # 20 gave the same speed profile as 1 within a few km/h and seconds on eu07_td_timetable,
+ # in 20 s instead of 4 min; 1 is for watching a run
+ ap.add_argument("--timespeed", type=float, default=20.0,
+ help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
args = ap.parse_args()
if not args.game_dir:
From cb0a1223835009fa8e82726170d4cc0afe992a41 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 21:55:16 +0200
Subject: [PATCH 024/104] test: red signal case, seven vehicles on the td.scn
timetable, parallel runs
- eu07_td_red_signal: no route set, the train has to stop before the exit
signal and stay there (new checks stays_stopped and distance; distance
is integrated from the speed, the physicslog has no position)
- en57/ep09/et22/sm42/sn61/vectron/eu07_td_timetable share one fragment
template, td_timetable.scn; a case sets vars.consist and the lead vehicle
is named {{vehicle}} = autotest_
- -j N runs cases in parallel: each case has its own physicslog and, with
multiplelogs, its own log files, which are moved to out//
- a run stops at once on Bad vehicle / Bad trainset instead of waiting for
the timeout, and fails after 120 s without physicslog rows
- the .sbt geometry cache of a test scenery is dropped when the base
scenery is newer
All 8 cases pass in about a minute with -j 4.
---
tests/scenarios/README.md | 35 ++-
tests/scenarios/cases/en57_td_timetable.json | 21 ++
tests/scenarios/cases/ep09_td_timetable.json | 17 ++
tests/scenarios/cases/et22_td_timetable.json | 17 ++
tests/scenarios/cases/eu07_td_red_signal.json | 18 ++
tests/scenarios/cases/eu07_td_timetable.json | 6 +-
tests/scenarios/cases/sm42_td_timetable.json | 17 ++
tests/scenarios/cases/sn61_td_timetable.json | 17 ++
tests/scenarios/cases/td_red_signal.scn | 6 +
...eu07_td_timetable.scn => td_timetable.scn} | 9 +-
.../scenarios/cases/vectron_td_timetable.json | 17 ++
tests/scenarios/run.py | 201 ++++++++++++++----
12 files changed, 332 insertions(+), 49 deletions(-)
create mode 100644 tests/scenarios/cases/en57_td_timetable.json
create mode 100644 tests/scenarios/cases/ep09_td_timetable.json
create mode 100644 tests/scenarios/cases/et22_td_timetable.json
create mode 100644 tests/scenarios/cases/eu07_td_red_signal.json
create mode 100644 tests/scenarios/cases/sm42_td_timetable.json
create mode 100644 tests/scenarios/cases/sn61_td_timetable.json
create mode 100644 tests/scenarios/cases/td_red_signal.scn
rename tests/scenarios/cases/{eu07_td_timetable.scn => td_timetable.scn} (51%)
create mode 100644 tests/scenarios/cases/vectron_td_timetable.json
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index c233154d6..23f793018 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -9,7 +9,7 @@ only, not in CI.
## Running
```
-python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna"
+python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna" -j 4
```
Python 3.10+, no extra packages. Options:
@@ -18,13 +18,15 @@ Python 3.10+, no extra packages. Options:
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
`cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
+- `-j N` runs N cases at once, each in its own simulator window. Each case prints its
+ results when it is done. All 8 cases take about a minute with `-j 4`.
- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
`--timespeed 1` to watch a run.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
-the vehicle's physicslog) land in `tests/scenarios/out//`.
+the vehicle's physicslog) are moved to `tests/scenarios/out//`.
## How it works
@@ -35,11 +37,19 @@ For each case the runner:
fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
in for keys the scenery expects a player to press, extra events) before it,
2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
- ghostview leaves every train to the AI, and the extra ini turns on `physicslog`,
- runs in a 1280x720 window and does not pause when the window loses focus,
-3. waits until `physicslog/.dat` covers `duration` seconds, then closes the simulator,
+ ghostview leaves every train to the AI, and the extra ini turns on `physicslog`, runs in a
+ 1280x720 window, does not pause when the window loses focus, and writes the logs to
+ `logs/log (autotest_) .txt` rather than the shared `log.txt` (`multiplelogs`),
+3. waits until `physicslog/autotest_.dat` covers `duration` seconds, then closes the
+ simulator. It gives up early when the log reports `Bad vehicle` / `Bad trainset`, or when
+ the scenario has loaded and no physicslog appeared,
4. runs the checks on the physicslog.
+The lead vehicle is named `autotest_`, so every case has its own physicslog and log
+files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt`
+geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base
+scenery is newer.
+
## Writing a case
`cases/.json`:
@@ -50,13 +60,19 @@ For each case the runner:
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
-| `vehicle` | node name of the vehicle whose physicslog is checked |
+| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
| `duration` | seconds of simulation to record |
| `timeout` | wall-clock seconds before giving up, loading included |
| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
| `checks` | list of checks, below |
-Checks (speeds in km/h, times in seconds of physicslog time):
+`{{vehicle}}` is always set, also inside `vars` values: the node name of the lead vehicle,
+the one whose physicslog is checked. Other vehicles of the consist take names made from it,
+e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
+train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
+only in `vars.consist`.
+
+Checks (speeds in km/h, times in seconds of physicslog time, distances in metres):
- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
@@ -64,6 +80,11 @@ Checks (speeds in km/h, times in seconds of physicslog time):
(physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0).
- `stops` `moving_speed`, `stop_speed`, `hold`: after reaching `moving_speed`, stays at or
below `stop_speed` for `hold` seconds.
+- `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes
+ above `stop_speed` again.
+- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the
+ distance comes from integrating the speed; on td.scn every vehicle's first stop after
+ Stacja1 came out at 1400 m (+-3), and the red signal stop at 140 m.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/en57_td_timetable.json b/tests/scenarios/cases/en57_td_timetable.json
new file mode 100644
index 000000000..ddd52af37
--- /dev/null
+++ b/tests/scenarios/cases/en57_td_timetable.json
@@ -0,0 +1,21 @@
+{
+ "description": "EN57 EMU (three cars) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": [
+ "node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic",
+ "node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic",
+ "node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/ep09_td_timetable.json b/tests/scenarios/cases/ep09_td_timetable.json
new file mode 100644
index 000000000..dd130be3c
--- /dev/null
+++ b/tests/scenarios/cases/ep09_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "EP09 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\ep09_v1 104e-005 104e_3 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/et22_td_timetable.json b/tests/scenarios/cases/et22_td_timetable.json
new file mode 100644
index 000000000..004f5354d
--- /dev/null
+++ b/tests/scenarios/cases/et22_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "ET22 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_red_signal.json b/tests/scenarios/cases/eu07_td_red_signal.json
new file mode 100644
index 000000000..b02acdc81
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_red_signal.json
@@ -0,0 +1,18 @@
+{
+ "description": "EU07 on td.scn with no route set: pulls off, stops before the exit signal stacja1_j at stop, and stays there.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 5, "within": 150 },
+ { "type": "max_speed", "limit": 40 },
+ { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 },
+ { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 },
+ { "type": "distance", "max": 150 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json
index c12b8ae71..2f23019fe 100644
--- a/tests/scenarios/cases/eu07_td_timetable.json
+++ b/tests/scenarios/cases/eu07_td_timetable.json
@@ -2,8 +2,10 @@
"description": "EU07 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
"base_scenery": "td.scn",
"time": "10:34",
- "fragment": "eu07_td_timetable.scn",
- "vehicle": "autotest_eu07",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
"duration": 240,
"timeout": 600,
"checks": [
diff --git a/tests/scenarios/cases/sm42_td_timetable.json b/tests/scenarios/cases/sm42_td_timetable.json
new file mode 100644
index 000000000..fc89be0fa
--- /dev/null
+++ b/tests/scenarios/cases/sm42_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "SM42 diesel shunter on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json
new file mode 100644
index 000000000..1db425c80
--- /dev/null
+++ b/tests/scenarios/cases/sn61_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "SN61 diesel railcar on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/td_red_signal.scn b/tests/scenarios/cases/td_red_signal.scn
new file mode 100644
index 000000000..981707085
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal.scn
@@ -0,0 +1,6 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// same start as td_timetable.scn, but nobody sets the route: the exit signal stacja1_j,
+// about 150 m ahead of the train, stays at stop.
+trainset td/rozklad tdo_n1734 0.0 0.1
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/cases/eu07_td_timetable.scn b/tests/scenarios/cases/td_timetable.scn
similarity index 51%
rename from tests/scenarios/cases/eu07_td_timetable.scn
rename to tests/scenarios/cases/td_timetable.scn
index c8044e467..e67dcf9ad 100644
--- a/tests/scenarios/cases/eu07_td_timetable.scn
+++ b/tests/scenarios/cases/td_timetable.scn
@@ -1,11 +1,12 @@
-// added by tests/scenarios/run.py to the base scenery, whose own trainsets were removed:
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed:
// the trainset goes after FirstInit, the launcher before it.
-// the EU07 stands where td.scn keeps its timetable train and gets the same timetable.
+// the case's consist stands where td.scn keeps its timetable train (track 1 of Stacja1)
+// and gets the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2.
trainset td/rozklad tdo_n1734 0.0 0.1
-node -1 0 autotest_eu07 dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic
+{{consist}}
endtrainset
// td.scn sets routes from the keyboard (shift+1..4 run events keyctrl01..04). keyctrl04 is the
-// way out of the track the train stands on: switch zwr02 and the exit signal stacja1_j at 40.
+// way out of track 1: switch zwr02 and the exit signal stacja1_j at 40.
// a launcher with a positive time fires once at that hour (HHMM), radius -1 means anywhere.
node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end
diff --git a/tests/scenarios/cases/vectron_td_timetable.json b/tests/scenarios/cases/vectron_td_timetable.json
new file mode 100644
index 000000000..9948a09ef
--- /dev/null
+++ b/tests/scenarios/cases/vectron_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "Vectron 1293-107 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index b3736a929..419906700 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -2,11 +2,11 @@
"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
A case (cases/.json) names a base scenery from the game install, a fragment
-appended to it (usually a trainset with an AI driver), and checks on the vehicle's
+added to it (usually a trainset with an AI driver), and checks on the vehicle's
physics log. The runner:
1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
- trainsets removed, optionally a different start time, and the case fragment appended,
+ trainsets removed, optionally a different start time, and the case fragment added,
2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
settings file (-ini) that turns on physicslog and runs in a window,
3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
@@ -14,10 +14,10 @@ physics log. The runner:
4. evaluates the checks on the log and prints PASS/FAIL per check.
Scenery and vehicle data are not part of this repo, so this runs against a local game
-install only (--game-dir or EU07_GAME_DIR), not in CI.
+install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md.
Usage:
- python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" # all cases
+ python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" -j 4 # all cases
python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases
"""
@@ -31,6 +31,7 @@ import shutil
import subprocess
import sys
import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
@@ -54,9 +55,11 @@ height 720
inactivepause no
soundenabled no
physicslog yes
-multiplelogs no
+multiplelogs yes
timespeed {timespeed}
"""
+# multiplelogs: log and errors go to logs/log () .txt instead of the shared
+# log.txt, so runs of different cases can go in parallel
# ---------------------------------------------------------------- scenery
@@ -83,7 +86,19 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
-def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
+def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str:
+ """Replaces {{name}} with the case's value; a list value becomes one line per item."""
+ def value(m):
+ if m.group(1) in keep:
+ return m.group(0)
+ v = values.get(m.group(1))
+ if v is None:
+ sys.exit(f"fragment uses {{{{{m.group(1)}}}}} but the case sets no such var")
+ return "\n".join(v) if isinstance(v, list) else str(v)
+ return re.sub(r"\{\{(\w+)\}\}", value, fragment)
+
+
+def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str:
"""Writes the case scenery into the game's scenery dir and returns its file name."""
scenery_dir = game_dir / "scenery"
# sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled
@@ -93,6 +108,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
if "time" in case:
text = set_start_time(text, case["time"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
+ # vars first: {{vehicle}} inside a var's value gets filled in the second pass
+ fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
+ fragment = fill_vars(fragment, {"vehicle": vehicle})
# FirstInit binds event launchers to their events and links the tracks. so launchers and
# events of the case go in before it (read after it they never fire), trainsets after it
# (placed before it they stand on unlinked track and derail at once)
@@ -106,6 +124,12 @@ def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
text += header + trainsets + "\n"
name = f"autotest_{case_name}.scn"
(scenery_dir / name).write_bytes(text.encode("latin-1"))
+ # the simulator caches the scenery's static geometry in .sbt and reads it instead of
+ # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so
+ # drop the cache once the base scenery has changed
+ cache = scenery_dir / f"autotest_{case_name}.sbt"
+ if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime:
+ cache.unlink()
return name
@@ -130,19 +154,47 @@ def read_physicslog(path: Path) -> list[list[float]]:
return rows
+def find_logs(game_dir: Path, scenery: str, since: float) -> dict[str, Path]:
+ """The log.txt / errors.txt of one run; with multiplelogs each scenery gets its own files."""
+ stem = scenery.rsplit(".", 1)[0]
+ found = {}
+ for kind in ("log", "errors"):
+ files = [p for p in (game_dir / "logs").glob(f"{kind} ({stem}) *.txt") if p.stat().st_mtime >= since]
+ if files:
+ found[kind] = max(files, key=lambda p: p.stat().st_mtime)
+ return found
+
+
+def read_text(path: Path | None) -> str:
+ try:
+ return path.read_text(errors="replace") if path else ""
+ except FileNotFoundError:
+ return ""
+
+
+# load problems that leave the case without its vehicle; no point waiting for the timeout
+FATAL_LOG_LINES = ("Bad vehicle:", "Bad trainset:")
+# wall seconds from start to the first physicslog row before giving up. "Scenario loading
+# time" in the log is not the end of loading (the trainsets after FirstInit still follow),
+# and with several simulators loading at once the first rows took well over 15 s
+STARTUP_TIMEOUT = 120.0
+
+
@dataclass
class RunResult:
rows: list[list[float]] = field(default_factory=list)
exit_code: int | None = None # None: still running when we closed it (the normal end)
- timed_out: bool = False
+ failure: str = "" # why the run was cut short
wall_seconds: float = 0.0
+ logs: dict[str, Path] = field(default_factory=dict)
def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
- duration: float, timeout: float) -> RunResult:
+ duration: float, timeout: float, say) -> RunResult:
physicslog.unlink(missing_ok=True)
cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
- print(" $", " ".join(f'"{c}"' if " " in c else c for c in cmd))
+ say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True)
+ since = time.time() - 1
started = time.monotonic()
proc = subprocess.Popen(cmd, cwd=game_dir)
result = RunResult()
@@ -150,12 +202,12 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
try:
while True:
time.sleep(0.25) # at timespeed 20 that is 5 s of simulation
+ wall = time.monotonic() - started
result.rows = read_physicslog(physicslog)
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
- wall = time.monotonic() - started
if wall - last_report >= 15:
v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0
- print(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h")
+ say(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h", progress=True)
last_report = wall
if proc.poll() is not None:
result.exit_code = proc.returncode
@@ -163,8 +215,18 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
if sim_t >= duration:
break
if wall > timeout:
- result.timed_out = True
+ result.failure = f"timed out after {timeout:.0f}s before {duration}s of simulation"
break
+ if not result.rows:
+ result.logs = find_logs(game_dir, scenery, since)
+ fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines()
+ if any(k in l for k in FATAL_LOG_LINES)]
+ if fatal:
+ result.failure = "vehicle failed to load: " + " | ".join(fatal)
+ break
+ if wall > STARTUP_TIMEOUT:
+ result.failure = f"no physicslog rows after {STARTUP_TIMEOUT:.0f}s"
+ break
finally:
if proc.poll() is None:
proc.terminate()
@@ -174,6 +236,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
proc.kill()
result.wall_seconds = time.monotonic() - started
result.rows = read_physicslog(physicslog)
+ result.logs = find_logs(game_dir, scenery, since)
return result
@@ -201,6 +264,15 @@ def _first_moving(rows, moving_speed):
return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None)
+def _distances(rows):
+ """Metres travelled up to each row, from the speed; the physicslog has no position."""
+ out, d = [0.0], 0.0
+ for a, b in zip(rows, rows[1:]):
+ d += (a[COL_VELOCITY] + b[COL_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME])
+ out.append(d)
+ return out
+
+
def check_brakes(rows, min_pressure, moving_speed=20):
start = _first_moving(rows, moving_speed)
if start is None:
@@ -215,23 +287,49 @@ def check_stops(rows, moving_speed, stop_speed, hold):
start = _first_moving(rows, moving_speed)
if start is None:
return False, f"never reached {moving_speed} km/h"
+ dist = _distances(rows)
stopped_at = None
- for r in rows[start:]:
+ for i in range(start, len(rows)):
+ r = rows[i]
if r[COL_VELOCITY] <= stop_speed:
if stopped_at is None:
- stopped_at = r[COL_TIME]
- if r[COL_TIME] - stopped_at >= hold:
- return True, f"came to a stop at t={stopped_at:.1f}s"
+ stopped_at = i
+ if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold:
+ return True, f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {dist[stopped_at]:.0f} m"
else:
stopped_at = None
return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
+def check_stays_stopped(rows, moving_speed, stop_speed):
+ """Once stopped after moving off, never moves again (e.g. waiting at a red signal)."""
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if rows[i][COL_VELOCITY] <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ moved = next((r for r in rows[stop:] if r[COL_VELOCITY] > stop_speed), None)
+ if moved is not None:
+ return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s but moved again at t={moved[COL_TIME]:.1f}s, v={moved[COL_VELOCITY]:.1f} km/h"
+ return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s and stayed until t={rows[-1][COL_TIME]:.1f}s"
+
+
+def check_distance(rows, max=None, min=None):
+ """Total distance travelled, in metres."""
+ d = _distances(rows)[-1]
+ ok = (max is None or d <= max) and (min is None or d >= min)
+ bounds = " ".join(s for s in (f">= {min}" if min is not None else "", f"<= {max}" if max is not None else "") if s)
+ return ok, f"travelled {d:.0f} m (wanted {bounds})"
+
+
CHECKS = {
"starts": check_starts,
"max_speed": check_max_speed,
"brakes": check_brakes,
"stops": check_stops,
+ "stays_stopped": check_stays_stopped,
+ "distance": check_distance,
}
@@ -254,49 +352,52 @@ def count_lines(path: Path) -> int:
return 0
-def run_case(name: str, exe: Path, game_dir: Path, timespeed: float) -> bool:
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> bool:
case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
- print(f"\n=== {name}: {case.get('description', '')}")
+ say(f"\n=== {name}: {case.get('description', '')}")
out = OUT_DIR / name
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
- scenery = build_scenery(case, game_dir, name)
+ # the lead vehicle is named after the case, so parallel runs never share a physicslog
+ vehicle = f"autotest_{name}"
+ scenery = build_scenery(case, game_dir, name, vehicle)
ini = out / "autotest.ini"
ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
- physicslog = game_dir / "physicslog" / f"{case['vehicle']}.dat"
+ physicslog = game_dir / "physicslog" / f"{vehicle}.dat"
result = run_simulator(exe, game_dir, scenery, ini, physicslog,
- float(case["duration"]), float(case.get("timeout", 600)))
+ float(case["duration"]), float(case.get("timeout", 600)), say)
- for f in ("log.txt", "errors.txt"):
- if (game_dir / f).exists():
- shutil.copy2(game_dir / f, out / f)
+ # the logs are ours alone (named after the case scenery), move them out of the game dir
+ for kind, path in result.logs.items():
+ shutil.move(path, out / f"{kind}.txt")
if physicslog.exists():
- shutil.copy2(physicslog, out / physicslog.name)
+ shutil.move(physicslog, out / physicslog.name)
ok = True
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
- print(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
+ say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
if result.exit_code is not None:
- print(f" FAIL simulator exited on its own with code {result.exit_code} (crash?)")
+ say(f" FAIL simulator exited on its own with code {result.exit_code}")
ok = False
- if result.timed_out:
- print(f" FAIL timed out before {case['duration']}s of simulation")
+ if result.failure:
+ say(f" FAIL {result.failure}")
ok = False
if not result.rows:
- print(f" FAIL no physicslog for '{case['vehicle']}' ({physicslog})")
+ if not result.failure:
+ say(f" FAIL no physicslog for '{vehicle}'")
return False
for check in case["checks"]:
params = {k: v for k, v in check.items() if k != "type"}
passed, detail = CHECKS[check["type"]](result.rows, **params)
- print(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
+ say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
ok &= passed
errors = count_lines(out / "errors.txt")
if errors:
- print(f" note errors.txt has {errors} line(s)")
+ say(f" note errors.txt has {errors} line(s)")
if case.get("fail_on_errors") and errors:
ok = False
return ok
@@ -312,6 +413,8 @@ def main() -> int:
# in 20 s instead of 4 min; 1 is for watching a run
ap.add_argument("--timespeed", type=float, default=20.0,
help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
+ ap.add_argument("-j", "--jobs", type=int, default=1,
+ help="cases run at once, each in its own simulator window (default 1)")
args = ap.parse_args()
if not args.game_dir:
@@ -321,11 +424,37 @@ def main() -> int:
print(f"exe: {exe}\ngame: {game_dir}")
names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json"))
- results = {n: run_case(n, exe, game_dir, args.timespeed) for n in names}
+ missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()]
+ if missing:
+ sys.exit("no such case: " + ", ".join(missing))
- print("\n=== summary")
- for n, ok in results.items():
- print(f" {'PASS' if ok else 'FAIL'} {n}")
+ started = time.monotonic()
+ results = {}
+ if args.jobs <= 1:
+ def say(line, progress=False):
+ print(line, flush=True)
+ for n in names:
+ results[n] = run_case(n, exe, game_dir, args.timespeed, say)
+ else:
+ # each case prints its block when it is done, so parallel output does not interleave
+ def job(n):
+ lines = []
+ def say(line, progress=False):
+ if not progress:
+ lines.append(line)
+ ok = run_case(n, exe, game_dir, args.timespeed, say)
+ return n, ok, lines
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
+ for n in names:
+ print(f"started {n}", flush=True)
+ for fut in as_completed([pool.submit(job, n) for n in names]):
+ n, ok, lines = fut.result()
+ print("\n".join(lines), flush=True)
+ results[n] = ok
+
+ print(f"\n=== summary ({time.monotonic() - started:.0f}s)")
+ for n in names:
+ print(f" {'PASS' if results[n] else 'FAIL'} {n}")
return 0 if all(results.values()) else 1
From 219836b4648020de36f1ccf7dc7d7edc71b8e2a6 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 13:55:06 +0200
Subject: [PATCH 025/104] test: track_friction case key for slippery rail
scenarios
---
tests/scenarios/README.md | 1 +
tests/scenarios/run.py | 8 ++++++++
2 files changed, 9 insertions(+)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 23f793018..463086cc5 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -59,6 +59,7 @@ scenery is newer.
| `base_scenery` | scenery file in the game's `scenery/` dir |
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
+| `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
| `duration` | seconds of simulation to record |
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 419906700..32be5dfc0 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -86,6 +86,12 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+def set_track_friction(text: str, friction: float) -> str:
+ """Sets the friction of every track: node track ..."""
+ return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+",
+ lambda m: m.group(1) + f"{friction}", text)
+
+
def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str:
"""Replaces {{name}} with the case's value; a list value becomes one line per item."""
def value(m):
@@ -107,6 +113,8 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
text, _ = split_trainsets(text)
if "time" in case:
text = set_start_time(text, case["time"])
+ if "track_friction" in case:
+ text = set_track_friction(text, case["track_friction"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
# vars first: {{vehicle}} inside a var's value gets filled in the second pass
fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
From fe9e2f77c24f71d965fd3d6c11478840c6f659e8 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 14:11:54 +0200
Subject: [PATCH 026/104] feat(log): vehicle speed column in the physicslog
The Velocity column is the wheel speed, which stays at 0 while the wheels
are locked in a skid, so a vehicle sliding on locked wheels looked as if
it stood still. Add the signed vehicle speed in km/h as the last column.
---
vehicle/Driver.cpp | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..c5f5f51e9 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -1880,7 +1880,8 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche,
<< "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] "
<< "MCP SCP BCP LBP Direction Command CVal1 CVal2 "
<< "Security Wheelslip "
- << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]"
+ << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] "
+ << "VehicleVelocity[km/h]"
<< "\r\n";
LogFile << std::fixed << std::setprecision( 4 );
#endif
@@ -4817,7 +4818,9 @@ void TController::PhysicsLog()
<< mvControlling->dizel_heat.Ts << " "
<< mvControlling->dizel_heat.To << " "
<< mvControlling->dizel_heat.temperatura1 << " "
- << mvControlling->dizel_heat.temperatura2
+ << mvControlling->dizel_heat.temperatura2 << " "
+ // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid
+ << mvOccupied->V * 3.6
<< "\r\n";
#endif
#if LOGPRESS == 1
From 6209e165583b841b61d4ec9a99b2d69b2e0db5c2 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 14:11:54 +0200
Subject: [PATCH 027/104] test: slippery rail skid cases, wheelslip and vehicle
speed checks
- physicslog rows keep all columns (text ones as None), checks can read
the wheelslip flag and the new vehicle speed column
- slips: the lead vehicle's wheels slip at some point (makes sure a
slippery rail case does what it's meant to)
- slip_clears: once stopped, the wheels stop slipping within N seconds
- holds_still: once stopped, the vehicle doesn't creep, by vehicle speed
- td_red_signal_moving.scn: the red signal case starting already moving
- eu07_slippery_red_signal / eu07_slippery_push_red_signal: skid on
braking for the red signal with track friction 0.03; the pushing one
fails without the fix for eu07/maszyna#479 (stays skidding, creeps)
- sn61_td_timetable: stop hold 5 -> 2 s, the railcar arrives 5-7 s
before its departure time, so 5 s made the case flaky
---
tests/scenarios/README.md | 14 +++-
.../cases/eu07_slippery_push_red_signal.json | 36 ++++++++++
.../cases/eu07_slippery_red_signal.json | 36 ++++++++++
tests/scenarios/cases/sn61_td_timetable.json | 2 +-
.../scenarios/cases/td_red_signal_moving.scn | 6 ++
tests/scenarios/run.py | 68 ++++++++++++++++++-
6 files changed, 156 insertions(+), 6 deletions(-)
create mode 100644 tests/scenarios/cases/eu07_slippery_push_red_signal.json
create mode 100644 tests/scenarios/cases/eu07_slippery_red_signal.json
create mode 100644 tests/scenarios/cases/td_red_signal_moving.scn
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 463086cc5..4600a3577 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -71,9 +71,13 @@ scenery is newer.
the one whose physicslog is checked. Other vehicles of the consist take names made from it,
e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
-only in `vars.consist`.
+only in `vars.consist`. `td_red_signal_moving.scn` is the red signal one with the train
+starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking.
-Checks (speeds in km/h, times in seconds of physicslog time, distances in metres):
+Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
+the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
+locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of
+the row instead, logged by builds from this branch on.
- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
@@ -86,6 +90,12 @@ Checks (speeds in km/h, times in seconds of physicslog time, distances in metres
- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the
distance comes from integrating the speed; on td.scn every vehicle's first stop after
Stacja1 came out at 1400 m (+-3), and the red signal stop at 140 m.
+- `slips` `within`: the lead vehicle's wheels slip or lock at some point (within `within`
+ seconds if given), so a slippery rail case does what it's meant to.
+- `slip_clears` `moving_speed`, `stop_speed`, `within` (*vehicle speed*): once stopped after
+ moving off, the wheels stop slipping within `within` seconds.
+- `holds_still` `moving_speed`, `stop_speed`, `max_distance` (*vehicle speed*): once stopped
+ after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/eu07_slippery_push_red_signal.json b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
new file mode 100644
index 000000000..f7ae10bb7
--- /dev/null
+++ b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
@@ -0,0 +1,36 @@
+{
+ "description": "EU07 pushing three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids. Pushed by the train it doesn't roll back at the stop, so it used to stay skidding on locked wheels with the brakes capped by the sliding adhesion and creep (eu07/maszyna#479).",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "track_friction": 0.03,
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "30",
+ "consist": [
+ "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 900,
+ "checks": [
+ {
+ "type": "slips",
+ "within": 60
+ },
+ {
+ "type": "slip_clears",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "within": 5
+ },
+ {
+ "type": "holds_still",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "max_distance": 0.01
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_slippery_red_signal.json b/tests/scenarios/cases/eu07_slippery_red_signal.json
new file mode 100644
index 000000000..40b5944eb
--- /dev/null
+++ b/tests/scenarios/cases/eu07_slippery_red_signal.json
@@ -0,0 +1,36 @@
+{
+ "description": "EU07 with three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids, then the skid ends and the train holds still.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "track_friction": 0.03,
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "30",
+ "consist": [
+ "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic",
+ "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 900,
+ "checks": [
+ {
+ "type": "slips",
+ "within": 60
+ },
+ {
+ "type": "slip_clears",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "within": 5
+ },
+ {
+ "type": "holds_still",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "max_distance": 0.01
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json
index 1db425c80..9fa4b18d8 100644
--- a/tests/scenarios/cases/sn61_td_timetable.json
+++ b/tests/scenarios/cases/sn61_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 2 }
]
}
diff --git a/tests/scenarios/cases/td_red_signal_moving.scn b/tests/scenarios/cases/td_red_signal_moving.scn
new file mode 100644
index 000000000..648e5d90a
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal_moving.scn
@@ -0,0 +1,6 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop),
+// but the train starts already moving at {{velocity}} km/h, so it has to brake right away.
+trainset td/rozklad tdo_n1734 0.0 {{velocity}}
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 32be5dfc0..2cd754a06 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -43,8 +43,11 @@ OUT_DIR = HERE / "out"
# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp.
# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa.
COL_TIME = 0
-COL_VELOCITY = 1
+COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid
COL_BRAKE_PRESS = 8
+COL_COMMAND = 16 # text, read as None
+COL_WHEELSLIP = 20
+COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
# settings layered over the user's eu07.ini for a test run
TEST_INI = """\
@@ -145,7 +148,7 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
def read_physicslog(path: Path) -> list[list[float]]:
- """Returns rows of numeric columns up to BrakePress; skips the header and partial lines."""
+ """Returns rows of columns, None for the text ones; skips the header and partial lines."""
rows = []
try:
lines = path.read_text(errors="replace").splitlines()
@@ -156,9 +159,15 @@ def read_physicslog(path: Path) -> list[list[float]]:
if len(parts) <= COL_BRAKE_PRESS:
continue # line still being written
try:
- rows.append([float(p) for p in parts[: COL_BRAKE_PRESS + 1]])
+ row = [float(p) for p in parts[: COL_BRAKE_PRESS + 1]]
except ValueError:
continue
+ for p in parts[COL_BRAKE_PRESS + 1:]:
+ try:
+ row.append(float(p))
+ except ValueError:
+ row.append(None)
+ rows.append(row)
return rows
@@ -331,7 +340,60 @@ def check_distance(rows, max=None, min=None):
return ok, f"travelled {d:.0f} m (wanted {bounds})"
+def check_slips(rows, within=None):
+ """The lead vehicle's wheels slip (or lock in a skid) at some point, e.g. to make sure a slippery rail case does what it's meant to."""
+ for r in rows:
+ if within is not None and r[COL_TIME] > within:
+ break
+ if len(r) > COL_WHEELSLIP and r[COL_WHEELSLIP]:
+ return True, f"wheels slipping at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
+ return False, "the wheels never slipped"
+
+
+def check_holds_still(rows, moving_speed, stop_speed, max_distance):
+ """Once stopped after moving off, the vehicle doesn't creep. Uses the vehicle speed rather than the
+ wheel speed, so it also catches a vehicle sliding on locked wheels."""
+ if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
+ return False, "the physicslog has no vehicle speed column, the build is too old"
+ speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows]
+ start = next((i for i, v in enumerate(speed) if v >= moving_speed), None)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if speed[i] <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ d, top, top_t = 0.0, 0.0, rows[stop][COL_TIME]
+ for i in range(stop + 1, len(rows)):
+ d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME])
+ if speed[i] > top:
+ top, top_t = speed[i], rows[i][COL_TIME]
+ held = rows[-1][COL_TIME] - rows[stop][COL_TIME]
+ detail = f"stopped at t={rows[stop][COL_TIME]:.1f}s, then moved {d:.3f} m in {held:.0f}s, top {top:.4f} km/h at t={top_t:.1f}s"
+ return d <= max_distance, detail
+
+
+def check_slip_clears(rows, moving_speed, stop_speed, within):
+ """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds
+ (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion)."""
+ if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
+ return False, "the physicslog has no vehicle speed column, the build is too old"
+ start = next((i for i, r in enumerate(rows) if abs(r[COL_VEHICLE_VELOCITY]) >= moving_speed), None)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if abs(rows[i][COL_VEHICLE_VELOCITY]) <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ deadline = rows[stop][COL_TIME] + within
+ late = [r for r in rows[stop:] if r[COL_TIME] > deadline and r[COL_WHEELSLIP]]
+ if late:
+ return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s, wheels still slipping at t={late[0][COL_TIME]:.1f}s ({len(late)} rows after the {within}s grace)"
+ return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s"
+
+
CHECKS = {
+ "slips": check_slips,
+ "slip_clears": check_slip_clears,
+ "holds_still": check_holds_still,
"starts": check_starts,
"max_speed": check_max_speed,
"brakes": check_brakes,
From 02e29f69712d1e02e960c14eba32feb1a3245ab3 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 13:17:26 +0100
Subject: [PATCH 028/104] feat(simulation): test mode, --test runs a scenery
unattended and exits with the result (eu07/maszyna#541)
eu07 --test -s [--test-timeout ] runs the scenery in ghostview with
the null renderer (models loaded, no textures), a hidden window, no sound,
network or python, and in fixed steps of 0.03 s of simulation time per frame
(three 10 ms physics steps) as fast as it can. Without -seed it uses a fixed
seed, so two runs give byte-identical physicslogs.
The scenery reports its result to the __test.result memory cell, which the
simulator always creates: value 1 passes once every vehicle has stood still for
1 s, value 0 fails at once. The run ends with exit code
0 pass, 1 fail,
2 a train passed a signal at stop (SetVelocity 0 0, as seen in its driver's
speed table; SetVelocity 0 x on automatic block doesn't count),
3 timeout (test.timeout, default 3600 s of simulation time),
4 standstill (every vehicle still for test.standstill s, default 300, with no
result; a pass with test.pass_on_standstill yes),
5 error (no -s, the scenery didn't load or has no vehicles, an exception).
The test.* keys go in the scenery's config block; test.fail_if_stop_overran no
only logs a signal passed at danger. Outside the test mode a signal passed at
danger is logged.
The null renderer gets a ui backend which draws nothing, hands out the null
texture and material instead of throwing, and ends the ui frame. A GL context
is still made for the hidden window, without asking for a version, as parts
of the ui create textures with gl calls of their own. No crash dialog or
message box in test mode; the window code no longer needs a monitor.
---
CMakeLists.txt | 1 +
EU07.cpp | 17 +++-
application/application.cpp | 82 +++++++++++++---
application/drivermode.cpp | 13 +++
application/scenarioloadermode.cpp | 10 ++
rendering/nullrenderer.cpp | 19 ++++
rendering/nullrenderer.h | 30 ++++--
simulation/simulation.cpp | 3 +
simulation/simulationtest.cpp | 149 +++++++++++++++++++++++++++++
simulation/simulationtest.h | 66 +++++++++++++
utilities/Globals.cpp | 37 +++++++
utilities/Globals.h | 10 ++
utilities/Timer.cpp | 13 ++-
utilities/Timer.h | 3 +
vehicle/Driver.cpp | 29 +++++-
vehicle/Driver.h | 2 +
16 files changed, 458 insertions(+), 26 deletions(-)
create mode 100644 simulation/simulationtest.cpp
create mode 100644 simulation/simulationtest.h
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6f34ad61f..8a4e1d6ea 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -160,6 +160,7 @@ set(SOURCES
"world/station.cpp"
"application/application.cpp"
"simulation/simulationtime.cpp"
+"simulation/simulationtest.cpp"
"scene/sceneeditor.cpp"
"rendering/screenshot.cpp"
"input/driverkeyboardinput.cpp"
diff --git a/EU07.cpp b/EU07.cpp
index e03618297..aac7cae11 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -19,6 +19,8 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "stdafx.h"
#include "application/application.h"
+#include "simulation/simulationtest.h"
+#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include
#ifdef WITHDUMPGEN
@@ -148,9 +150,14 @@ int main(int argc, char *argv[])
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
- std::string msg = "Simulator crash occured :(\n";
- msg += Error.what();
- MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
+ ErrorLog("Critical error: " + std::string(Error.what()));
+ // in test mode nobody is there to close the box, the exit code tells of the error
+ if (false == Global.test.enabled)
+ {
+ std::string msg = "Simulator crash occured :(\n";
+ msg += Error.what();
+ MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
+ }
}
#endif
}
@@ -158,5 +165,7 @@ int main(int argc, char *argv[])
fflush(stdout);
fflush(stderr);
#endif
- std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults
+ // skip destructors, there are ordering errors which causes segfaults
+ // a test run (--test) says its result in the exit code
+ std::_Exit(Global.test.enabled ? simulation::Test.exit_code() : 0);
}
diff --git a/application/application.cpp b/application/application.cpp
index ee381f98b..37afff67f 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -378,7 +378,7 @@ int eu07_application::init(int Argc, char *Argv[])
return result;
}
- if (crashreport_is_pending())
+ if (crashreport_is_pending() && false == Global.test.enabled)
{ // run crashgui as early as possible
if ((result = run_crashgui()) != 0)
{
@@ -951,14 +951,17 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi
}
// for index -1 create a new child window
- auto const *vmode{glfwGetVideoMode(monitor ? monitor : glfwGetPrimaryMonitor())};
-
- // match requested video mode to current to allow for
- // fullwindow creation when resolution is the same
- glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
- glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
- glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
- glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
+ auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()};
+ // a machine without a display (e.g. a test runner) has no monitor to match
+ if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr})
+ {
+ // match requested video mode to current to allow for
+ // fullwindow creation when resolution is the same
+ glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
+ glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
+ glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
+ glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
+ }
glfwWindowHint(GLFW_VISIBLE, visible);
@@ -1195,6 +1198,19 @@ int eu07_application::init_settings(int Argc, char *Argv[])
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
}
}
+ else if (token == "--test")
+ {
+ // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541)
+ Global.test.enabled = true;
+ }
+ else if (token == "--test-timeout")
+ {
+ if (i + 1 < Argc)
+ {
+ Global.test.timeout = std::max(0.0, std::atof(Argv[++i]));
+ Global.test.timeout_from_command_line = true;
+ }
+ }
else if (token == "-ini")
{
// extra settings file read on top of eu07.ini, so a run can override a few keys
@@ -1210,13 +1226,45 @@ int eu07_application::init_settings(int Argc, char *Argv[])
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
<< " [-seed number|word]"
- << " [-ini settingsfile]" << std::endl;
+ << " [-ini settingsfile]"
+ << " [--test [--test-timeout seconds]]" << std::endl;
return -1;
}
}
if (editwithoutscenery && false == sceneryfromcommandline)
Global.SceneryFile.clear();
+ if (Global.test.enabled)
+ {
+ if (false == sceneryfromcommandline || Global.SceneryFile.empty())
+ {
+ ErrorLog("test: --test needs a scenery given with -s");
+ return -1;
+ }
+ // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
+ Global.editor_session = false;
+ Global.local_start_vehicle = "ghostview";
+ Global.GfxRenderer = "null";
+ Global.NvRenderer = false;
+ Global.bSoundEnabled = false;
+ Global.python_enabled = false;
+ Global.bInactivePause = false;
+ Global.bFullScreen = false;
+ Global.fullscreen_windowed = false;
+ Global.VSync = false;
+ Global.iMultisampling = 0;
+ Global.gfx_usegles = false;
+ Global.minframetime = std::chrono::duration(0.0f);
+ Global.extra_viewports.clear();
+ Global.headtrack_conf.joy.clear();
+ // a test runs on its own
+ Global.network_servers.clear();
+ Global.network_client.reset();
+ // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
+ if (!Global.random_seed)
+ Global.random_seed = seed_of("test");
+ }
+
return 0;
}
@@ -1290,6 +1338,12 @@ int eu07_application::init_glfw()
{
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
}
+ else if (Global.test.enabled)
+ {
+ // the null renderer draws nothing, but parts of the ui make textures with gl calls of their own.
+ // any context will do for them, so none is asked for in particular: a machine without a graphics
+ // driver (a test runner) has only the basic one of the system
+ }
else
{
if (!Global.LegacyRenderer)
@@ -1341,7 +1395,8 @@ int eu07_application::init_glfw()
Global.bFullScreen = true;
}
- auto *mainwindow = window(-1, true, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false);
+ // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it
+ auto *mainwindow = window(-1, false == Global.test.enabled, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false);
if (mainwindow == nullptr)
{
@@ -1428,6 +1483,11 @@ int eu07_application::init_gfx()
// default render path
GfxRenderer = gfx_renderer_factory::get_instance()->create("modern");
}
+ else if (Global.GfxRenderer == "null")
+ {
+ // draws nothing and loads no textures (test mode)
+ GfxRenderer = gfx_renderer_factory::get_instance()->create("null");
+ }
else if (Global.GfxRenderer == "experimental")
{
GfxRenderer = gfx_renderer_factory::get_instance()->create(Global.GfxRenderer);
diff --git a/application/drivermode.cpp b/application/drivermode.cpp
index b55d09c2b..1b3a44d63 100644
--- a/application/drivermode.cpp
+++ b/application/drivermode.cpp
@@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "scene/scene.h"
#include "rendering/lightarray.h"
#include "rendering/particles.h"
@@ -305,6 +306,11 @@ bool driver_mode::update()
simulation::Events.update();
simulation::Region->update_events();
simulation::Lights.update();
+
+ if (Global.test.enabled && simulation::is_ready)
+ {
+ simulation::Test.update(deltatime);
+ }
}
// render time routines follow:
@@ -478,6 +484,13 @@ void driver_mode::enter()
Timer::ResetTimers();
+ if (Global.test.enabled)
+ {
+ // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree
+ Timer::set_fixed_step(simulation::test_manager::frame_step);
+ simulation::Test.start();
+ }
+
set_picking(!Global.captureonstart);
m_editorpending = Global.editor_session;
diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp
index f8f06ac93..b84c1912f 100644
--- a/application/scenarioloadermode.cpp
+++ b/application/scenarioloadermode.cpp
@@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "application/application.h"
#include "application/scenarioloaderuilayer.h"
#include "rendering/renderer.h"
@@ -58,6 +59,10 @@ bool scenarioloader_mode::update() {
catch (std::runtime_error const &e) {
ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what()));
state.reset();
+ if (Global.test.enabled) {
+ simulation::Test.finish(simulation::test_result::error, "scenario couldn't be opened");
+ return true;
+ }
Global.SceneryFile.clear();
Application.pop_mode();
Application.push_mode(eu07_application::mode::launcher);
@@ -73,6 +78,11 @@ bool scenarioloader_mode::update() {
// back to the launcher as when the scenario can't be opened, not on to the driver mode with the scenery half loaded
ErrorLog( "Bad init: scenario loading failed" );
state.reset();
+ if( Global.test.enabled ) {
+ // there's nothing to test; the exit code says the run went wrong
+ simulation::Test.finish( simulation::test_result::error, "scenario loading failed" );
+ return true;
+ }
Global.SceneryFile.clear();
Application.pop_mode();
Application.push_mode(eu07_application::mode::launcher);
diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp
index 332d357c7..f193ad3e4 100644
--- a/rendering/nullrenderer.cpp
+++ b/rendering/nullrenderer.cpp
@@ -1,6 +1,25 @@
#include "stdafx.h"
#include "rendering/nullrenderer.h"
+#include "application/application.h"
+
+void null_imgui_renderer::BeginFrame()
+{
+ auto &io { ImGui::GetIO() };
+ if( false == io.Fonts->IsBuilt() ) {
+ unsigned char *pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsAlpha8( &pixels, &width, &height );
+ }
+}
+
+bool null_renderer::Render()
+{
+ // the ui frame begun by the application has to be ended, or imgui won't start the next one
+ Application.render_ui();
+ return true;
+}
+
std::unique_ptr null_renderer::create_func()
{
return std::make_unique();
diff --git a/rendering/nullrenderer.h b/rendering/nullrenderer.h
index 0b21580b9..2a7ef0398 100644
--- a/rendering/nullrenderer.h
+++ b/rendering/nullrenderer.h
@@ -35,7 +35,18 @@ private:
release_() override { /* null implementation, nothing to do */ }
};
+// user interface backend which draws nothing: imgui still builds its frames, so the ui code runs as usual
+class null_imgui_renderer : public imgui_renderer {
+public:
+ bool Init() override { return true; }
+ void Shutdown() override { /* null implementation, nothing to do */ }
+ // imgui wants its font atlas built before a frame starts; that's done on the cpu, no texture is made of it
+ void BeginFrame() override;
+ void Render() override { /* null implementation, nothing to do */ }
+};
+
// bare-bones render controller, in lack of anything better yet
+// it's the renderer of the test mode (--test): models are loaded for the physics, textures aren't
class null_renderer : public gfx_renderer {
public:
@@ -49,7 +60,7 @@ public:
Init( GLFWwindow *Window ) override { return true; }
// main draw call. returns false on error
bool
- Render() override { return true; }
+ Render() override;
void
SwapBuffers() override { /* null implementation, nothing to do */ }
inline
@@ -105,20 +116,22 @@ public:
void
Bind_Material( material_handle const Material, TSubModel const *sm = nullptr, lighting_data const *lighting = nullptr ) override { /* null implementation, nothing to do */ }
IMaterial const *
- Material( material_handle const Material ) const override { return m_materials.at(Material - 1).get(); }
+ Material( material_handle const Material ) const override {
+ return ( Material > 0 && static_cast( Material ) <= m_materials.size() ? m_materials[ Material - 1 ].get() : IMaterial::null_material() ); }
// shader methods
auto Fetch_Shader( std::string const &name ) -> std::shared_ptr override { throw std::runtime_error("not impl"); }
// texture methods
+ // no textures are loaded; whoever asks gets the null texture
texture_handle
- Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { throw std::runtime_error("not impl"); }
+ Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { return null_handle; }
void
Bind_Texture( texture_handle const Texture ) override { /* null implementation, nothing to do */ }
void
Bind_Texture( std::size_t const Unit, texture_handle const Texture ) override { /* null implementation, nothing to do */ }
- opengl_texture &
- Texture( texture_handle const Texture ) override { throw std::runtime_error("not impl"); }
- opengl_texture const &
- Texture( texture_handle const Texture ) const override { throw std::runtime_error("not impl"); }
+ ITexture &
+ Texture( texture_handle const Texture ) override { return *ITexture::null_texture(); }
+ ITexture const &
+ Texture( texture_handle const Texture ) const override { return *ITexture::null_texture(); }
// utility methods
void
Pick_Control_Callback( std::function Callback ) override { /* null implementation, nothing to do */ }
@@ -152,11 +165,12 @@ public:
imgui_renderer *GetImguiRenderer() override
{
- return nullptr;
+ return &m_imgui;
}
private:
std::string empty_str;
+ null_imgui_renderer m_imgui;
gfx::geometrybank_manager m_geometry;
std::vector> m_materials;
};
diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp
index ea2177170..59635c38c 100644
--- a/simulation/simulation.cpp
+++ b/simulation/simulation.cpp
@@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "utilities/Globals.h"
#include "world/Event.h"
@@ -109,6 +110,8 @@ state_manager::init_scripting_interface() {
simulation::Memory.insert( memorycell );
simulation::Region->insert( memorycell );
}
+ // the cell a test scenery reports its result to
+ simulation::Test.init_result_cell();
}
// legacy method, calculates changes in simulation state over specified time
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
new file mode 100644
index 000000000..4dbe4c24f
--- /dev/null
+++ b/simulation/simulationtest.cpp
@@ -0,0 +1,149 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#include "stdafx.h"
+#include "simulation/simulationtest.h"
+
+#include "application/application.h"
+#include "scene/scene.h"
+#include "simulation/simulation.h"
+#include "utilities/Globals.h"
+#include "utilities/Logs.h"
+#include "vehicle/DynObj.h"
+#include "world/Event.h"
+#include "world/MemCell.h"
+
+namespace simulation {
+
+test_manager Test;
+
+std::string_view to_string(test_result const Result)
+{
+ switch (Result)
+ {
+ case test_result::pass: return "pass";
+ case test_result::fail: return "fail";
+ case test_result::signal_passed_at_danger: return "signal passed at danger";
+ case test_result::timeout: return "timeout";
+ case test_result::standstill: return "standstill";
+ case test_result::error: return "error";
+ }
+ return "unknown";
+}
+
+void test_manager::init_result_cell()
+{
+ auto *cell = new TMemCell({0, -1, std::string(result_cell), "memcell"});
+ // neither of the reported values, so that a cell nobody wrote to says nothing
+ cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2);
+ simulation::Memory.insert(cell);
+ simulation::Region->insert(cell);
+}
+
+void test_manager::start()
+{
+ if (m_started)
+ return;
+ m_started = true;
+ m_time = 0.0;
+ m_resttime = 0.0;
+ if (simulation::Vehicles.sequence().empty())
+ {
+ // most likely the scenery wasn't found, or it isn't a test scenery
+ finish(test_result::error, "the scenery has no vehicles");
+ return;
+ }
+ // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
+ Global.iPause = 0;
+ WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}", Global.test.timeout, Global.test.standstill,
+ Global.test.pass_on_standstill ? ", standstill passes" : "",
+ Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed"));
+}
+
+void test_manager::update(double const Deltatime)
+{
+ if (false == m_started || m_finished)
+ return;
+
+ m_time += Deltatime;
+
+ if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
+ {
+ auto const value { cell->Value1() };
+ auto const reason { cell->Text().empty() ? std::string() : " (" + cell->Text() + ")" };
+ if (value == 0.0)
+ {
+ finish(test_result::fail, "__test.result set to 0" + reason);
+ return;
+ }
+ if (value == 1.0 && false == m_passrequested)
+ {
+ m_passrequested = true;
+ WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_time, reason));
+ }
+ }
+
+ auto const atrest = std::none_of(simulation::Vehicles.sequence().begin(), simulation::Vehicles.sequence().end(),
+ [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; });
+ m_resttime = atrest ? m_resttime + Deltatime : 0.0;
+
+ if (m_passrequested && m_resttime >= pass_settle_time)
+ {
+ finish(test_result::pass, "__test.result set to 1 and every vehicle stopped");
+ return;
+ }
+ if (Global.test.standstill > 0.0 && m_resttime >= Global.test.standstill)
+ {
+ auto const reason { std::format("every vehicle stood still for {:.0f} s", Global.test.standstill) };
+ finish(Global.test.pass_on_standstill ? test_result::pass : test_result::standstill, reason);
+ return;
+ }
+ if (Global.test.timeout > 0.0 && m_time >= Global.test.timeout)
+ {
+ finish(test_result::timeout, std::format("no result after {:.0f} s", Global.test.timeout));
+ return;
+ }
+}
+
+void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal)
+{
+ auto const reason { Vehicle + " passed signal " + Signal + " at danger" };
+ if (false == Global.test.enabled)
+ {
+ WriteLog(reason, logtype::generic);
+ return;
+ }
+ if (false == Global.test.fail_if_stop_overran)
+ {
+ WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_time));
+ return;
+ }
+ finish(test_result::signal_passed_at_danger, reason);
+}
+
+void test_manager::finish(test_result const Result, std::string const &Reason)
+{
+ if (m_finished || false == Global.test.enabled)
+ return;
+ m_finished = true;
+ m_result = Result;
+
+ auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_time, Reason) };
+ if (Result == test_result::pass)
+ WriteLog(line);
+ else
+ ErrorLog(line);
+ // the process has no console of its own; whoever started it with a redirected output gets the verdict there too
+ std::fprintf(stdout, "%s\n", line.c_str());
+ std::fflush(stdout);
+
+ Application.queue_quit(true);
+}
+
+} // namespace simulation
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
new file mode 100644
index 000000000..c9bc5437e
--- /dev/null
+++ b/simulation/simulationtest.h
@@ -0,0 +1,66 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#pragma once
+
+#include
+
+// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
+// fixed-step loop and the simulator quits with an exit code saying how the test went
+namespace simulation {
+
+// exit codes of a test run; public, scripts and CI read them
+enum class test_result : int {
+ pass = 0, // __test.result set to 1, then every vehicle came to rest (or test.pass_on_standstill)
+ fail = 1, // __test.result set to 0
+ signal_passed_at_danger = 2, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
+ timeout = 3, // test.timeout seconds of simulation time went by without a result
+ standstill = 4, // every vehicle stood still for test.standstill seconds without a result
+ error = 5, // the run could not start (no -s, the scenery failed to load) or the simulator threw
+};
+
+std::string_view to_string(test_result Result);
+
+class test_manager {
+
+public:
+ // name of the memory cell a scenery reports its result to
+ static constexpr std::string_view result_cell { "__test.result" };
+ // how long everything has to stand before a requested pass is granted [s]
+ static constexpr double pass_settle_time { 1.0 };
+ // fixed simulation time step of one frame in test mode [s]: 3 physics steps of 10 ms
+ static constexpr double frame_step { 0.03 };
+
+ // creates the result cell; called with the other scripting interface cells, before the scenery is read
+ void init_result_cell();
+ // the simulation is ready: start the clocks
+ void start();
+ // checks the end conditions after a simulation frame of Deltatime seconds
+ void update(double Deltatime);
+ // reported by a driver whose train went past a signal showing stop
+ void signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal);
+ // ends the test with given result; the first call wins
+ void finish(test_result Result, std::string const &Reason);
+
+ bool finished() const { return m_finished; }
+ // exit code of the process: the result, or error while the test hasn't finished
+ int exit_code() const { return static_cast(m_finished ? m_result : test_result::error); }
+
+private:
+ bool m_started { false };
+ bool m_finished { false };
+ test_result m_result { test_result::error };
+ bool m_passrequested { false };
+ double m_time { 0.0 }; // simulation time since the start [s]
+ double m_resttime { 0.0 }; // how long every vehicle has been standing [s]
+};
+
+extern test_manager Test;
+
+} // namespace simulation
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index b4f2e14be..e36223174 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -456,6 +456,40 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token
return false;
}
+bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
+{
+ // integration test limits, usually given in the config block of a test scenery
+ if (token == "test.timeout")
+ {
+ double value{ test.timeout };
+ ParseOne(Parser, value);
+ if (false == test.timeout_from_command_line)
+ test.timeout = std::max(0.0, value);
+ return true;
+ }
+
+ if (token == "test.standstill")
+ {
+ ParseOne(Parser, test.standstill);
+ test.standstill = std::max(0.0, test.standstill);
+ return true;
+ }
+
+ if (token == "test.pass_on_standstill")
+ {
+ ParseOne(Parser, test.pass_on_standstill);
+ return true;
+ }
+
+ if (token == "test.fail_if_stop_overran")
+ {
+ ParseOne(Parser, test.fail_if_stop_overran);
+ return true;
+ }
+
+ return false;
+}
+
bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& token)
{
if (token == "async.trainThreads")
@@ -1316,6 +1350,9 @@ void global_settings::ConfigParse(cParser& Parser)
if (ConfigParseDebug(Parser, token))
continue;
+ if (ConfigParseTest(Parser, token))
+ continue;
+
// WriteLog(std::format("Unknown config token: {}", token), logtype::warning, false);
} while (true);
diff --git a/utilities/Globals.h b/utilities/Globals.h
index ad216cd96..8fa04e9ce 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -86,6 +86,15 @@ struct global_settings {
std::string local_start_vehicle{ "EU07-424" };
std::string editor_enter_vehicle; // vehicle placed in the editor, to be entered when the driving goes on
bool editor_session{ false }; // scenery was opened for editing (-edit): loader keeps track of scenery layers and hands over to the editor
+ // integration test mode (--test, eu07/maszyna#541); the limits can be set in the scenery's config block (test.*)
+ struct test_settings {
+ bool enabled{ false };
+ double timeout{ 3600.0 }; // [s] of simulation time; no result by then fails the test
+ double standstill{ 300.0 }; // [s] every vehicle standing still this long ends the test; 0 = never
+ bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it
+ bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged
+ bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it
+ } test;
bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap
int iConvertModels{ 0 }; // tworzenie plików binarnych
int iConvertIndexRange{ 1000 }; // range of duplicate vertex scan
@@ -377,6 +386,7 @@ struct global_settings {
bool ConfigParseNetwork(cParser& Parser, const std::string& token);
bool ConfigParseHardware(cParser& Parser, const std::string& token);
bool ConfigParseDebug(cParser& Parser, const std::string& token);
+ bool ConfigParseTest(cParser& Parser, const std::string& token);
bool ConfigParse_gfx( cParser &parser, std::string_view const Token );
// sends basic content of the class in legacy (text) format to provided stream
void
diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp
index 0b877f2b4..388330bbe 100644
--- a/utilities/Timer.cpp
+++ b/utilities/Timer.cpp
@@ -26,6 +26,7 @@ double fRenderTime{ 0.0 };
double fSoundTimer{ 0.0 };
double fSinceStart{ 0.0 };
double override_delta = -1.0f;
+double fixed_step = 0.0;
double GetTime()
{
@@ -53,6 +54,11 @@ void set_delta_override(double t)
override_delta = t;
}
+void set_fixed_step(double t)
+{
+ fixed_step = t;
+}
+
void ResetTimers()
{
UpdateTimers( Global.iPause != 0 );
@@ -76,10 +82,15 @@ void UpdateTimers(bool pause)
fr = 1000000000;
#endif
DeltaRenderTime = double(count - oldCount) / double(fr);
+ if (fixed_step > 0.0)
+ {
+ // the frame lasts exactly as long as said, however long it took to compute; the time speed doesn't apply
+ DeltaRenderTime = fixed_step;
+ }
fRenderTime += DeltaRenderTime;
if (!pause)
{
- DeltaTime = Global.fTimeSpeed * DeltaRenderTime;
+ DeltaTime = (fixed_step > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
fSoundTimer += DeltaTime;
if (fSoundTimer > 0.1)
fSoundTimer = 0.0;
diff --git a/utilities/Timer.h b/utilities/Timer.h
index 32e170a46..15fdd4f6b 100644
--- a/utilities/Timer.h
+++ b/utilities/Timer.h
@@ -19,6 +19,9 @@ double GetDeltaRenderTime();
void set_delta_override(double v);
+// every frame advances the clocks by this many seconds, whatever the real time; 0 = real time (test mode)
+void set_fixed_step(double v);
+
void ResetTimers();
void UpdateTimers(bool pause);
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index c5f5f51e9..5f1bde20c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/.
#include "world/MemCell.h"
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
+#include "simulation/simulationtest.h"
#include "world/Track.h"
#include "world/station.h"
#include "input/keyboardinput.h"
@@ -767,7 +768,12 @@ void TController::TableCheck(double fDistance)
{ // aktualizacja rekordów z wyjątkiem ostatniego
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
{
- if (sSpeedTable[i].Update())
+ auto const waspassed { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
+ auto const switchchanged { sSpeedTable[ i ].Update() };
+ if( false == waspassed ) {
+ CheckSignalPassedAtDanger( sSpeedTable[ i ] );
+ }
+ if (switchchanged)
{
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
@@ -816,7 +822,12 @@ void TController::TableCheck(double fDistance)
}
}
}
- sSpeedTable[iLast].Update(); // aktualizacja ostatniego
+ // aktualizacja ostatniego; a signal at stop often is the last, the scan doesn't go past it
+ auto const lastwaspassed { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
+ sSpeedTable[iLast].Update();
+ if( false == lastwaspassed ) {
+ CheckSignalPassedAtDanger( sSpeedTable[ iLast ] );
+ }
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
if( sSpeedTable[ iLast ].fDist < fDistance ) {
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
@@ -827,6 +838,20 @@ void TController::TableCheck(double fDistance)
}
};
+void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point ) const
+{
+ if( false == TestFlag( Point.iFlags, spElapsed )
+ || false == TestFlag( Point.iFlags, spEvent )
+ || false == TestFlag( Point.iFlags, spSemaphor )
+ || true == TestFlag( Point.iFlags, spStopOnSBL ) // SetVelocity 0 x on automatic block: may go on after a stop
+ || Point.fVelNext != 0.0
+ || Point.evEvent == nullptr
+ || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only
+ return;
+ }
+ simulation::Test.signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
+}
+
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc)
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index f88e115ac..8c12087f9 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -519,6 +519,8 @@ private:
bool TableNotFound( basic_event const *Event, double const Distance ) const;
void TableTraceRoute( double fDistance, TDynamicObject *pVehicle );
void TableCheck( double fDistance );
+ // reports the train going past a signal showing stop (SetVelocity 0 0); called once the head passed Point
+ void CheckSignalPassedAtDanger( TSpeedPos const &Point ) const;
TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc );
bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance );
bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex );
From 6a538d202b6437e27e189e7c63a0fa413da65167 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 13:17:27 +0100
Subject: [PATCH 029/104] test: scenario tests run in the simulator's test mode
and check its exit code
run.py starts eu07 with --test (and --test-timeout for cases that
record a fixed time) and compares the result from the exit code with the
case's expect key, before the physicslog checks. The 14 cases take about 30 s
with -j 4 instead of minutes. --watch keeps the old windowed run.
New case keys: expect, test_config (lines of a config block), track_events
(lines added to a track of the base scenery, e.g. event0 test_pass). New cases
show each end of the test mode: test_mode_pass, _signal_passed_at_danger,
_timeout and _standstill. The slippery rail cases slide past the red signal,
which now ends a test, so they set test.fail_if_stop_overran no.
README documents the test mode for scenery authors.
---
tests/scenarios/README.md | 130 ++++++++++++++----
.../cases/eu07_slippery_push_red_signal.json | 3 +
.../cases/eu07_slippery_red_signal.json | 3 +
tests/scenarios/cases/td_red_signal_pass.scn | 8 ++
tests/scenarios/cases/test_mode_pass.json | 31 +++++
.../test_mode_signal_passed_at_danger.json | 22 +++
.../scenarios/cases/test_mode_standstill.json | 26 ++++
tests/scenarios/cases/test_mode_timeout.json | 21 +++
tests/scenarios/run.py | 122 ++++++++++++----
9 files changed, 315 insertions(+), 51 deletions(-)
create mode 100644 tests/scenarios/cases/td_red_signal_pass.scn
create mode 100644 tests/scenarios/cases/test_mode_pass.json
create mode 100644 tests/scenarios/cases/test_mode_signal_passed_at_danger.json
create mode 100644 tests/scenarios/cases/test_mode_standstill.json
create mode 100644 tests/scenarios/cases/test_mode_timeout.json
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 4600a3577..1ebd84c75 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -1,49 +1,121 @@
# Scenario tests
-End-to-end checks that run the real simulator on a scenery and look at what a vehicle
-did: did it start, did it keep to the speed limit, did it brake and stop.
+End-to-end checks that run the real simulator on a scenery and look at how the run ended
+and what a vehicle did: did it start, did it keep to the speed limit, did it brake and stop,
+did it pass a signal at stop.
Scenery and vehicle data are not in this repo, so these run against a local game install
only, not in CI.
+## The simulator's test mode
+
+The runner drives the simulator's test mode (eu07/maszyna#541), which works without the
+runner too and is meant for scenery authors as well:
+
+```
+eu07 --test -s [--test-timeout ] [-seed ] [-ini ]
+```
+
+With `--test` the simulator:
+
+- needs `-s`; `-v` is ignored and every train is driven by AI (ghostview),
+- draws nothing: the null renderer loads the 3D models (the physics needs some of their
+ data) but no textures, and the window stays hidden,
+- has no sound, no network, no python, no pause (not even one set by the scenery), and
+ no crash dialog,
+- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
+ frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
+- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
+ runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal),
+- quits when the test ends, and says how it ended in the exit code and in a `test: ...`
+ line on stdout and in the log.
+
+A scenery reports its result to the memory cell `__test.result`, which the simulator creates
+(in every run, so a test scenery loads normally too). Write value 1 to it for a pass and 0
+for a failure, with an `UpdateValues` event; other values are ignored, and the text, if
+given, goes to the log as the reason:
+
+```
+event test_pass UpdateValues 0 __test.result reached_the_stop 1 * endevent
+event test_fail UpdateValues 0 __test.result wrong_track 0 * endevent
+```
+
+(`PutValues` isn't the event for it: it hands a command to a vehicle, it doesn't write a cell.)
+A good place for the pass event is `event0` of a track the train should stop on: it runs
+while a train stands there, and the length of the track is the margin of the stop.
+
+The test ends with the first of these:
+
+| exit code | result | when |
+| --- | --- | --- |
+| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first. Also the standstill end with `test.pass_on_standstill yes` |
+| 1 | fail | `__test.result` was set to 0; ends at once |
+| 2 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
+| 3 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
+| 4 | standstill | every vehicle stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits |
+| 5 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw |
+
+A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819).
+
+The limits go in a `config` block of the scenery:
+
+```
+config
+test.timeout 600
+test.standstill 120
+test.pass_on_standstill no
+test.fail_if_stop_overran yes
+endconfig
+```
+
+`--test-timeout` on the command line wins over `test.timeout` of the scenery.
+
+A signal is passed at danger when the head of a train goes past a signal which its driver
+has in its speed table, showing stop. So it's the driver's view that counts: a train without
+a driver isn't watched, and neither is a signal the driver never scanned (a train placed at
+100 km/h 150 m before a signal at stop got past it before its AI first looked ahead; at
+60 km/h it was caught). Outside the test mode the same is written to the log, nothing more.
+
## Running
```
-python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna" -j 4
+python tests/scenarios/run.py --game-dir "C:/Steam/steamapps/common/MaSzyna" -j 4
```
Python 3.10+, no extra packages. Options:
- `EU07_GAME_DIR` can replace `--game-dir`.
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
- `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
+ `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command
+ line options.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
-- `-j N` runs N cases at once, each in its own simulator window. Each case prints its
- results when it is done. All 8 cases take about a minute with `-j 4`.
-- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
- about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
- profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
- `--timespeed 1` to watch a run.
+- `-j N` runs N cases at once. Each case prints its results when it is done. All 14 cases
+ take about 30 s with `-j 4`, loading included.
+- `--watch` runs a case the old way, in a visible window in real time (or faster with
+ `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For
+ watching what a case does.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
-the vehicle's physicslog) are moved to `tests/scenarios/out//`.
+`stdout.txt`, the vehicle's physicslog) are moved to `tests/scenarios/out//`.
## How it works
For each case the runner:
1. writes `scenery/autotest_.scn` into the game dir: the base scenery with its own
- trainsets removed, the start time changed if the case says so, and the case's `.scn`
- fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
- in for keys the scenery expects a player to press, extra events) before it,
-2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
- ghostview leaves every train to the AI, and the extra ini turns on `physicslog`, runs in a
- 1280x720 window, does not pause when the window loses focus, and writes the logs to
- `logs/log (autotest_) .txt` rather than the shared `log.txt` (`multiplelogs`),
-3. waits until `physicslog/autotest_.dat` covers `duration` seconds, then closes the
- simulator. It gives up early when the log reports `Bad vehicle` / `Bad trainset`, or when
- the scenario has loaded and no physicslog appeared,
-4. runs the checks on the physicslog.
+ trainsets removed, the start time changed if the case says so, the case's track events
+ added, and the case's `.scn` fragment added: its trainsets after `FirstInit`, everything
+ else (the case's `test_config`, event launchers standing in for keys the scenery expects a
+ player to press, extra events) before it,
+2. starts the simulator with `--test -s autotest_.scn -ini out//autotest.ini`,
+ plus `--test-timeout ` when the case gives a `duration`; the extra ini turns on
+ `physicslog` and writes the logs to `logs/log (autotest_) .txt` rather than the
+ shared `log.txt` (`multiplelogs`),
+3. waits until the simulator quits by itself. It gives up early when the log reports
+ `Bad vehicle` / `Bad trainset`, when the scenario has loaded and no physicslog appeared, or
+ after the case's `timeout` of wall-clock time,
+4. compares the result from the exit code with the case's `expect`, then runs the checks on
+ the physicslog.
The lead vehicle is named `autotest_`, so every case has its own physicslog and log
files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt`
@@ -60,9 +132,12 @@ scenery is newer.
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
| `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail |
+| `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes |
+| `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]` |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
-| `duration` | seconds of simulation to record |
+| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`. Default `timeout` for a case with `duration`, else `pass` |
+| `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) |
| `timeout` | wall-clock seconds before giving up, loading included |
| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
| `checks` | list of checks, below |
@@ -72,7 +147,14 @@ the one whose physicslog is checked. Other vehicles of the consist take names ma
e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
only in `vars.consist`. `td_red_signal_moving.scn` is the red signal one with the train
-starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking.
+starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking
+and slides past the signal, so those cases set `test.fail_if_stop_overran no`.
+`td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0`
+on `tor1k`, the track in front of the signal.
+
+The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass
+event), `test_mode_signal_passed_at_danger` (exit 2), `test_mode_timeout` (exit 3, from
+`test.timeout`) and `test_mode_standstill` (exit 4, from `test.standstill`).
Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
diff --git a/tests/scenarios/cases/eu07_slippery_push_red_signal.json b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
index f7ae10bb7..64d6ba884 100644
--- a/tests/scenarios/cases/eu07_slippery_push_red_signal.json
+++ b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
@@ -4,6 +4,9 @@
"time": "10:34",
"track_friction": 0.03,
"fragment": "td_red_signal_moving.scn",
+ "test_config": [
+ "test.fail_if_stop_overran no"
+ ],
"vars": {
"velocity": "30",
"consist": [
diff --git a/tests/scenarios/cases/eu07_slippery_red_signal.json b/tests/scenarios/cases/eu07_slippery_red_signal.json
index 40b5944eb..c2f60f22d 100644
--- a/tests/scenarios/cases/eu07_slippery_red_signal.json
+++ b/tests/scenarios/cases/eu07_slippery_red_signal.json
@@ -4,6 +4,9 @@
"time": "10:34",
"track_friction": 0.03,
"fragment": "td_red_signal_moving.scn",
+ "test_config": [
+ "test.fail_if_stop_overran no"
+ ],
"vars": {
"velocity": "30",
"consist": [
diff --git a/tests/scenarios/cases/td_red_signal_pass.scn b/tests/scenarios/cases/td_red_signal_pass.scn
new file mode 100644
index 000000000..724050322
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal_pass.scn
@@ -0,0 +1,8 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop),
+// with the test mode's pass event: the case puts it as event0 on tor1k, the track in front of
+// the signal, so it runs once the train stands there. the test passes when every vehicle stopped.
+event test_pass UpdateValues 0 __test.result stopped_before_stacja1_j 1 * endevent
+trainset td/rozklad tdo_n1734 0.0 0.1
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/cases/test_mode_pass.json b/tests/scenarios/cases/test_mode_pass.json
new file mode 100644
index 000000000..686b7d160
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_pass.json
@@ -0,0 +1,31 @@
+{
+ "description": "Test mode, pass: EU07 on td.scn with no route set stops before the exit signal stacja1_j; event0 of the track there reports the pass, and the test ends as passed once the train stands.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_pass.scn",
+ "track_events": {
+ "tor1k": "event0 test_pass"
+ },
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "pass",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 150
+ },
+ {
+ "type": "stops",
+ "moving_speed": 5,
+ "stop_speed": 0.5,
+ "hold": 0.5
+ },
+ {
+ "type": "distance",
+ "max": 150
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_signal_passed_at_danger.json b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json
new file mode 100644
index 000000000..338e7e6ea
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json
@@ -0,0 +1,22 @@
+{
+ "description": "Test mode, signal passed at danger: EU07 on td.scn with no route set starts at 60 km/h about 150 m before the exit signal stacja1_j at stop. Its AI driver is still preparing the engine and doesn't brake, and the run ends when the train passes the signal.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "60",
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "signal_passed_at_danger",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "max_speed",
+ "limit": 61
+ },
+ {
+ "type": "distance",
+ "min": 140
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_standstill.json b/tests/scenarios/cases/test_mode_standstill.json
new file mode 100644
index 000000000..0d96585ee
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_standstill.json
@@ -0,0 +1,26 @@
+{
+ "description": "Test mode, standstill: EU07 on td.scn with no route set stops before the exit signal stacja1_j at stop and stays; nothing reports a result, so the test ends once every vehicle stood still for test.standstill 120 seconds (the train waits about 70 s before it pulls off, so less would end it before the start).",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "test_config": [
+ "test.standstill 120"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "standstill",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "stops",
+ "moving_speed": 5,
+ "stop_speed": 0.5,
+ "hold": 5
+ },
+ {
+ "type": "distance",
+ "max": 150
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_timeout.json b/tests/scenarios/cases/test_mode_timeout.json
new file mode 100644
index 000000000..46899e89c
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_timeout.json
@@ -0,0 +1,21 @@
+{
+ "description": "Test mode, timeout: EU07 on td.scn with no route set pulls off towards the exit signal stacja1_j at stop; nothing reports a result and test.timeout 90 from the scenery's config block runs out first.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "test_config": [
+ "test.timeout 90"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "timeout",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 90
+ }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 2cd754a06..770069d12 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -2,16 +2,19 @@
"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
A case (cases/.json) names a base scenery from the game install, a fragment
-added to it (usually a trainset with an AI driver), and checks on the vehicle's
-physics log. The runner:
+added to it (usually a trainset with an AI driver), the result the simulator's test
+mode should end with, and checks on the vehicle's physics log. The runner:
1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
trainsets removed, optionally a different start time, and the case fragment added,
- 2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
- settings file (-ini) that turns on physicslog and runs in a window,
- 3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
- then closes the simulator,
- 4. evaluates the checks on the log and prints PASS/FAIL per check.
+ 2. starts eu07 in test mode (--test: every train driven by AI, nothing drawn, fixed
+ time steps as fast as it can) with that scenery and an extra settings file (-ini)
+ that turns on physicslog,
+ 3. waits until the simulator quits by itself and reads the test result from its exit
+ code: pass, fail, signal passed at danger, timeout (after `duration` seconds of
+ simulation, if the case gives one), standstill or error,
+ 4. compares the result with the one the case expects, evaluates the checks on the
+ physicslog and prints PASS/FAIL per check.
Scenery and vehicle data are not part of this repo, so this runs against a local game
install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md.
@@ -49,7 +52,18 @@ COL_COMMAND = 16 # text, read as None
COL_WHEELSLIP = 20
COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
-# settings layered over the user's eu07.ini for a test run
+# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtest.h
+EXIT_RESULTS = {
+ 0: "pass",
+ 1: "fail",
+ 2: "signal_passed_at_danger",
+ 3: "timeout",
+ 4: "standstill",
+ 5: "error",
+}
+
+# settings layered over the user's eu07.ini for a test run; the window ones only matter
+# with --watch, test mode keeps its window hidden and turns the sound off by itself
TEST_INI = """\
fullscreen no
fullscreenwindowed no
@@ -89,6 +103,17 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+def add_track_events(text: str, events: dict) -> str:
+ """Adds lines (e.g. "event0 test_pass") to tracks named in events, before their endtrack."""
+ for track, lines in events.items():
+ lines = [lines] if isinstance(lines, str) else lines
+ m = re.search(rf"(?im)^\s*node\s+\S+\s+\S+\s+{re.escape(track)}\s+track\b.*?^(\s*endtrack\b)", text, re.S)
+ if not m:
+ sys.exit(f"track_events: no track {track} in the base scenery itself (not in its includes)")
+ text = text[: m.start(1)] + "".join(line + "\n" for line in lines) + text[m.start(1):]
+ return text
+
+
def set_track_friction(text: str, friction: float) -> str:
"""Sets the friction of every track: node track ..."""
return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+",
@@ -118,6 +143,8 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
text = set_start_time(text, case["time"])
if "track_friction" in case:
text = set_track_friction(text, case["track_friction"])
+ if "track_events" in case:
+ text = add_track_events(text, case["track_events"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
# vars first: {{vehicle}} inside a var's value gets filled in the second pass
fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
@@ -126,6 +153,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
# events of the case go in before it (read after it they never fire), trainsets after it
# (placed before it they stand on unlinked track and derail at once)
before, trainsets = split_trainsets(fragment)
+ if case.get("test_config"):
+ # settings of the test mode (test.timeout and so on), read like any other config block
+ before = "config\n" + "".join(line + "\n" for line in case["test_config"]) + "endconfig\n" + before
header = f"\n// ---- autotest: {case_name} ----\n"
firstinit = re.search(r"(?im)^\s*firstinit\b", text)
if firstinit:
@@ -200,20 +230,30 @@ STARTUP_TIMEOUT = 120.0
@dataclass
class RunResult:
rows: list[list[float]] = field(default_factory=list)
- exit_code: int | None = None # None: still running when we closed it (the normal end)
+ exit_code: int | None = None # None: still running when we closed it (the normal end with --watch)
+ verdict: str = "" # the simulator's own line about the test result
failure: str = "" # why the run was cut short
wall_seconds: float = 0.0
logs: dict[str, Path] = field(default_factory=dict)
def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
- duration: float, timeout: float, say) -> RunResult:
+ duration: float | None, timeout: float, watch: bool, say) -> RunResult:
+ """Runs the simulator on the scenery. In test mode it quits by itself and the exit code
+ is the result; with watch it runs in a window and gets closed after `duration`."""
physicslog.unlink(missing_ok=True)
- cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ if watch:
+ cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ else:
+ cmd = [str(exe), "--test", "-s", scenery, "-ini", str(ini)]
+ if duration is not None:
+ cmd += ["--test-timeout", f"{duration:g}"]
say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True)
since = time.time() - 1
started = time.monotonic()
- proc = subprocess.Popen(cmd, cwd=game_dir)
+ # the test result line goes to stdout; a file, not a pipe, so a chatty run can't block on it
+ stdout = (ini.parent / "stdout.txt").open("w+b")
+ proc = subprocess.Popen(cmd, cwd=game_dir, stdout=stdout, stderr=subprocess.STDOUT)
result = RunResult()
last_report = 0.0
try:
@@ -229,7 +269,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
if proc.poll() is not None:
result.exit_code = proc.returncode
break
- if sim_t >= duration:
+ if watch and sim_t >= duration:
break
if wall > timeout:
result.failure = f"timed out after {timeout:.0f}s before {duration}s of simulation"
@@ -252,6 +292,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
except subprocess.TimeoutExpired:
proc.kill()
result.wall_seconds = time.monotonic() - started
+ stdout.seek(0)
+ result.verdict = next((line.strip() for line in stdout.read().decode(errors="replace").splitlines()
+ if line.startswith("test:")), "")
+ stdout.close()
result.rows = read_physicslog(physicslog)
result.logs = find_logs(game_dir, scenery, since)
return result
@@ -422,7 +466,14 @@ def count_lines(path: Path) -> int:
return 0
-def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> bool:
+def describe_exit(code: int | None) -> str:
+ if code is None:
+ return "none, still running"
+ name = EXIT_RESULTS.get(code)
+ return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)"
+
+
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool:
case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
say(f"\n=== {name}: {case.get('description', '')}")
out = OUT_DIR / name
@@ -436,8 +487,16 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> boo
ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
physicslog = game_dir / "physicslog" / f"{vehicle}.dat"
+ duration = float(case["duration"]) if "duration" in case else None
+ # a case that only records `duration` seconds ends on the test timeout; one that says
+ # how the test ends (a pass event, a signal passed at danger...) expects that result
+ expect = case.get("expect", "timeout" if duration is not None else "pass")
+ if expect not in EXIT_RESULTS.values():
+ sys.exit(f"{name}: expect must be one of {', '.join(EXIT_RESULTS.values())}")
+ if watch and duration is None:
+ sys.exit(f"{name}: --watch needs a case with duration")
result = run_simulator(exe, game_dir, scenery, ini, physicslog,
- float(case["duration"]), float(case.get("timeout", 600)), say)
+ duration, float(case.get("timeout", 600)), watch, say)
# the logs are ours alone (named after the case scenery), move them out of the game dir
for kind, path in result.logs.items():
@@ -448,18 +507,26 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> boo
ok = True
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
- if result.exit_code is not None:
- say(f" FAIL simulator exited on its own with code {result.exit_code}")
- ok = False
+ if watch:
+ if result.exit_code is not None:
+ say(f" FAIL simulator exited on its own with code {result.exit_code}")
+ ok = False
+ else:
+ if result.verdict:
+ say(f" {result.verdict}")
+ got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None
+ passed = got == expect
+ say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}, expected {expect}")
+ ok &= passed
if result.failure:
say(f" FAIL {result.failure}")
ok = False
- if not result.rows:
+ if not result.rows and case.get("checks"):
if not result.failure:
say(f" FAIL no physicslog for '{vehicle}'")
return False
- for check in case["checks"]:
+ for check in case.get("checks", []):
params = {k: v for k, v in check.items() if k != "type"}
passed, detail = CHECKS[check["type"]](result.rows, **params)
say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
@@ -479,12 +546,13 @@ def main() -> int:
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
- # 20 gave the same speed profile as 1 within a few km/h and seconds on eu07_td_timetable,
- # in 20 s instead of 4 min; 1 is for watching a run
- ap.add_argument("--timespeed", type=float, default=20.0,
- help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
+ ap.add_argument("--watch", action="store_true",
+ help="run in a visible window in real time (see --timespeed) instead of the test mode, "
+ "closed after the case's duration; the exit code isn't checked")
+ ap.add_argument("--timespeed", type=float, default=1.0,
+ help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)")
ap.add_argument("-j", "--jobs", type=int, default=1,
- help="cases run at once, each in its own simulator window (default 1)")
+ help="cases run at once, each in a simulator of its own (default 1)")
args = ap.parse_args()
if not args.game_dir:
@@ -504,7 +572,7 @@ def main() -> int:
def say(line, progress=False):
print(line, flush=True)
for n in names:
- results[n] = run_case(n, exe, game_dir, args.timespeed, say)
+ results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say)
else:
# each case prints its block when it is done, so parallel output does not interleave
def job(n):
@@ -512,7 +580,7 @@ def main() -> int:
def say(line, progress=False):
if not progress:
lines.append(line)
- ok = run_case(n, exe, game_dir, args.timespeed, say)
+ ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say)
return n, ok, lines
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
for n in names:
From 441caeed641b1a2257b382916f5dd6431b3369bc Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:12:11 +0100
Subject: [PATCH 030/104] refactor(simulation): tidy the test mode code
The test manager is reached through simulation::test() instead of a global,
the result cell is owned by a unique_ptr until the memory table takes it, the
cell value is compared with a margin, strings are built with std::format and
the --test settings moved to apply_test_mode_settings(). The driver's signal
check is folded into UpdateSpeedPosition(), which updates a speed table entry
and reports a signal at stop the head of the train just passed. The test.*
keys are listed with the other settings at the start of the log.
---
EU07.cpp | 5 +--
application/application.cpp | 55 ++++++++++++++++++------------
application/drivermode.cpp | 4 +--
application/scenarioloadermode.cpp | 4 +--
rendering/nullrenderer.cpp | 5 +--
simulation/simulation.cpp | 2 +-
simulation/simulationtest.cpp | 47 ++++++++++++++++++-------
simulation/simulationtest.h | 8 +++--
utilities/Globals.cpp | 4 +++
utilities/Timer.cpp | 21 +++++++++---
vehicle/Driver.cpp | 46 +++++++++++++------------
vehicle/Driver.h | 5 +--
12 files changed, 131 insertions(+), 75 deletions(-)
diff --git a/EU07.cpp b/EU07.cpp
index aac7cae11..ec3e972e7 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -23,6 +23,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include
+#include
#ifdef WITHDUMPGEN
#ifdef _WIN32
#include
@@ -150,7 +151,7 @@ int main(int argc, char *argv[])
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
- ErrorLog("Critical error: " + std::string(Error.what()));
+ ErrorLog(std::format("Critical error: {}", Error.what()));
// in test mode nobody is there to close the box, the exit code tells of the error
if (false == Global.test.enabled)
{
@@ -167,5 +168,5 @@ int main(int argc, char *argv[])
#endif
// skip destructors, there are ordering errors which causes segfaults
// a test run (--test) says its result in the exit code
- std::_Exit(Global.test.enabled ? simulation::Test.exit_code() : 0);
+ std::_Exit(Global.test.enabled ? simulation::test().exit_code() : 0);
}
diff --git a/application/application.cpp b/application/application.cpp
index 37afff67f..439c01d97 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1137,6 +1137,38 @@ void eu07_application::init_files()
}
namespace fs = std::filesystem;
+namespace
+{
+
+// the settings of the test mode (--test), over whatever the settings files say
+void apply_test_mode_settings()
+{
+ // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
+ Global.editor_session = false;
+ Global.local_start_vehicle = "ghostview";
+ Global.GfxRenderer = "null";
+ Global.NvRenderer = false;
+ Global.bSoundEnabled = false;
+ Global.python_enabled = false;
+ Global.bInactivePause = false;
+ Global.bFullScreen = false;
+ Global.fullscreen_windowed = false;
+ Global.VSync = false;
+ Global.iMultisampling = 0;
+ Global.gfx_usegles = false;
+ Global.minframetime = std::chrono::duration(0.0f);
+ Global.extra_viewports.clear();
+ Global.headtrack_conf.joy.clear();
+ // a test runs on its own
+ Global.network_servers.clear();
+ Global.network_client.reset();
+ // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
+ if (!Global.random_seed)
+ Global.random_seed = seed_of("test");
+}
+
+} // namespace
+
int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
@@ -1241,28 +1273,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
ErrorLog("test: --test needs a scenery given with -s");
return -1;
}
- // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
- Global.editor_session = false;
- Global.local_start_vehicle = "ghostview";
- Global.GfxRenderer = "null";
- Global.NvRenderer = false;
- Global.bSoundEnabled = false;
- Global.python_enabled = false;
- Global.bInactivePause = false;
- Global.bFullScreen = false;
- Global.fullscreen_windowed = false;
- Global.VSync = false;
- Global.iMultisampling = 0;
- Global.gfx_usegles = false;
- Global.minframetime = std::chrono::duration(0.0f);
- Global.extra_viewports.clear();
- Global.headtrack_conf.joy.clear();
- // a test runs on its own
- Global.network_servers.clear();
- Global.network_client.reset();
- // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
- if (!Global.random_seed)
- Global.random_seed = seed_of("test");
+ apply_test_mode_settings();
}
return 0;
diff --git a/application/drivermode.cpp b/application/drivermode.cpp
index 1b3a44d63..deb906a4a 100644
--- a/application/drivermode.cpp
+++ b/application/drivermode.cpp
@@ -309,7 +309,7 @@ bool driver_mode::update()
if (Global.test.enabled && simulation::is_ready)
{
- simulation::Test.update(deltatime);
+ simulation::test().update(deltatime);
}
}
@@ -488,7 +488,7 @@ void driver_mode::enter()
{
// the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree
Timer::set_fixed_step(simulation::test_manager::frame_step);
- simulation::Test.start();
+ simulation::test().start();
}
set_picking(!Global.captureonstart);
diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp
index b84c1912f..20fa46d3d 100644
--- a/application/scenarioloadermode.cpp
+++ b/application/scenarioloadermode.cpp
@@ -60,7 +60,7 @@ bool scenarioloader_mode::update() {
ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what()));
state.reset();
if (Global.test.enabled) {
- simulation::Test.finish(simulation::test_result::error, "scenario couldn't be opened");
+ simulation::test().finish(simulation::test_result::error, "scenario couldn't be opened");
return true;
}
Global.SceneryFile.clear();
@@ -80,7 +80,7 @@ bool scenarioloader_mode::update() {
state.reset();
if( Global.test.enabled ) {
// there's nothing to test; the exit code says the run went wrong
- simulation::Test.finish( simulation::test_result::error, "scenario loading failed" );
+ simulation::test().finish( simulation::test_result::error, "scenario loading failed" );
return true;
}
Global.SceneryFile.clear();
diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp
index f193ad3e4..bc466e977 100644
--- a/rendering/nullrenderer.cpp
+++ b/rendering/nullrenderer.cpp
@@ -7,8 +7,9 @@ void null_imgui_renderer::BeginFrame()
{
auto &io { ImGui::GetIO() };
if( false == io.Fonts->IsBuilt() ) {
- unsigned char *pixels;
- int width, height;
+ unsigned char *pixels { nullptr };
+ int width { 0 };
+ int height { 0 };
io.Fonts->GetTexDataAsAlpha8( &pixels, &width, &height );
}
}
diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp
index 59635c38c..d10d555a3 100644
--- a/simulation/simulation.cpp
+++ b/simulation/simulation.cpp
@@ -111,7 +111,7 @@ state_manager::init_scripting_interface() {
simulation::Region->insert( memorycell );
}
// the cell a test scenery reports its result to
- simulation::Test.init_result_cell();
+ simulation::test().init_result_cell();
}
// legacy method, calculates changes in simulation state over specified time
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 4dbe4c24f..439f295fe 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -19,9 +19,29 @@ http://mozilla.org/MPL/2.0/.
#include "world/Event.h"
#include "world/MemCell.h"
+#include
+#include
+#include
+#include
+#include
+
+namespace {
+
+// the cell holds what the scenery wrote, so the values are whole numbers; the margin only keeps a stray fraction out
+bool holds(double const Value, double const Expected)
+{
+ return std::abs(Value - Expected) < 1e-6;
+}
+
+} // namespace
+
namespace simulation {
-test_manager Test;
+test_manager &test()
+{
+ static test_manager instance;
+ return instance;
+}
std::string_view to_string(test_result const Result)
{
@@ -39,11 +59,12 @@ std::string_view to_string(test_result const Result)
void test_manager::init_result_cell()
{
- auto *cell = new TMemCell({0, -1, std::string(result_cell), "memcell"});
+ auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
// neither of the reported values, so that a cell nobody wrote to says nothing
cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2);
- simulation::Memory.insert(cell);
- simulation::Region->insert(cell);
+ simulation::Region->insert(cell.get());
+ // the table owns its cells
+ simulation::Memory.insert(cell.release());
}
void test_manager::start()
@@ -76,21 +97,21 @@ void test_manager::update(double const Deltatime)
if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
{
auto const value { cell->Value1() };
- auto const reason { cell->Text().empty() ? std::string() : " (" + cell->Text() + ")" };
- if (value == 0.0)
+ auto const reason { cell->Text().empty() ? std::string() : std::format(" ({})", cell->Text()) };
+ if (holds(value, 0.0))
{
- finish(test_result::fail, "__test.result set to 0" + reason);
+ finish(test_result::fail, std::format("__test.result set to 0{}", reason));
return;
}
- if (value == 1.0 && false == m_passrequested)
+ if (holds(value, 1.0) && false == m_passrequested)
{
m_passrequested = true;
WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_time, reason));
}
}
- auto const atrest = std::none_of(simulation::Vehicles.sequence().begin(), simulation::Vehicles.sequence().end(),
- [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; });
+ auto const atrest { std::ranges::none_of(simulation::Vehicles.sequence(),
+ [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; }) };
m_resttime = atrest ? m_resttime + Deltatime : 0.0;
if (m_passrequested && m_resttime >= pass_settle_time)
@@ -111,9 +132,9 @@ void test_manager::update(double const Deltatime)
}
}
-void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal)
+void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal)
{
- auto const reason { Vehicle + " passed signal " + Signal + " at danger" };
+ auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) };
if (false == Global.test.enabled)
{
WriteLog(reason, logtype::generic);
@@ -127,7 +148,7 @@ void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::stri
finish(test_result::signal_passed_at_danger, reason);
}
-void test_manager::finish(test_result const Result, std::string const &Reason)
+void test_manager::finish(test_result const Result, std::string_view const Reason)
{
if (m_finished || false == Global.test.enabled)
return;
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index c9bc5437e..f47f408b7 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include
+#include
// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
// fixed-step loop and the simulator quits with an exit code saying how the test went
@@ -44,9 +45,9 @@ public:
// checks the end conditions after a simulation frame of Deltatime seconds
void update(double Deltatime);
// reported by a driver whose train went past a signal showing stop
- void signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal);
+ void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal);
// ends the test with given result; the first call wins
- void finish(test_result Result, std::string const &Reason);
+ void finish(test_result Result, std::string_view Reason);
bool finished() const { return m_finished; }
// exit code of the process: the result, or error while the test hasn't finished
@@ -61,6 +62,7 @@ private:
double m_resttime { 0.0 }; // how long every vehicle has been standing [s]
};
-extern test_manager Test;
+// the test of the run
+test_manager &test();
} // namespace simulation
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index e36223174..5cdb3ef25 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -1779,6 +1779,10 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "gfx.shadowmap.enabled", gfx_shadowmap_enabled );
// TODO: export fpslimit
export_as_text( Output, "randomseed", Global.random_seed );
+ export_as_text( Output, "test.timeout", test.timeout );
+ export_as_text( Output, "test.standstill", test.standstill );
+ export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill );
+ export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran );
export_as_text( Output, "gfx.envmap.enabled", gfx_envmap_enabled );
export_as_text( Output, "gfx.postfx.motionblur.enabled", gfx_postfx_motionblur_enabled );
export_as_text( Output, "gfx.postfx.motionblur.shutter", gfx_postfx_motionblur_shutter );
diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp
index 388330bbe..eacd2ba0a 100644
--- a/utilities/Timer.cpp
+++ b/utilities/Timer.cpp
@@ -26,7 +26,17 @@ double fRenderTime{ 0.0 };
double fSoundTimer{ 0.0 };
double fSinceStart{ 0.0 };
double override_delta = -1.0f;
-double fixed_step = 0.0;
+
+namespace {
+
+// when set (test mode), every frame lasts this long, see set_fixed_step()
+double &fixed_step()
+{
+ static double step{0.0};
+ return step;
+}
+
+} // namespace
double GetTime()
{
@@ -56,7 +66,7 @@ void set_delta_override(double t)
void set_fixed_step(double t)
{
- fixed_step = t;
+ fixed_step() = t;
}
void ResetTimers()
@@ -82,15 +92,16 @@ void UpdateTimers(bool pause)
fr = 1000000000;
#endif
DeltaRenderTime = double(count - oldCount) / double(fr);
- if (fixed_step > 0.0)
+ auto const fixedstep{fixed_step()};
+ if (fixedstep > 0.0)
{
// the frame lasts exactly as long as said, however long it took to compute; the time speed doesn't apply
- DeltaRenderTime = fixed_step;
+ DeltaRenderTime = fixedstep;
}
fRenderTime += DeltaRenderTime;
if (!pause)
{
- DeltaTime = (fixed_step > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
+ DeltaTime = (fixedstep > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
fSoundTimer += DeltaTime;
if (fSoundTimer > 0.1)
fSoundTimer = 0.0;
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5f1bde20c..c0614923c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -768,12 +768,7 @@ void TController::TableCheck(double fDistance)
{ // aktualizacja rekordów z wyjątkiem ostatniego
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
{
- auto const waspassed { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
- auto const switchchanged { sSpeedTable[ i ].Update() };
- if( false == waspassed ) {
- CheckSignalPassedAtDanger( sSpeedTable[ i ] );
- }
- if (switchchanged)
+ if (UpdateSpeedPosition(sSpeedTable[i]))
{
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
@@ -823,11 +818,7 @@ void TController::TableCheck(double fDistance)
}
}
// aktualizacja ostatniego; a signal at stop often is the last, the scan doesn't go past it
- auto const lastwaspassed { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
- sSpeedTable[iLast].Update();
- if( false == lastwaspassed ) {
- CheckSignalPassedAtDanger( sSpeedTable[ iLast ] );
- }
+ UpdateSpeedPosition(sSpeedTable[iLast]);
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
if( sSpeedTable[ iLast ].fDist < fDistance ) {
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
@@ -838,18 +829,31 @@ void TController::TableCheck(double fDistance)
}
};
-void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point ) const
+namespace {
+
+// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop
+bool is_signal_at_stop( TSpeedPos const &Point )
{
- if( false == TestFlag( Point.iFlags, spElapsed )
- || false == TestFlag( Point.iFlags, spEvent )
- || false == TestFlag( Point.iFlags, spSemaphor )
- || true == TestFlag( Point.iFlags, spStopOnSBL ) // SetVelocity 0 x on automatic block: may go on after a stop
- || Point.fVelNext != 0.0
- || Point.evEvent == nullptr
- || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only
- return;
+ return TestFlag( Point.iFlags, spEvent )
+ && TestFlag( Point.iFlags, spSemaphor )
+ && false == TestFlag( Point.iFlags, spStopOnSBL )
+ && std::abs( Point.fVelNext ) <= 0.0
+ && Point.evEvent != nullptr;
+}
+
+} // namespace
+
+bool TController::UpdateSpeedPosition( TSpeedPos &Point ) const
+{
+ auto const passedbefore { TestFlag( Point.iFlags, spElapsed ) };
+ auto const switchchanged { Point.Update() };
+ if( false == passedbefore
+ && TestFlag( Point.iFlags, spElapsed )
+ && is_signal_at_stop( Point )
+ && ( mvOccupied->CategoryFlag & 1 ) != 0 ) { // railway only
+ simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
}
- simulation::Test.signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
+ return switchchanged;
}
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 8c12087f9..8f2015f2f 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -519,8 +519,9 @@ private:
bool TableNotFound( basic_event const *Event, double const Distance ) const;
void TableTraceRoute( double fDistance, TDynamicObject *pVehicle );
void TableCheck( double fDistance );
- // reports the train going past a signal showing stop (SetVelocity 0 0); called once the head passed Point
- void CheckSignalPassedAtDanger( TSpeedPos const &Point ) const;
+ // updates a position of the speed table, returns true when a switch on it changed (TSpeedPos::Update).
+ // reports the head of the train going past it, if it's a signal showing stop
+ bool UpdateSpeedPosition( TSpeedPos &Point ) const;
TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc );
bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance );
bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex );
From dd019d88ba4f45c711e37abe00782c27207ed5be Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:38:37 +0100
Subject: [PATCH 031/104] feat(simulation): the test mode takes no input from
outside (eu07/maszyna#541)
With --test the gamepad, mouse picking, UART, ZeroMQ and motion telemetry are
off, the hidden window gets no key, mouse, scroll or char callbacks, and the
window procedure that takes WM_COPYDATA commands from other programs isn't
installed, so nothing but the scenery drives a test run.
---
application/application.cpp | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index 439c01d97..eaf60c7cd 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1159,9 +1159,16 @@ void apply_test_mode_settings()
Global.minframetime = std::chrono::duration(0.0f);
Global.extra_viewports.clear();
Global.headtrack_conf.joy.clear();
- // a test runs on its own
+ // a test runs on its own: no network, and no input from outside (eu07/maszyna#541)
Global.network_servers.clear();
Global.network_client.reset();
+ Global.InputGamepad = false;
+ Global.InputMouse = false;
+ Global.uart_conf.enable = false;
+ Global.motiontelemetry_conf.enable = false;
+#ifdef WITH_ZMQ
+ Global.zmq_address.clear();
+#endif
// and the same way every time, unless given another seed (-seed, or randomseed in the settings)
if (!Global.random_seed)
Global.random_seed = seed_of("test");
@@ -1431,7 +1438,9 @@ int eu07_application::init_glfw()
#ifdef _WIN32
// setup wrapper for base glfw window proc, to handle copydata messages
Hwnd = glfwGetWin32Window(mainwindow);
- BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
+ // commands sent by other programs are input from outside, which a test doesn't take
+ if (false == Global.test.enabled)
+ BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
// switch off the topmost flag
::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
#endif
@@ -1445,13 +1454,18 @@ void eu07_application::init_callbacks()
auto *window{m_windows.front()};
glfwSetWindowSizeCallback(window, window_resize_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);
+ glfwSetWindowFocusCallback(window, focus_callback);
+ glfwSetCursorEnterCallback(window, cursor_enter_callback);
+ if (Global.test.enabled)
+ {
+ // a test takes no input: keys and clicks sent to its hidden window would change the run
+ return;
+ }
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetCharCallback(window, char_callback);
- glfwSetWindowFocusCallback(window, focus_callback);
- glfwSetCursorEnterCallback(window, cursor_enter_callback);
}
int eu07_application::init_ogl()
From 6ccf4b14bf8a02fb7835dd20837db54ed5a5edcb Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:38:38 +0100
Subject: [PATCH 032/104] feat(simulation): test.no_movement_before_pass, a
pass that doesn't wait for a stop
The config key from eu07/maszyna#541. By default (yes) a pass reported to
__test.result waits until every vehicle has stood still for 1 s; with no it
ends the test at once. The key is listed with the other test.* settings in the
log and in the test start line.
Scenario tests: new case test_mode_pass_while_moving reports the pass from
event2 of tor1k as the train runs onto it and checks the run ended with the
train still moving (new check ends_moving). The README lists the test.* keys
with their defaults and the input the test mode ignores.
---
simulation/simulationtest.cpp | 10 +++++--
tests/scenarios/README.md | 18 +++++++++++-
.../cases/test_mode_pass_while_moving.json | 28 +++++++++++++++++++
tests/scenarios/run.py | 10 +++++++
utilities/Globals.cpp | 7 +++++
utilities/Globals.h | 1 +
6 files changed, 71 insertions(+), 3 deletions(-)
create mode 100644 tests/scenarios/cases/test_mode_pass_while_moving.json
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 439f295fe..8d57505ff 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -82,9 +82,10 @@ void test_manager::start()
}
// a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
Global.iPause = 0;
- WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}", Global.test.timeout, Global.test.standstill,
+ WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}{}", Global.test.timeout, Global.test.standstill,
Global.test.pass_on_standstill ? ", standstill passes" : "",
- Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed"));
+ Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed",
+ Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop"));
}
void test_manager::update(double const Deltatime)
@@ -103,6 +104,11 @@ void test_manager::update(double const Deltatime)
finish(test_result::fail, std::format("__test.result set to 0{}", reason));
return;
}
+ if (holds(value, 1.0) && false == Global.test.no_movement_before_pass)
+ {
+ finish(test_result::pass, std::format("__test.result set to 1{}", reason));
+ return;
+ }
if (holds(value, 1.0) && false == m_passrequested)
{
m_passrequested = true;
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 1ebd84c75..b57fc4a05 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -23,6 +23,9 @@ With `--test` the simulator:
data) but no textures, and the window stays hidden,
- has no sound, no network, no python, no pause (not even one set by the scenery), and
no crash dialog,
+- takes no input from outside: keys and mouse sent to its window, gamepad, UART (a cab
+ desk), ZeroMQ and commands sent by other programs (`WM_COPYDATA`) are all ignored, and
+ motion telemetry is off,
- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
@@ -48,7 +51,7 @@ The test ends with the first of these:
| exit code | result | when |
| --- | --- | --- |
-| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first. Also the standstill end with `test.pass_on_standstill yes` |
+| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first (with `test.no_movement_before_pass no` the pass ends the test at once). Also the standstill end with `test.pass_on_standstill yes` |
| 1 | fail | `__test.result` was set to 0; ends at once |
| 2 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
| 3 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
@@ -65,9 +68,18 @@ test.timeout 600
test.standstill 120
test.pass_on_standstill no
test.fail_if_stop_overran yes
+test.no_movement_before_pass yes
endconfig
```
+| key | default | meaning |
+| --- | --- | --- |
+| `test.timeout` | 3600 | seconds of simulation time before the test ends as `timeout`; 0 = never |
+| `test.standstill` | 300 | seconds with every vehicle still and no result before the test ends as `standstill`; 0 = never |
+| `test.pass_on_standstill` | no | the standstill end passes the test instead |
+| `test.fail_if_stop_overran` | yes | a signal passed at danger ends the test; with `no` it's only logged |
+| `test.no_movement_before_pass` | yes | a pass waits until every vehicle stands still; with `no` it ends the test at once |
+
`--test-timeout` on the command line wins over `test.timeout` of the scenery.
A signal is passed at danger when the head of a train goes past a signal which its driver
@@ -155,6 +167,8 @@ on `tor1k`, the track in front of the signal.
The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass
event), `test_mode_signal_passed_at_danger` (exit 2), `test_mode_timeout` (exit 3, from
`test.timeout`) and `test_mode_standstill` (exit 4, from `test.standstill`).
+`test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto
+it, with `test.no_movement_before_pass no`, so the test ends with the train still moving.
Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
@@ -178,6 +192,8 @@ the row instead, logged by builds from this branch on.
moving off, the wheels stop slipping within `within` seconds.
- `holds_still` `moving_speed`, `stop_speed`, `max_distance` (*vehicle speed*): once stopped
after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels.
+- `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g.
+ the test ended without waiting for the train to stop.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/test_mode_pass_while_moving.json b/tests/scenarios/cases/test_mode_pass_while_moving.json
new file mode 100644
index 000000000..cdf798f16
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_pass_while_moving.json
@@ -0,0 +1,28 @@
+{
+ "description": "Test mode, pass without waiting for a stop: like test_mode_pass, but event2 of the track in front of the exit signal reports the pass as the train runs onto it, and with test.no_movement_before_pass no the test ends at once, the train still moving.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_pass.scn",
+ "track_events": {
+ "tor1k": "event2 test_pass"
+ },
+ "test_config": [
+ "test.no_movement_before_pass no"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "pass",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 150
+ },
+ {
+ "type": "ends_moving",
+ "min_speed": 3
+ }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 770069d12..4c3383081 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -416,6 +416,15 @@ def check_holds_still(rows, moving_speed, stop_speed, max_distance):
return d <= max_distance, detail
+def check_ends_moving(rows, min_speed):
+ """The run ended with the vehicle still moving, e.g. a pass that didn't wait for the trains to stop."""
+ if not rows:
+ return False, "the physicslog is empty"
+ last = rows[-1]
+ ok = last[COL_VELOCITY] >= min_speed
+ return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})"
+
+
def check_slip_clears(rows, moving_speed, stop_speed, within):
"""Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds
(a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion)."""
@@ -444,6 +453,7 @@ CHECKS = {
"stops": check_stops,
"stays_stopped": check_stays_stopped,
"distance": check_distance,
+ "ends_moving": check_ends_moving,
}
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index 5cdb3ef25..2516da29e 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -487,6 +487,12 @@ bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
return true;
}
+ if (token == "test.no_movement_before_pass")
+ {
+ ParseOne(Parser, test.no_movement_before_pass);
+ return true;
+ }
+
return false;
}
@@ -1783,6 +1789,7 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "test.standstill", test.standstill );
export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill );
export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran );
+ export_as_text( Output, "test.no_movement_before_pass", test.no_movement_before_pass );
export_as_text( Output, "gfx.envmap.enabled", gfx_envmap_enabled );
export_as_text( Output, "gfx.postfx.motionblur.enabled", gfx_postfx_motionblur_enabled );
export_as_text( Output, "gfx.postfx.motionblur.shutter", gfx_postfx_motionblur_shutter );
diff --git a/utilities/Globals.h b/utilities/Globals.h
index 8fa04e9ce..a6a9e1226 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -93,6 +93,7 @@ struct global_settings {
double standstill{ 300.0 }; // [s] every vehicle standing still this long ends the test; 0 = never
bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it
bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged
+ bool no_movement_before_pass{ true }; // a pass waits until every vehicle stands still; with false it ends the test at once
bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it
} test;
bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap
From 19b500f9bebdce6125630d3787c5bb684237a099 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:58:20 +0100
Subject: [PATCH 033/104] fix(lights): darken the coupled end with the light
programmer from either cab (eu07/maszyna#395)
SetLights() gives RaLightsSet() the lights for the vehicle's end towards
the head of the consist and the end towards its tail, whichever way the
occupied cab faces. The coupling that switches an end off was looked up
at the opposite end whenever the cab faced the tail of the consist
(e.g. 6Dg driven from its second cab position), so the free end went
dark and the end with the train was lit.
The per-vehicle choice moves to lights_programmer::vehicle_lights() in
vehicle/lightsprogrammer.h, which checks the coupling at the same end
it lights, with unit tests for both cabs, both orientations and the
train at either end. Driving from a cab facing the head of the consist
gives the same lights as before. No data change needed.
---
tests/unit/test_lights_programmer.cpp | 93 +++++++++++++++++++++++++++
vehicle/DynObj.cpp | 30 ++++-----
vehicle/lightsprogrammer.h | 41 ++++++++++++
3 files changed, 148 insertions(+), 16 deletions(-)
create mode 100644 tests/unit/test_lights_programmer.cpp
create mode 100644 vehicle/lightsprogrammer.h
diff --git a/tests/unit/test_lights_programmer.cpp b/tests/unit/test_lights_programmer.cpp
new file mode 100644
index 000000000..8a31563d8
--- /dev/null
+++ b/tests/unit/test_lights_programmer.cpp
@@ -0,0 +1,93 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "vehicle/lightsprogrammer.h"
+
+// the lights the light preset selector (programmer) of the occupied cab gives the vehicles of the consist,
+// TDynamicObject::SetLights(): the cab's front lights at the end the cab faces, its back lights at the other
+// end, and no lights at an end with another vehicle coupled
+
+namespace {
+
+int const pc1{light::headlight_left | light::headlight_upper | light::headlight_right};
+int const tailmarkers{light::redmarker_left | light::redmarker_right};
+std::array const cablights{pc1, tailmarkers}; // Lights[end::front], Lights[end::rear]
+
+// the lights at the vehicle's own end, placed the way TDynamicObject::RaLightsSet() places them
+int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, end const Side) {
+ auto const headend{Direction > 0 ? end::front : end::rear};
+ return Side == headend ? Lights.head : Lights.rear;
+}
+
+struct setup {
+ int cab; // CabOccupied of the vehicle with the programmer
+ int direction; // its iDirection
+ std::array coupled; // vehicle coupled at its end::front / end::rear
+};
+
+lights_programmer::consist_lights lights_for(setup const &Setup) {
+ // TDynamicObject::SetLights(): the cab faces the head of the consist when CabOccupied * DirectionGet() >= 0
+ auto const cabfacinghead{Setup.cab * (Setup.direction > 0 ? 1 : -1) >= 0};
+ return lights_programmer::vehicle_lights(cablights, cabfacinghead, Setup.direction, Setup.coupled);
+}
+
+} // namespace
+
+TEST_CASE("lights programmer: a lone vehicle gets the cab's front lights ahead of the cab and its back lights behind it") {
+ for (auto const direction : {0, 1}) {
+ CAPTURE(direction);
+ // cab 1 faces end::front
+ auto const fromcab1{lights_for({1, direction, {false, false}})};
+ CHECK(lights_at(fromcab1, direction, end::front) == pc1);
+ CHECK(lights_at(fromcab1, direction, end::rear) == tailmarkers);
+ // cab -1 faces end::rear
+ auto const fromcab2{lights_for({-1, direction, {false, false}})};
+ CHECK(lights_at(fromcab2, direction, end::rear) == pc1);
+ CHECK(lights_at(fromcab2, direction, end::front) == tailmarkers);
+ }
+}
+
+TEST_CASE("lights programmer: the end with the train coupled goes dark, not the other one (eu07/maszyna#395)") {
+ // a locomotive driven from either cab, with the train coupled at either end, either way round in the consist.
+ // the end with the train goes dark, the free end shows the lights meant for it
+ for (auto const direction : {0, 1}) {
+ for (auto const cab : {1, -1}) {
+ for (auto const trainend : {end::front, end::rear}) {
+ CAPTURE(direction);
+ CAPTURE(cab);
+ CAPTURE(trainend);
+ std::array coupled{false, false};
+ coupled[trainend] = true;
+ auto const freeend{trainend == end::front ? end::rear : end::front};
+ auto const cabfront{cab > 0 ? end::front : end::rear};
+
+ auto const lights{lights_for({cab, direction, coupled})};
+
+ CHECK(lights_at(lights, direction, trainend) == 0);
+ CHECK(lights_at(lights, direction, freeend) == (freeend == cabfront ? pc1 : tailmarkers));
+ }
+ }
+ }
+}
+
+TEST_CASE("lights programmer: 6Dg driven backwards from its second cab position pulls the train with its head lights lit (eu07/maszyna#395)") {
+ // the reported case: the train coupled behind the driver (end::front, which cab -1 has at its back), the
+ // locomotive running towards end::rear, the train in tow. the head lights stay lit, the end with the train goes dark;
+ // before the fix the couplings were looked up at the swapped ends and it was the other way round
+ auto const lights{lights_for({-1, 1, {true, false}})};
+
+ CHECK(lights_at(lights, 1, end::rear) == pc1);
+ CHECK(lights_at(lights, 1, end::front) == 0);
+}
+
+TEST_CASE("lights programmer: a vehicle coupled at both ends stays dark") {
+ for (auto const direction : {0, 1}) {
+ for (auto const cab : {1, -1}) {
+ CAPTURE(direction);
+ CAPTURE(cab);
+ auto const lights{lights_for({cab, direction, {true, true}})};
+ CHECK(lights.head == 0);
+ CHECK(lights.rear == 0);
+ }
+ }
+}
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index d5f60e332..ce1f89e72 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "vehicle/DynObj.h"
+#include "vehicle/lightsprogrammer.h"
+
#include "simulation/simulation.h"
#include "rendering/lightarray.h"
#include "vehicle/Camera.h"
@@ -7289,26 +7291,22 @@ void TDynamicObject::SetLights() {
auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 };
int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers
? light::redmarker_left + light::redmarker_right : 0 };
- int const front { ( isfrontcaboccupied ? end::front : end::rear ) };
- int const rear { 1 - front };
auto const lightpos { MoverParameters->LightsPos - 1 };
- auto const frontlights { automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ front ][ lightpos ] };
- auto const rearlights { automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ rear ][ lightpos ] };
+ std::array const cablights {
+ automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ],
+ automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] };
+ // the custom position keeps the lights lit at coupled ends as well
+ auto const ignorecouplings { MoverParameters->LightsPos == 18 };
auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, coupling::control ) };
while( vehicle != nullptr ) {
// set lights on given side if there's no coupling with another vehicle, turn them off otherwise
- auto const *frontvehicle{(isfrontcaboccupied ? vehicle->Prev(coupling::coupler) : vehicle->Next(coupling::coupler))};
- auto const *rearvehicle{(isfrontcaboccupied ? vehicle->Next(coupling::coupler) : vehicle->Prev(coupling::coupler))};
-
- if (MoverParameters->LightsPos == 18)
- {
- frontvehicle = nullptr;
- rearvehicle = nullptr;
- }
-
- vehicle->RaLightsSet(
- frontvehicle == nullptr ? frontlights : 0,
- rearvehicle == nullptr ? rearlights : 0 );
+ auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) {
+ return false == ignorecouplings
+ && ( vehicle->MoverParameters->Couplers[ Side ].CouplingFlag & coupling::coupler ) != 0
+ && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } };
+ auto const lights { lights_programmer::vehicle_lights(
+ cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) };
+ vehicle->RaLightsSet( lights.head, lights.rear );
vehicle = isfrontcaboccupied ? vehicle->Next(coupling::control) : vehicle->Prev(coupling::control);
}
};
diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h
new file mode 100644
index 000000000..9ae8c2ab0
--- /dev/null
+++ b/vehicle/lightsprogrammer.h
@@ -0,0 +1,41 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#pragma once
+
+#include
+
+#include "McZapkie/MOVER.h"
+
+// the lights the light preset selector (programmer) of the occupied cab gives one vehicle of the consist
+namespace lights_programmer {
+
+// the lights for the vehicle's two ends, in the terms of TDynamicObject::RaLightsSet(): head is the end
+// towards the head of the consist (TDynamicObject::Prev()), rear the end towards its tail (Next())
+struct consist_lights {
+ int head;
+ int rear;
+};
+
+// Cablights: the selector's lights for the occupied cab's front and back (Lights[end::front / end::rear]).
+// Cabfacinghead: the occupied cab faces the head of the consist.
+// Direction: the vehicle's iDirection, 1 when its end::front is towards the head of the consist.
+// Coupled: whether another vehicle is coupled at the vehicle's end::front / end::rear; an end with a coupled
+// vehicle stays dark
+inline consist_lights vehicle_lights(std::array const &Cablights, bool const Cabfacinghead, int const Direction, std::array const &Coupled) {
+ auto const headlights{Cablights[Cabfacinghead ? end::front : end::rear]};
+ auto const rearlights{Cablights[Cabfacinghead ? end::rear : end::front]};
+ // the head lights go to the vehicle's end towards the head of the consist whichever way the cab faces,
+ // so the coupling which keeps them dark is the one at that same end (eu07/maszyna#395)
+ auto const headend{Direction > 0 ? end::front : end::rear};
+ auto const rearend{Direction > 0 ? end::rear : end::front};
+ return {Coupled[headend] ? 0 : headlights, Coupled[rearend] ? 0 : rearlights};
+}
+
+} // namespace lights_programmer
From f53e184949614cab1aeed8411110694ddbef7c4a Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:37:14 +0100
Subject: [PATCH 034/104] AI braking: hold a train coming to a stand uphill
Uphill a long train often came to a stand with its brake on the way
off and rolled back several metres: the AI released the train brake
to 0 about 20 m short of the stop (the gradient alone would have
stopped the train short of the stopping window), applied only the
first step again at the last moment, and a G train cannot apply its
brake again within the few seconds the gradient takes to stop it.
Coming to a stand on an up gradient (also when only part of the train
is on it) the AI now:
- applies the brake before the train stops on the gradient alone, once
the time left to the stand is no longer than half of what the brake
takes to apply;
- does not let the train coast on or pull up while the brake is applied
and the gradient would stop the train sooner than the brake of the
consist can be released;
- does not release the train brake any further below 10 km/h on the
way to a stand (unless the train is to be driven on);
- puts the locomotive brake on below 3 km/h when the train will reach
the point it is to stop at (not when it has slowed down short of it
and is to pull up), and at once if the train rolls back.
---
vehicle/Driver.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++--
vehicle/Driver.h | 2 ++
2 files changed, 59 insertions(+), 2 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index ea78e655c..75f7bea7a 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3203,6 +3203,12 @@ bool TController::DecBrake() {
// a distributor applied at all gives at least its minimum stage, about what the first position does, so
// a position short of the first one brakes no weaker than that
deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] );
+ }
+ if( ( BrakeCtrlPosition > 0.0 )
+ && ( uphill_stop_hold() ) ) {
+ // any release now raises the pipe, and a long train releases more than the handle is moved back, too late
+ // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it
+ break;
}
if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) {
OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25);
@@ -7341,8 +7347,15 @@ TController::pick_optimal_speed( double const Range ) {
AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
}
else if( ( vel < 0.0 )
- || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) ) {
- AccDesired = std::min( AccDesired, fAccGravity - 0.15 );
+ || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) )
+ // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops:
+ // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any
+ // sooner and the brake takes off more of the distance than the stop was planned with
+ || ( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) {
+ // the gradient alone already slows the train down nearly this much; ask for enough on top of it that
+ // the brake is applied for sure, not held back by the margin against small corrections
+ AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() );
}
}
@@ -7651,6 +7664,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
( VelNext * VelNext - vel * vel ) / ( 25.92 * stoppingroom ) );
if( ( fAccGravity < -0.025 )
&& ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
+ && ( false == uphill_brake_committed( vel ) )
&& ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > stopping_margin() ) ) {
// uphill the gradient alone would bring the train to a stand short of the
// middle of the stopping window; keep it rolling at the present speed until that changes,
@@ -7726,6 +7740,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else if( ( fAccGravity < -0.025 )
&& ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( false == uphill_brake_committed( vel ) )
&& ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > brakingpointoffset ) ) {
// uphill the gradient alone slows the train down more than it is asked to;
// keep it rolling at the present speed until that changes
@@ -8177,6 +8192,35 @@ TController::brake_increase_margin() const {
return fBrake_a1[ 0 ];
}
+// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be
+// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the
+// locomotive brake, which acts at once, helps to hold the train
+bool
+TController::uphill_stop_hold() const {
+
+ return (
+ ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( VelNext == 0.0 )
+ && ( ActualProximityDist <= fMaxProximityDist )
+ && ( fAccGravity < -0.005 )
+ && ( std::abs( DirectionalVel() ) < 10.0 )
+ // not while the train is to be driven on
+ && ( AccDesired <= 0.0 ) );
+}
+
+// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist
+// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the
+// train stands with the brake on its way off instead
+bool
+TController::uphill_brake_committed( double const Velocity ) const {
+
+ return (
+ ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( BrakeCtrlPosition > 0.0 )
+ && ( fAccGravity < -0.025 )
+ && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) );
+}
+
void TController::control_braking_force() {
// don't touch the brakes when compressing buffers during coupling/uncoupling
@@ -8276,6 +8320,17 @@ void TController::control_braking_force() {
cue_action(driver_hint::brakingforcedecrease,
(mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1
}
+ // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply:
+ // put it on as the train comes to a stand, and at once if the train has started to roll back
+ if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake )
+ && ( mvOccupied->LocalBrakePosA < 1.0 )
+ && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 )
+ // a train that has slowed down short of where it is to stop and is to pull up further does not get it
+ && ( VelDesired <= std::abs( velocity ) + 0.5 )
+ && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) )
+ || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < -0.005 ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) {
+ cue_action( driver_hint::independentbrakeapply );
+ }
// stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry
// instead of releasing the brakes and creeping into obstacle at 1-2 km/h
if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) {
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index f1975fca6..82899493a 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -312,6 +312,8 @@ private:
return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); }
double brake_increase_margin() const;
+ bool uphill_stop_hold() const;
+ bool uphill_brake_committed( double const Velocity ) const;
void update_timers( double const dt );
void update_logs( double const dt );
From 8d1d9eec9b2f2e0ae15dc20f21c943e7f9693c89 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 18:10:47 +0100
Subject: [PATCH 035/104] AI braking: smaller steps, earlier, while approaching
a stop or a lower speed
Changes to how the AI works the train brake on the way to a lower speed
or a stop, so that it uses few, early applications instead of a late
deep one:
- Approaching a lower speed, the deceleration may fall short of the
demand by only half of a step (fBrake_a1) before the brake is applied
harder. With a full step the demand crept up meanwhile and a long G
train got its next step many seconds too late.
- The shortfall is checked every 3 s. If it keeps growing at a handle
left alone for longer than the brake takes to respond, the AI adds a
small step at once instead of waiting until the margin calls for a
deep one. A shortfall that shrinks on its own (brake still filling,
blocks gripping harder at lower speed) does not trigger it.
- Releasing, a position short of the first one counts as giving the
minimum stage of the distributor, not less.
- Holding the speed on a descent, the predicted excess speed is taken
off over the time the brake takes to respond, not at once, so a slow
brake does not get a deep application that then takes as long to
release.
---
vehicle/Driver.cpp | 69 ++++++++++++++++++++++++++++++++++++++++------
vehicle/Driver.h | 5 ++++
2 files changed, 65 insertions(+), 9 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 8d2a3fac6..ea78e655c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -2928,6 +2928,9 @@ bool TController::ReleaseEngine() {
return OK;
}
+// defined further down, with the braking demand it is used for
+static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 );
+
bool TController::IncBrake()
{ // zwiększenie hamowania
auto OK { false };
@@ -3040,7 +3043,7 @@ bool TController::IncBrake()
}
double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
- if( deltaAcc > fBrake_a1[0])
+ if( deltaAcc > brake_increase_margin() )
{
if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
OK = /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ); //GBH
@@ -3069,10 +3072,13 @@ bool TController::IncBrake()
}
else if( BrakeCtrlPosition > 0.0
&& AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
- && fBrakeHeldTime > (
- mvOccupied->BrakeDelayFlag > bdelay_G ?
- mvOccupied->BrakeDelay[ 1 ] :
- mvOccupied->BrakeDelay[ 3 ] ) ) {
+ && ( fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] )
+ // a train falling further behind needs no full fill time to be seen not to get enough
+ || ( ( fShortfall > 0.02 )
+ && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) {
// the table says the present position is enough, but the brake has had its full fill
// time since the handle last moved and the train is still not slowing down as asked:
// believe the train rather than the table
@@ -3194,7 +3200,9 @@ bool TController::DecBrake() {
if( fBrake_a0[0] != 0.0
|| fBrake_a1[0] != 0.0 ) {
auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) };
- deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - pos_diff )*fBrake_a1[ 0 ] );
+ // a distributor applied at all gives at least its minimum stage, about what the first position does, so
+ // a position short of the first one brakes no weaker than that
+ deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] );
}
if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) {
OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25);
@@ -7701,7 +7709,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
// train is still speeding up, the prediction above has taken that off already)
auto room { brakingroom };
if( ( AbsAccS <= 0.0 )
- && ( ( VelNext > 0.0 ) || ( BrakeCtrlPosition <= 0.0 ) ) ) { // for a stop, only while the brake is still to be applied
+ && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind
room = std::max(
0.5 * brakingroom,
brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
@@ -7830,6 +7838,10 @@ TController::adjust_desired_speed_for_current_speed() {
BrakeSystem == TBrakeSystem::Pneumatic ?
std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
+ // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a
+ // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as
+ // long to let go, and the train ends up well below the speed it was to hold
+ auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) };
if( ( speedestimate > VelDesired )
&& ( VelDesired == 0.0 ) ) {
// jesli stoj, to hamuj, ale i tak juz za pozno :)
@@ -7843,7 +7855,7 @@ TController::adjust_desired_speed_for_current_speed() {
AccDesired = std::min(
AccDesired, // but don't override decceleration for VelNext
std::clamp(
- EU07_AI_NOACCELERATION - 0.04 * ( speedestimate - holdspeed ),
+ EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ),
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
@@ -8151,6 +8163,20 @@ void TController::increase_tractive_force() {
cue_action( driver_hint::tractiveforceincrease );
}
+// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower
+// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand
+// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough
+double
+TController::brake_increase_margin() const {
+
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( VelNext > 0.0 )
+ && ( VelNext < DirectionalVel() ) ) {
+ return 0.5 * fBrake_a1[ 0 ];
+ }
+ return fBrake_a1[ 0 ];
+}
+
void TController::control_braking_force() {
// don't touch the brakes when compressing buffers during coupling/uncoupling
@@ -8168,6 +8194,19 @@ void TController::control_braking_force() {
// resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
+ // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake
+ // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a
+ // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve
+ if( ElapsedTime - fShortfallTime >= 3.0 ) {
+ auto const shortfall { AbsAccS - accdesiredresultant };
+ iShortfallGrowth = (
+ ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ?
+ iShortfallGrowth + 1 :
+ 0 );
+ fShortfall = shortfall;
+ fShortfallTime = ElapsedTime;
+ }
+
if( is_emu() && !ForcePNBrake ) {
// właściwie, to warunek powinien być na działający EP
// Ra: to dobrze hamuje EP w EZT
@@ -8201,7 +8240,7 @@ void TController::control_braking_force() {
} // type & dt_ezt
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
- if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + fBrake_a1[0] // regular braking
+ if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking
|| fAccGravity < -0.05 && velocity < -0.1) && // also brake if uphill and slipping back
(fBrakeTime < 0.0
// the size of the brake demand decides whether to skip the reaction time, so the brake-only part
@@ -8214,6 +8253,18 @@ void TController::control_braking_force() {
// Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy
(3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1
}
+ else if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AccDesired < 0.0 )
+ && ( BrakeCtrlPosition > 0.0 )
+ && ( fShortfall > 0.02 )
+ && ( iShortfallGrowth >= 2 )
+ && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) {
+ // the train has been falling further behind the demand for a while at a handle left alone for longer than
+ // the brake takes to respond: a small step now, while it still is small, rather than the deep one the
+ // margin above would allow only once the train is far behind
+ cue_action( driver_hint::brakingforceincrease );
+ iShortfallGrowth = 0;
+ }
if ( (accdesiredresultant < fAccGravity - 0.05
|| AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) {
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 11a01517f..f1975fca6 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -311,6 +311,8 @@ private:
double DirectionalVel() const {
return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); }
+ double brake_increase_margin() const;
+
void update_timers( double const dt );
void update_logs( double const dt );
void determine_consist_state();
@@ -401,6 +403,9 @@ private:
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego
+ double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2]
+ double fShortfallTime = 0.0; // when that was checked
+ int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From 137eb9641f0ea9fa93596c8a4be959f2342d0ba3 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:37:48 +0100
Subject: [PATCH 036/104] AI: start a train uphill on the train brake
Starting uphill the AI released the train brake (and the locomotive
brake with it) at once, while the power came on only later: a train on
10 per mille rolled back 20-30 m (E186 with 19 container wagons), and an
E189 with 7 Z2 coaches rolled back for minutes without power, because
the brake applied again for the rollback kept the power off. Many
locomotives cannot pull while their own cylinder is under pressure
(asynchronous drives switch to braking, others have a control pressure
switch), so holding the train on the locomotive brake is no way out.
A train standing on an up gradient with the train brake applied now
starts as a driver of a heavy train does:
- the train brake stays applied, the locomotive brake is released and
the locomotive's own share of the train brake is let off with the
releaser;
- the power is applied against the braked train (Ready does not hold
it back meanwhile, and the rule that brakes a train slipping back
is off);
- the train brake is released only once the tractive force exceeds 1.1
times the gradient force, the train moves forward, or after 45 s if
the locomotive cannot hold the train on its own power.
Multiple units are not affected.
---
vehicle/Driver.cpp | 73 +++++++++++++++++++++++++++++++++++++++++++---
vehicle/Driver.h | 3 ++
2 files changed, 72 insertions(+), 4 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 75f7bea7a..1a4d8e3a5 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3204,6 +3204,10 @@ bool TController::DecBrake() {
// a position short of the first one brakes no weaker than that
deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] );
}
+ if( bUphillStart ) {
+ // starting uphill the train brake holds the train until the power does
+ break;
+ }
if( ( BrakeCtrlPosition > 0.0 )
&& ( uphill_stop_hold() ) ) {
// any release now raises the pipe, and a long train releases more than the handle is moved back, too late
@@ -5947,6 +5951,8 @@ TController::determine_consist_state() {
{ // sprawdzenie odhamowania wszystkich połączonych pojazdów
auto *vehicle { p->MoverParameters };
auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) };
+ // starting uphill the power is applied against the train brake on purpose, until the power holds the train
+ auto const heldforstart { bUphillStart };
if (Ready) {
// bo jak coś nie odhamowane, to dalej nie ma co sprawdzać
if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) };
@@ -5955,7 +5961,9 @@ TController::determine_consist_state() {
// once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor
// is still in the lap position while the brake pipe recharges
( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN
- Ready = false;
+ if( false == heldforstart ) {
+ Ready = false;
+ }
}
// Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka...
if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy
@@ -5973,7 +5981,7 @@ TController::determine_consist_state() {
vehicle->BrakeReleaser(0);
}
}
- fReady = std::max( bp, fReady ); // szukanie najbardziej zahamowanego
+ fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego
if( ( dy = p->VectorFront().y ) != 0.0 ) {
// istotne tylko dla pojazdów na pochyleniu
// ciężar razy składowa styczna grawitacji
@@ -8109,6 +8117,8 @@ void TController::control_motor_connectors() {
void TController::control_tractive_force() {
+ control_uphill_start();
+
auto const velocity { DirectionalVel() };
// jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz...
if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up
@@ -8156,6 +8166,58 @@ bool TController::is_too_fast_uphill() const {
return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 );
}
+// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the
+// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train
+// brake only once the power holds the train. releasing everything first lets the train roll back before the power is
+// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous
+// drives, the control pressure switch)
+void TController::control_uphill_start() {
+
+ auto const velocity { DirectionalVel() };
+ auto const uphill {
+ ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && is_train()
+ && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it
+ && ( fAccGravity < -0.01 ) };
+ if( false == uphill ) {
+ bUphillStart = false;
+ return;
+ }
+ if( false == bUphillStart ) {
+ if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT )
+ && ( AccDesired > EU07_AI_NOACCELERATION )
+ && ( VelDesired > 0.0 )
+ && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train
+ bUphillStart = true;
+ fUphillStartTime = ElapsedTime;
+ }
+ else {
+ return;
+ }
+ }
+ if( AccDesired <= EU07_AI_NOACCELERATION ) {
+ // no longer to start: the standing rules take over
+ bUphillStart = false;
+ return;
+ }
+ if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake )
+ && ( mvOccupied->LocalBrakePosA > 0.0 ) ) {
+ cue_action( driver_hint::independentbrakerelease );
+ }
+ auto tractiveforce { 0.0 };
+ for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
+ tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft );
+ }
+ auto const holdingforce { fMass * -fAccGravity };
+ if( ( velocity > 1.0 )
+ || ( tractiveforce > 1.1 * holdingforce )
+ // a locomotive that can't hold the train on its own power gets the brake off in the end all the same
+ || ( ElapsedTime - fUphillStartTime > 45.0 ) ) {
+ // the power holds the train: the train brake can be released
+ bUphillStart = false;
+ }
+}
+
void TController::increase_tractive_force() {
if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać
@@ -8285,7 +8347,7 @@ void TController::control_braking_force() {
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking
- || fAccGravity < -0.05 && velocity < -0.1) && // also brake if uphill and slipping back
+ || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back
(fBrakeTime < 0.0
// the size of the brake demand decides whether to skip the reaction time, so the brake-only part
// (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow)
@@ -8401,7 +8463,10 @@ void TController::control_releaser() {
// this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
// the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
if( mvOccupied->BrakePress > 0.4
- && mvOccupied->Hamulec->GetCRP() > 4.9
+ && ( mvOccupied->Hamulec->GetCRP() > 4.9
+ // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go
+ // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied)
+ || bUphillStart )
&& mvOccupied->Vel < 1.0 ) {
actuate = true;
}
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 82899493a..895e638c5 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -314,6 +314,7 @@ private:
double brake_increase_margin() const;
bool uphill_stop_hold() const;
bool uphill_brake_committed( double const Velocity ) const;
+ void control_uphill_start();
void update_timers( double const dt );
void update_logs( double const dt );
@@ -408,6 +409,8 @@ private:
double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2]
double fShortfallTime = 0.0; // when that was checked
int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown
+ bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does
+ double fUphillStartTime = 0.0; // when the uphill start began
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From d7c66fa7bcdcb4af351591cf2d1b7dd51273f29b Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 18:10:59 +0100
Subject: [PATCH 037/104] feat: bistable hold coil lever of the line breaker
(eu07/maszyna#364)
main_off_bt declared with "type: toggle" in the cab's .mmd is now the
line breaker's hold coil lever of the ET22 and EP09: it stays where it is
put. Off, it opens the line breaker and keeps it from closing (also
cancelling a closing armed by a held main_on_bt); back on, it only feeds
the coil again. The single keyboard key puts the lever back on before
closing, and a line breaker closed by the AI or through the control
cable puts the lever back on to match.
TGauge now remembers whether type: was given, since every control
defaults to toggle. Without type: on main_off_bt (all vehicles today)
nothing changes.
Data (SVN, not part of this commit): add "type: toggle" to main_off_bt:
in dynamic/pkp/et22_v3/*.mmd and dynamic/pkp/ep09_v1, ep09_v2/*.mmd.
Older exes ignore it.
---
tests/unit/test_hold_coil_lever.cpp | 30 +++++++++++++++++++
vehicle/Gauge.cpp | 1 +
vehicle/Gauge.h | 4 +++
vehicle/Train.cpp | 45 +++++++++++++++++++++++++++--
vehicle/holdcoillever.h | 34 ++++++++++++++++++++++
5 files changed, 112 insertions(+), 2 deletions(-)
create mode 100644 tests/unit/test_hold_coil_lever.cpp
create mode 100644 vehicle/holdcoillever.h
diff --git a/tests/unit/test_hold_coil_lever.cpp b/tests/unit/test_hold_coil_lever.cpp
new file mode 100644
index 000000000..cd3a3fee5
--- /dev/null
+++ b/tests/unit/test_hold_coil_lever.cpp
@@ -0,0 +1,30 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "vehicle/holdcoillever.h"
+
+// the lever of the line breaker's hold coil on the ET22 and the EP09 stays where it's put (eu07/maszyna#364), when the
+// cab declares its main_off_bt control with "type: toggle"; otherwise main_off_bt is the push button it always was
+
+TEST_CASE("hold coil lever: only a main_off_bt declared as a toggle switch is the bistable lever (eu07/maszyna#364)") {
+ CHECK(hold_coil_lever::is_bistable(true, true));
+ // declared as a push button
+ CHECK_FALSE(hold_coil_lever::is_bistable(true, false));
+ // no type given: a control defaults to the toggle type, which existing cabs relied on for the push button
+ CHECK_FALSE(hold_coil_lever::is_bistable(false, true));
+}
+
+TEST_CASE("hold coil lever: operated, it goes over to the other position and stays there") {
+ // on: the hold coil fed, the line breaker can close
+ CHECK_FALSE(hold_coil_lever::cuts_off(0.f));
+ auto const off{hold_coil_lever::operated(0.f)};
+ CHECK(off == doctest::Approx(1.f));
+ CHECK(hold_coil_lever::cuts_off(off));
+ // operated again it goes back on
+ auto const on{hold_coil_lever::operated(off)};
+ CHECK(on == doctest::Approx(0.f));
+ CHECK_FALSE(hold_coil_lever::cuts_off(on));
+ // caught on the way between the positions it goes to the far one
+ CHECK(hold_coil_lever::operated(0.3f) == doctest::Approx(1.f));
+ CHECK(hold_coil_lever::operated(0.7f) == doctest::Approx(0.f));
+}
diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp
index af8e9a060..080efaef2 100644
--- a/vehicle/Gauge.cpp
+++ b/vehicle/Gauge.cpp
@@ -249,6 +249,7 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) {
gaugetype == "delayed" ? push_delayed :
gaugetype == "pushtoggle" ? pushtoggle :
toggle; // "toggle" and default
+ m_typedeclared = true;
}
else if( key == "soundinc:" ) {
m_soundfxincrease.deserialize( Input, sound_type::single );
diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h
index fdef9c58e..54d8504da 100644
--- a/vehicle/Gauge.h
+++ b/vehicle/Gauge.h
@@ -58,6 +58,9 @@ public:
// returns offset of submodel associated with the button from the model centre
glm::vec3 model_offset() const;
TGaugeType type() const;
+ // whether the definition of the control declared its type, rather than left it at the default
+ bool type_declared() const {
+ return m_typedeclared; }
inline
bool is_push() const {
return ( static_cast( type() ) & static_cast( TGaugeType::push ) ) != 0; }
@@ -87,6 +90,7 @@ private:
// members
TGaugeAnimation m_animation { TGaugeAnimation::gt_Unknown }; // typ ruchu
TGaugeType m_type { TGaugeType::toggle }; // switch type
+ bool m_typedeclared { false }; // the type was given with type: in the definition
float m_friction { 0.f }; // hamowanie przy zliżaniu się do zadanej wartości
float m_targetvalue { 0.f }; // wartość docelowa
float m_value { 0.f }; // wartość obecna
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..5265d755b 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "vehicle/Train.h"
#include "vehicle/horn.h"
+#include "vehicle/holdcoillever.h"
#include "utilities/Globals.h"
#include "simulation/simulation.h"
@@ -3646,6 +3647,15 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data
}
}
+namespace
+{
+// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364)
+bool is_hold_coil_lever(TGauge const &Button)
+{
+ return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle);
+}
+} // namespace
+
void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command)
{
@@ -3655,6 +3665,11 @@ void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Comm
if (Train->m_linebreakerstate == 0)
{
// ...to close the circuit
+ if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue()))
+ {
+ // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close
+ Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch);
+ }
// NOTE: bit of a dirty shortcut here
OnCommand_linebreakerclose(Train, Command);
}
@@ -3694,7 +3709,18 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman
if (Command.action == GLFW_PRESS)
{
// visual feedback
- if (Train->ggMainOffButton.SubModel != nullptr)
+ if (is_hold_coil_lever(Train->ggMainOffButton))
+ {
+ // the bistable lever goes over to its other position and stays there
+ auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())};
+ Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch);
+ if (false == hold_coil_lever::cuts_off(position))
+ {
+ // the hold coil is fed again, which by itself doesn't close the line breaker
+ return;
+ }
+ }
+ else if (Train->ggMainOffButton.SubModel != nullptr)
{
Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch);
}
@@ -3731,8 +3757,9 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman
{
Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch);
}
- if (Train->ggMainOffButton.SubModel != nullptr)
+ if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton))
{
+ // (the bistable hold coil lever stays where it was put)
Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch);
}
// and the two-state switch too, for good measure
@@ -8365,6 +8392,20 @@ bool TTrain::Update(double const Deltatime)
// because the state of the line breaker isn't changed to match, we need to do it here manually
m_linebreakerstate = 0;
}
+ if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue()))
+ {
+ if (true == mvControlled->Mains)
+ {
+ // the line breaker was closed with the hold coil lever off, by the AI or through the control cable:
+ // put the lever back on to match, like the line breaker state above
+ ggMainOffButton.UpdateValue(0.0);
+ }
+ else if (m_linebreakerstate == 2)
+ {
+ // the hold coil was cut off while the closing button was held, the line breaker won't close on its release
+ m_linebreakerstate = 0;
+ }
+ }
if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) ||
ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 ||
diff --git a/vehicle/holdcoillever.h b/vehicle/holdcoillever.h
new file mode 100644
index 000000000..005bccbd5
--- /dev/null
+++ b/vehicle/holdcoillever.h
@@ -0,0 +1,34 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#pragma once
+
+// the lever of the line breaker's hold coil (eu07/maszyna#364), as on the ET22 and the EP09: the cab's main_off_bt
+// control declared with "type: toggle" stays in the position it's put in. Position 0 keeps the hold coil fed, so the
+// line breaker can be closed; position 1 cuts the coil off, which opens the line breaker and keeps it from closing
+// until the lever is put back. Without the declared type main_off_bt stays the push button it always was, which
+// opens the line breaker and springs back.
+namespace hold_coil_lever {
+
+// whether the main_off_bt control is the bistable lever, from the type its definition declares, if it declares one
+inline bool is_bistable(bool const Typedeclared, bool const Toggletype) {
+ return Typedeclared && Toggletype;
+}
+
+// whether the lever in the given position cuts off the hold coil
+inline bool cuts_off(float const Position) {
+ return Position > 0.5f;
+}
+
+// the position the lever goes to when it's operated: the other one
+inline float operated(float const Position) {
+ return cuts_off(Position) ? 0.f : 1.f;
+}
+
+} // namespace hold_coil_lever
From d8f3875929b6fd4829cc6c69ea52de6f03892e0b Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 18:22:42 +0100
Subject: [PATCH 038/104] fix(gfx): diesel smoke only once the engine fires,
not while the starter turns (eu07/maszyna#523)
The smoke of a diesel came out at full strength the moment its ignition
set Mains and started the spin up, together with the ignition sound, whose
first part is the starter cranking the engine.
The ignition now starts a countdown of the new optional .fiz parameter
SmokeDelay (Engine section of DieselEngine and DieselElectric vehicles,
seconds, default 2.0, 0 restores the old behaviour); the smoke source of
the vehicle spawns nothing until it runs out. Engines already running, or
switched on another way, smoke as before. No SVN data change is needed;
vehicle authors may tune SmokeDelay to the cranking part of their
ignition: sample.
---
McZapkie/MOVER.h | 4 +++
McZapkie/Mover.cpp | 7 ++++
tests/unit/test_smoke.cpp | 68 +++++++++++++++++++++++++++++++++++++++
vehicle/smoke.cpp | 2 +-
vehicle/smoke.h | 1 +
5 files changed, 81 insertions(+), 1 deletion(-)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..f39de8e26 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2171,6 +2171,10 @@ class TMoverParameters
bool dizel_startup{false}; // engine startup procedure request indicator
bool dizel_ignition{false}; // engine ignition request indicator
bool dizel_spinup{false}; // engine spin up to idle speed flag
+ // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the .fiz,
+ // seconds from the start of the spin up) has passed. 0 lets it out as soon as the starter turns, as before eu07/maszyna#523
+ double dizel_SmokeDelay{2.0};
+ double dizel_FiringCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own
double dizel_engagedeltaomega = 0.0; /*roznica predkosci katowych tarcz sprzegla*/
double dizel_n_old = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/
double dizel_Torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..8632e404e 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -7843,6 +7843,9 @@ bool TMoverParameters::dizel_Update(double dt)
WaterHeaterCheck(dt);
OilPumpCheck(dt);
FuelPumpCheck(dt);
+ // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over
+ dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0);
+
if (true == dizel_startup && true == dizel_StartupCheck())
{
dizel_ignition = true;
@@ -7857,6 +7860,7 @@ bool TMoverParameters::dizel_Update(double dt)
LastSwitchingTime = 0;
Mains = true;
dizel_spinup = true;
+ dizel_FiringCountdown = dizel_SmokeDelay;
enrot = std::max(enrot,
0.35 * ( // TODO: dac zaleznie od temperatury i baterii
EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0));
@@ -11365,6 +11369,9 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input)
// oil pump
extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, "");
extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, "");
+ // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523)
+ extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "");
+ dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay);
// engine cooling factore
extract_value(dizel_heat.kw, "HeatKW", Input, "");
extract_value(dizel_heat.kv, "HeatKV", Input, "");
diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp
index 05fb8ae8b..a1ea788f3 100644
--- a/tests/unit/test_smoke.cpp
+++ b/tests/unit/test_smoke.cpp
@@ -2,6 +2,7 @@
#include "doctest.h"
#include "vehicle.h"
+#include "drive.h"
#include "vehicle/smoke.h"
@@ -83,3 +84,70 @@ TEST_CASE("smoke: the pending particles never outgrow the room of the source") {
CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, 10.0) == rate.limit);
}
+
+TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") {
+ auto vehicle{diesel()};
+ vehicle->dizel_spinup = true;
+ auto pending{source};
+ pending.pending = 5.f;
+
+ vehicle->dizel_FiringCountdown = 0.5;
+ CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f);
+
+ vehicle->dizel_FiringCountdown = 0.0;
+ CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f);
+}
+
+namespace {
+
+// the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains)
+bool start_engine(test::driven const &Driven, test::track const &Track) {
+ for (int second = 0; second < 120 && false == Driven.controlling.Mains; ++second) {
+ test::start_up(Driven, Track, 1.0);
+ }
+ return Driven.controlling.Mains;
+}
+
+} // namespace
+
+TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDelay after the starter began (#523)") {
+ // a diesel with a mechanical transmission and a diesel-electric one
+ for (auto const *path : {"sm42_v1/6d1", "st44_v2/m62-1151"}) {
+ CAPTURE(path);
+ test::track const track{};
+ {
+ // the default delay
+ test::vehicle locomotive{test::definition::fiz(path)};
+ REQUIRE(locomotive->dizel_SmokeDelay == doctest::Approx(2.0));
+ auto const driven{test::driving(locomotive)};
+ REQUIRE(start_engine(driven, track));
+ // the engine started less than a second ago: the starter still turns it
+ CHECK(locomotive->dizel_FiringCountdown > 0.5);
+ CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f);
+ // it has fired since
+ test::drive(driven, track, 3.0);
+ CHECK(locomotive->Mains);
+ CHECK(locomotive->dizel_FiringCountdown == 0.0);
+ CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
+ }
+ {
+ // SmokeDelay=0: smoke as soon as the starter turns, as before
+ test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 0)};
+ REQUIRE(locomotive->dizel_SmokeDelay == 0.0);
+ auto const driven{test::driving(locomotive)};
+ REQUIRE(start_engine(driven, track));
+ CHECK(locomotive->dizel_FiringCountdown == 0.0);
+ CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
+ }
+ {
+ // a longer delay from the .fiz
+ test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 5)};
+ auto const driven{test::driving(locomotive)};
+ REQUIRE(start_engine(driven, track));
+ test::drive(driven, track, 3.0);
+ CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f);
+ test::drive(driven, track, 3.0);
+ CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
+ }
+ }
+}
diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp
index b6e923222..f5f64bef0 100644
--- a/vehicle/smoke.cpp
+++ b/vehicle/smoke.cpp
@@ -34,7 +34,7 @@ double engine_load(TMoverParameters const &Mover) {
} // namespace
float vehicle_spawn_count(TMoverParameters const &Mover, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) {
- if (false == Ontracks) {
+ if (false == Ontracks || Mover.dizel_FiringCountdown > 0.0) {
return 0.f;
}
// the steady rate of the source, the way a source of the scenery spawns...
diff --git a/vehicle/smoke.h b/vehicle/smoke.h
index e9dac2622..dbcc131ae 100644
--- a/vehicle/smoke.h
+++ b/vehicle/smoke.h
@@ -25,6 +25,7 @@ struct spawn_rate {
// number of particles the smoke source of a vehicle has to spawn after Timedelta seconds: the steady rate of the
// source, plus a share which grows with the work of its engine. a vehicle taken off the tracks (Ontracks false: gone through a portal, or waiting in the pool of the road
// traffic) puffs no more, the particles it already let out fade away as usual
+// an engine the starter turns but which hasn't fired yet (TMoverParameters::dizel_FiringCountdown) lets out no smoke either
float vehicle_spawn_count(TMoverParameters const &Mover, bool Ontracks, spawn_rate const &Rate, double Timedelta);
} // namespace smoke
From e8c4f3592e21ee431dca6947b4f9b4bbac625076 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 18:47:41 +0100
Subject: [PATCH 039/104] fix: fpslimit paced in integer clock ticks, FPS shown
counts the wait (eu07/maszyna#416)
The limiter slept off the rest of each frame with sleep_for() given a float
duration. MSVC adds that to steady_clock::now() in float nanoseconds, so after
a few hours of system uptime the wake-up time is rounded to tens of ms: at
95 h uptime fpslimit 60 had no effect at all and fpslimit 30 gave ~22 fps, in
the full and the legacy renderer alike.
frame_pacer now schedules frames on a fixed cadence in steady_clock ticks and
the loop waits with sleep_until; an overshooting wait is made up in the next
frame. The FPS shown and the motion blur use the new mainloop_period stopwatch
(frame start to frame start, wait included); the targetfps/fpsaverage
draw-range controllers keep reading the work time as before.
(eu07/maszyna#416)
---
application/application.cpp | 13 +++-
rendering/opengl33renderer.cpp | 9 ++-
rendering/openglrenderer.cpp | 9 ++-
tests/unit/test_framepacer.cpp | 110 +++++++++++++++++++++++++++++++++
utilities/Timer.h | 1 +
utilities/framepacer.h | 59 ++++++++++++++++++
6 files changed, 192 insertions(+), 9 deletions(-)
create mode 100644 tests/unit/test_framepacer.cpp
create mode 100644 utilities/framepacer.h
diff --git a/application/application.cpp b/application/application.cpp
index 9b7b82853..64693b4dc 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/translation.h"
#include "vehicle/Train.h"
#include "utilities/Timer.h"
+#include "utilities/framepacer.h"
#include "utilities/dictionary.h"
#include "version_info.h"
#include
@@ -479,9 +480,14 @@ bool eu07_application::is_client() const
int eu07_application::run()
{
auto frame{0};
+ frame_pacer framepacer;
+ Timer::subsystem.mainloop_period.start();
// main application loop
while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty())
{
+ // the time from one frame's start to the next, the wait for fpslimit included
+ Timer::subsystem.mainloop_period.stop();
+ Timer::subsystem.mainloop_period.start();
Timer::subsystem.mainloop_total.start();
glfwPollEvents();
@@ -641,10 +647,11 @@ int eu07_application::run()
if (m_network)
m_network->update();
- auto const frametime{Timer::subsystem.mainloop_total.stop()};
- if (Global.minframetime.count() != 0.0f && (Global.minframetime - frametime).count() > 0.0f)
+ Timer::subsystem.mainloop_total.stop();
+ // fpslimit: wait for the next frame's slot (eu07/maszyna#416)
+ if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)})
{
- std::this_thread::sleep_for(Global.minframetime - frametime);
+ std::this_thread::sleep_until(*nextframe);
}
}
// Handled by application.exit
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index c24f750c8..aa37c83e2 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -5663,12 +5663,15 @@ void opengl33_renderer::Update(double const Deltatime)
}
m_updateaccumulator = 0.0;
- m_framerate = 1000.f / ( Timer::subsystem.mainloop_total.average() );
+ // the frames actually shown, the wait for fpslimit included (eu07/maszyna#416)
+ m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() );
+ // the frames the work alone would allow, so a frame rate held down by fpslimit doesn't cut the draw ranges
+ auto const workframerate{1000.f / Timer::subsystem.mainloop_total.average()};
// adjust draw ranges etc, based on recent performance
if (Global.targetfps != 0.0f) {
- float fps_diff = Global.targetfps - m_framerate;
+ float fps_diff = Global.targetfps - workframerate;
if (fps_diff > 0.0f)
Global.fDistanceFactor = std::max(0.5f, Global.fDistanceFactor - 0.05f);
else
@@ -5676,7 +5679,7 @@ void opengl33_renderer::Update(double const Deltatime)
}
// legacy framerate parameters
else if (Global.fFpsAverage != 0.f) {
- auto const fps_diff = m_framerate - Global.fFpsAverage;
+ auto const fps_diff = workframerate - Global.fFpsAverage;
if (fps_diff < -Global.fFpsDeviation) {
Global.fDistanceFactor = std::min(std::max(1.0f, Global.fDistanceFactor - 0.05f), Global.gfx_distance_factor_max);
}
diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp
index 180dba771..e09aad917 100644
--- a/rendering/openglrenderer.cpp
+++ b/rendering/openglrenderer.cpp
@@ -4327,12 +4327,15 @@ opengl_renderer::Update( double const Deltatime ) {
}
m_updateaccumulator = 0.0;
- m_framerate = 1000.f / ( Timer::subsystem.gfx_total.average() );
+ // the frames actually shown, the wait for fpslimit included (eu07/maszyna#416)
+ m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() );
+ // the draw ranges follow the time spent on drawing alone, as before
+ auto const drawframerate { 1000.f / ( Timer::subsystem.gfx_total.average() ) };
// adjust draw ranges etc, based on recent performance
// TODO: it doesn't make much sense with vsync
if( Global.targetfps != 0.f ) {
- auto const fps_diff = m_framerate - Global.targetfps;
+ auto const fps_diff = drawframerate - Global.targetfps;
if( fps_diff < -0.5f ) {
Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max );
}
@@ -4342,7 +4345,7 @@ opengl_renderer::Update( double const Deltatime ) {
}
// legacy framerate parameters
else if( Global.fFpsAverage != 0.f ) {
- auto const fps_diff = m_framerate - Global.fFpsAverage;
+ auto const fps_diff = drawframerate - Global.fFpsAverage;
if( fps_diff < -Global.fFpsDeviation ) {
Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max );
}
diff --git a/tests/unit/test_framepacer.cpp b/tests/unit/test_framepacer.cpp
new file mode 100644
index 000000000..bb9acb025
--- /dev/null
+++ b/tests/unit/test_framepacer.cpp
@@ -0,0 +1,110 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "utilities/framepacer.h"
+
+// the main loop's frame limiter (fpslimit in eu07.ini, eu07/maszyna#416), driven with made-up clock readings
+namespace
+{
+using namespace std::chrono_literals;
+using clock_type = frame_pacer::clock;
+
+clock_type::time_point const kStart{clock_type::time_point{} + 100s};
+constexpr clock_type::duration kFrame{std::chrono::duration_cast(std::chrono::duration(1.f / 30.f))};
+
+// runs frames that take Work each, with every wait overshooting by Oversleep; returns when the last of Frames ends
+clock_type::time_point run_frames(frame_pacer &Pacer, int const Frames, clock_type::duration const Work, clock_type::duration const Oversleep)
+{
+ auto now{kStart};
+ for (auto frame = 0; frame < Frames; ++frame)
+ {
+ now += Work;
+ if (auto const next{Pacer.next_frame(now, kFrame)})
+ {
+ CHECK(*next > now);
+ now = *next + Oversleep;
+ }
+ }
+ return now;
+}
+} // namespace
+
+TEST_CASE("frame pacer: without a limit nothing waits")
+{
+ frame_pacer pacer;
+ CHECK_FALSE(pacer.next_frame(kStart, clock_type::duration::zero()).has_value());
+ CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value());
+}
+
+TEST_CASE("frame pacer: a quick frame waits out the rest of the frame time")
+{
+ frame_pacer pacer;
+ // the first frame only sets the cadence
+ CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
+ auto const next{pacer.next_frame(kStart + 5ms, kFrame)};
+ REQUIRE(next.has_value());
+ CHECK(*next == kStart + kFrame);
+}
+
+TEST_CASE("frame pacer: a slow frame doesn't wait")
+{
+ frame_pacer pacer;
+ CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
+ CHECK_FALSE(pacer.next_frame(kStart + kFrame + 5ms, kFrame).has_value());
+}
+
+TEST_CASE("frame pacer: the frame rate holds the limit with fast frames")
+{
+ frame_pacer pacer;
+ auto const end{run_frames(pacer, 301, 2ms, clock_type::duration::zero())};
+ // 300 paced frames after the first
+ CHECK(end == kStart + 2ms + 300 * kFrame);
+}
+
+TEST_CASE("frame pacer: a wait that overshoots is made up in the next frame")
+{
+ // the windows timer wakes a sleeping thread up to ~15.6 ms late; sleeping off what is left of each frame
+ // then drops 30 fps to about 22. on a fixed cadence the frame rate still averages to the limit
+ frame_pacer pacer;
+ auto const end{run_frames(pacer, 301, 2ms, 12ms)};
+ auto const elapsed{std::chrono::duration(end - kStart).count()};
+ CHECK(300.0 / elapsed == doctest::Approx(30.0).epsilon(0.01));
+}
+
+TEST_CASE("frame pacer: after a long frame the cadence starts anew instead of catching up")
+{
+ frame_pacer pacer;
+ CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
+ // a hitch of half a second
+ auto const late{kStart + 500ms};
+ CHECK_FALSE(pacer.next_frame(late, kFrame).has_value());
+ // the next quick frame waits a whole frame time from there rather than running at once
+ auto const next{pacer.next_frame(late + 1ms, kFrame)};
+ REQUIRE(next.has_value());
+ CHECK(*next == late + kFrame);
+}
+
+TEST_CASE("frame pacer: turning the limit off and on again starts a new cadence")
+{
+ frame_pacer pacer;
+ CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
+ CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value());
+ CHECK_FALSE(pacer.next_frame(kStart + 2s, kFrame).has_value());
+ auto const next{pacer.next_frame(kStart + 2s + 1ms, kFrame)};
+ REQUIRE(next.has_value());
+ CHECK(*next == kStart + 2s + kFrame);
+}
+
+TEST_CASE("frame pacer: the wait stays exact after days of system uptime")
+{
+ // fpslimit 60 gives the frame time as float seconds; the old limiter handed the float rest of the frame
+ // to sleep_for, which adds it to steady_clock::now() in float nanoseconds. after 95 hours of uptime that
+ // rounds the wake-up time to steps of ~33 ms, and a 14 ms wait came out as no wait at all
+ frame_pacer pacer;
+ std::chrono::duration const frametime{1.f / 60.f};
+ auto const uptime{clock_type::time_point{} + 95h};
+ CHECK_FALSE(pacer.next_frame(uptime, frametime).has_value());
+ auto const next{pacer.next_frame(uptime + 2ms, frametime)};
+ REQUIRE(next.has_value());
+ auto const wait{std::chrono::duration(*next - (uptime + 2ms)).count()};
+ CHECK(wait == doctest::Approx(1000.0 / 60.0 - 2.0).epsilon(0.001));
+}
diff --git a/utilities/Timer.h b/utilities/Timer.h
index 32e170a46..c63ef14a7 100644
--- a/utilities/Timer.h
+++ b/utilities/Timer.h
@@ -64,6 +64,7 @@ struct subsystem_stopwatches {
stopwatch sim_events;
stopwatch sim_ai;
stopwatch mainloop_total;
+ stopwatch mainloop_period; // start to start, the wait for fpslimit included
};
extern subsystem_stopwatches subsystem;
diff --git a/utilities/framepacer.h b/utilities/framepacer.h
new file mode 100644
index 000000000..a0de0144d
--- /dev/null
+++ b/utilities/framepacer.h
@@ -0,0 +1,59 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#pragma once
+
+#include
+#include
+
+// paces the main loop to the frame time set by fpslimit in eu07.ini.
+// the frames are scheduled on a fixed cadence rather than by sleeping off what is left of each frame,
+// so a sleep that overshoots (the windows timer wakes up in steps of up to ~15.6 ms) is made up by
+// a shorter wait in the next frame, and the frame rate averages to the limit.
+// all the time arithmetic is done in the clock's integer ticks: a sleep_for() given a float duration
+// adds it to now() as float nanoseconds, which after a few hours of system uptime rounds the wake-up
+// time to tens of milliseconds and lets the limit fall through (eu07/maszyna#416)
+class frame_pacer {
+
+public:
+ using clock = std::chrono::steady_clock;
+
+ // called at the end of each frame. returns the point in time the next frame may start at,
+ // or nothing when it may start right away
+ [[nodiscard]] std::optional next_frame(clock::time_point const Now, std::chrono::duration const Frametime) {
+ return next_frame(Now, std::chrono::duration_cast(Frametime));
+ }
+ [[nodiscard]] std::optional next_frame(clock::time_point const Now, clock::duration const Minframetime) {
+ if (Minframetime <= clock::duration::zero()) {
+ // no limit
+ m_framestart.reset();
+ return std::nullopt;
+ }
+ if (!m_framestart) {
+ // first paced frame
+ m_framestart = Now;
+ return std::nullopt;
+ }
+ auto const nextframe{*m_framestart + Minframetime};
+ if (Now >= nextframe + Minframetime) {
+ // a whole frame or more behind: start the cadence anew rather than run frames back to back to catch up
+ m_framestart = Now;
+ return std::nullopt;
+ }
+ m_framestart = nextframe;
+ if (Now >= nextframe) {
+ return std::nullopt;
+ }
+ return nextframe;
+ }
+
+private:
+ // the scheduled start of the current frame
+ std::optional m_framestart;
+};
From 00955513500bc30f089cd01a97a798f58ae08310 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 19:30:10 +0100
Subject: [PATCH 040/104] feat: universal controller power demand in steps
(UCList CtrlValStep)
The 6Dg sets its power demand in 5% steps, while the universal controller
(EIMCtrlType 3) ramped it continuously. A new optional UCList header key,
CtrlValStep (e.g. 0.05), makes the setting move in whole steps: one at once
when the controller is moved onto a raising or lowering position, then one
each time SpeedUp / SpeedDown covers a step, stopping at the position's set
value. Without the key (default 0) nothing changes.
Data (SVN, optional, after this): add CtrlValStep=0.05 to the UCList: line
of dynamic/pkp/6dg_v1/6dg.fiz (its variants include it).
(eu07/maszyna#412)
---
McZapkie/MOVER.h | 5 ++
McZapkie/Mover.cpp | 69 +++++++++++++++++++--
tests/unit/test_uc_steps.cpp | 115 +++++++++++++++++++++++++++++++++++
3 files changed, 184 insertions(+), 5 deletions(-)
create mode 100644 tests/unit/test_uc_steps.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..51bdedcee 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -1727,6 +1727,10 @@ class TMoverParameters
bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/
bool UniCtrlIntegratedLocalBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/
int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force
+ // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the
+ // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown
+ // covers a step; 0 (the default) changes it continuously
+ double UniCtrlValStep{0.0};
std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab
/*-sekcja parametrow dla lokomotywy elektrycznej*/
@@ -2199,6 +2203,7 @@ class TMoverParameters
double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/
double eimic_analog = 0; /*pozycja zadajnika analogowa*/
double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/
+ double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far
double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/
int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/
bool SpeedCtrlTypeTime = false; /*czy tempomat sterowany czasowo*/
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..b7536c4fc 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -7290,6 +7290,60 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify
return State != initialstate;
}
+namespace
+{
+// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it
+double next_uc_step(double const Value, double const Limit, double const Step)
+{
+ constexpr double epsilon{1e-6};
+ if (Limit > Value)
+ {
+ return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit);
+ }
+ return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit);
+}
+
+// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps.
+// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each
+// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go)
+double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress)
+{
+ if (Moved)
+ {
+ Progress = 0.0;
+ }
+ double const delta{Ramped - Current};
+ if (std::abs(delta) < 1e-9)
+ {
+ Progress = 0.0;
+ return Ramped;
+ }
+ double limit{0.0};
+ if (delta > 0.0)
+ {
+ limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal;
+ }
+ else
+ {
+ limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal;
+ }
+ Progress = Moved ? Step : Progress + std::abs(delta);
+ double value{Current};
+ bool reached{std::abs(value - limit) < 1e-9};
+ while (!reached && Progress >= Step - 1e-9)
+ {
+ value = next_uc_step(value, limit, Step);
+ Progress -= Step;
+ reached = std::abs(value - limit) < 1e-9;
+ }
+ if (reached)
+ {
+ Progress = 0.0;
+ }
+ return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal);
+}
+} // namespace
+
void TMoverParameters::CheckEIMIC(double dt)
{
double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0;
@@ -7414,11 +7468,14 @@ void TMoverParameters::CheckEIMIC(double dt)
if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay)
{
- eimic -= safe_clamp(-UniCtrlList[MainCtrlPos].SetCtrlVal + eimic, 0.0,
- MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedDown : sign(UniCtrlList[MainCtrlPos].SpeedDown) * 0.01); // odejmuj do X
- eimic += safe_clamp(UniCtrlList[MainCtrlPos].SetCtrlVal - eimic, 0.0,
- MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedUp : sign(UniCtrlList[MainCtrlPos].SpeedUp) * 0.01); // dodawaj do X
- eimic = safe_clamp(eimic, UniCtrlList[MainCtrlPos].MinCtrlVal, UniCtrlList[MainCtrlPos].MaxCtrlVal);
+ auto const &position{UniCtrlList[MainCtrlPos]};
+ double ramped{eimic};
+ ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0,
+ MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X
+ ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0,
+ MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X
+ ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal);
+ eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped;
}
if (MainCtrlActualPos == MainCtrlPos)
LastRelayTime += dt;
@@ -11515,6 +11572,8 @@ void TMoverParameters::LoadFIZ_UCList(std::string const &Input)
extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, "");
extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, "");
extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, "");
+ extract_value(UniCtrlValStep, "CtrlValStep", Input, "");
+ UniCtrlValStep = std::max(UniCtrlValStep, 0.0);
}
void TMoverParameters::LoadFIZ_DList(std::string const &Input)
diff --git a/tests/unit/test_uc_steps.cpp b/tests/unit/test_uc_steps.cpp
new file mode 100644
index 000000000..eb1b26fa4
--- /dev/null
+++ b/tests/unit/test_uc_steps.cpp
@@ -0,0 +1,115 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+#include "drive.h"
+
+#include
+
+// the universal controller (EIMCtrlType 3) setting its power demand in steps (UCList CtrlValStep), as the 6Dg does
+// in steps of 5% (eu07/maszyna#412). the 214M railbus's controller: 3 lowers the power to 0, 4 holds it, 5 raises it
+// to 1, at 0.15 a second after IniCDelay (1 s)
+
+using test::definition;
+using test::vehicle;
+
+namespace {
+
+constexpr int lower{3};
+constexpr int hold{4};
+constexpr int raise{5};
+
+// the railbus started up, its brakes released and its direction set, its controller holding no power
+void get_ready(vehicle &Railbus, test::track const &Track) {
+ auto driven{test::driving(Railbus)};
+ REQUIRE(test::start_up(driven, Track));
+ test::release_brakes(driven.cab);
+ for (int i = 0; i < 3 && Railbus->DirActive <= 0; ++i) {
+ Railbus->DirectionForward();
+ }
+ while (Railbus->MainCtrlPos < hold && Railbus->IncMainCtrl(1)) {
+ ;
+ }
+ while (Railbus->MainCtrlPos > hold && Railbus->DecMainCtrl(1)) {
+ ;
+ }
+ REQUIRE(Railbus->MainCtrlPos == hold);
+ Railbus.run(2.0, Track);
+ REQUIRE(Railbus->eimic == doctest::Approx(0.0));
+}
+
+void move_to(vehicle &Railbus, int const Position) {
+ while (Railbus->MainCtrlPos < Position && Railbus->IncMainCtrl(1)) {
+ ;
+ }
+ while (Railbus->MainCtrlPos > Position && Railbus->DecMainCtrl(1)) {
+ ;
+ }
+ REQUIRE(Railbus->MainCtrlPos == Position);
+}
+
+bool on_step(double const Value, double const Step) {
+ return std::abs(Value / Step - std::round(Value / Step)) < 1e-6;
+}
+
+} // namespace
+
+TEST_CASE("controls: the universal controller with CtrlValStep sets its power in whole steps") {
+ test::track const line{0.15, 0.0};
+ vehicle railbus{definition::fiz("21xm_v1/214ma").set("UCList", "CtrlValStep", 0.05), 0.0, "test", 1};
+ REQUIRE(railbus->UniCtrlValStep == doctest::Approx(0.05));
+ get_ready(railbus, line);
+
+ // a tap on the raising position: one step at once, kept by the holding one
+ move_to(railbus, raise);
+ railbus.step(line);
+ CHECK(railbus->eimic == doctest::Approx(0.05));
+ move_to(railbus, hold);
+ railbus.run(2.0, line);
+ CHECK(railbus->eimic == doctest::Approx(0.05));
+
+ // held there: after the initial delay a step each third of a second (0.15 a second), never in between
+ move_to(railbus, raise);
+ for (int i = 0; i < 310; ++i) { // 3.1 s
+ railbus.step(line);
+ CAPTURE(i);
+ CHECK(on_step(railbus->eimic, 0.05));
+ }
+ // the first step at once, 1 s of the initial delay, then 2.1 s of 0.15 a second (6 steps)
+ CHECK(railbus->eimic == doctest::Approx(0.40));
+ move_to(railbus, hold);
+ railbus.run(2.0, line);
+ CHECK(railbus->eimic == doctest::Approx(0.40));
+
+ // up to the full power, and not past it
+ move_to(railbus, raise);
+ railbus.run(10.0, line);
+ CHECK(railbus->eimic == doctest::Approx(1.0));
+
+ // down the same way: a tap is one step, holding it goes on in steps down to nothing
+ move_to(railbus, lower);
+ railbus.step(line);
+ CHECK(railbus->eimic == doctest::Approx(0.95));
+ move_to(railbus, hold);
+ railbus.run(1.0, line);
+ CHECK(railbus->eimic == doctest::Approx(0.95));
+ move_to(railbus, lower);
+ for (int i = 0; i < 800; ++i) { // 8 s
+ railbus.step(line);
+ CAPTURE(i);
+ CHECK(on_step(railbus->eimic, 0.05));
+ }
+ CHECK(railbus->eimic == doctest::Approx(0.0));
+}
+
+TEST_CASE("controls: the universal controller without CtrlValStep sets its power continuously, as before") {
+ test::track const line{0.15, 0.0};
+ vehicle railbus{definition::fiz("21xm_v1/214ma"), 0.0, "test", 1};
+ REQUIRE(railbus->UniCtrlValStep == 0.0);
+ get_ready(railbus, line);
+ // a tap moves it by 0.01, held it goes on at 0.15 a second after the initial delay
+ move_to(railbus, raise);
+ railbus.step(line);
+ CHECK(railbus->eimic == doctest::Approx(0.01));
+ railbus.run(2.0 - 0.01, line);
+ CHECK(railbus->eimic == doctest::Approx(0.01 + 0.15).epsilon(0.05));
+}
From a86bcb1ef51b9ddd4c6ae030d15c7895185b2361 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 20:08:59 +0100
Subject: [PATCH 041/104] fix: SM42 shunt mode switched on at the first move of
the switch (eu07/maszyna#497)
CurrentSwitch() asked MaxCurrentSwitch() first. Since 2e86b3a5 (2021) that one
takes any change of the motor overload relay threshold, on every engine type, and
reports it, so the first move of the switch only flipped the threshold (meaningless
on a diesel) and the shunt mode of the SM42/SP42 (and the 2Ls150 gear of the SM03)
took a second one, both on and off; the cab switch, which shows the shunt mode,
didn't move at the first click. The diesels with a shunt mode now set it alone.
---
McZapkie/Mover.cpp | 27 +++++++++++++--------------
tests/unit/test_diesel.cpp | 29 +++++++++++++++++++++++++++++
2 files changed, 42 insertions(+), 14 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..34caced15 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -809,6 +809,19 @@ bool TMoverParameters::ChangeCab(int direction)
// rozruch wysoki (true) albo niski (false)
bool TMoverParameters::CurrentSwitch(bool const State)
{
+ // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that
+ // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone.
+ // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497)
+ if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric))
+ {
+ // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position
+ if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos())
+ {
+ return false;
+ }
+ ShuntMode = State;
+ return true;
+ }
if (MaxCurrentSwitch(State))
{
@@ -818,20 +831,6 @@ bool TMoverParameters::CurrentSwitch(bool const State)
}
return true;
}
- // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that
- // dla 2Ls150
- if (EngineType == TEngineType::DieselEngine && true == ShuntModeAllow && DirActive == 0)
- {
- // przed ustawieniem kierunku
- ShuntMode = State;
- return true;
- }
- // for SM42/SP42
- if (EngineType == TEngineType::DieselElectric && true == ShuntModeAllow && IsMainCtrlNoPowerPos())
- {
- ShuntMode = State;
- return true;
- }
return false;
};
diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp
index 07686dc10..c4ea147d3 100644
--- a/tests/unit/test_diesel.cpp
+++ b/tests/unit/test_diesel.cpp
@@ -177,3 +177,32 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button
CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive);
scenario.check();
}
+
+TEST_CASE("diesel: the SM42's shunt mode, switched on and off with one move of the switch") {
+ // eu07/maszyna#497: the shunt mode of the diesel-electrics (ShuntMode=1) shares its switch with the motor
+ // overload relay threshold of the electric locomotives (CurrentSwitch()). the SM42 has no such relay, so
+ // the switch sets the shunt mode at the first move, at the controller's zero position only
+ scenario scenario{"diesel/sm42 shunt mode", motion() + traction(), test::track{}};
+ scenario.add("sm42_v1/6d1", 1);
+ REQUIRE(scenario.start_up());
+ auto &sm42{scenario.cab()};
+ REQUIRE(sm42.ShuntModeAllow);
+ CHECK_FALSE(sm42.ShuntMode);
+ scenario.act("shunt mode on");
+ CHECK(sm42.CurrentSwitch(true));
+ CHECK(sm42.ShuntMode);
+ scenario.get_going();
+ scenario.act("shunting power");
+ sm42.AnPos = 0.5;
+ CHECK(sm42.IncMainCtrl(1));
+ scenario.wait(60.0);
+ CHECK(sm42.Vel > 1.0);
+ // not with the controller out of its zero position
+ CHECK_FALSE(sm42.CurrentSwitch(false));
+ CHECK(sm42.ShuntMode);
+ scenario.notch_back(0);
+ scenario.act("shunt mode off");
+ CHECK(sm42.CurrentSwitch(false));
+ CHECK_FALSE(sm42.ShuntMode);
+ scenario.check();
+}
From 329dc4e42efda784739d82386737398189267f36 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 20:13:46 +0100
Subject: [PATCH 042/104] feat: SM42 vigilance device switched off in the shunt
mode (eu07/maszyna#457)
The shunt mode of the diesel-electrics (ShuntMode=1: SM42, SP42, SU42) now
suspends their vigilance device (CA): no alerter while running, no alarm for the
button held too long, and an alarm already on goes out. The cab signalling (SHP)
stays as it was. Back in the line mode the CA works as before.
---
McZapkie/MOVER.h | 2 ++
McZapkie/Mover.cpp | 26 ++++++++++++++++++++++----
tests/unit/test_cab.cpp | 35 +++++++++++++++++++++++++++++++++++
3 files changed, 59 insertions(+), 4 deletions(-)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..0149bfb7d 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -1131,6 +1131,7 @@ class TSecuritySystem
bool is_sifa = false; // Sifa-like pedal device, with inverted input for convenient keyboard usage
bool separate_acknowledge = false; // cabsignal reset button is separate from vigilance
bool cabsignal_lock = false;
+ bool vigilance_suspended = false; // the vigilance device switched off by the vehicle, as by the SM42's shunt mode
double vigilance_timer = 0.0;
double alert_timer = 0.0;
@@ -1155,6 +1156,7 @@ class TSecuritySystem
void update(double dt, double Vel, bool pwr, int cab);
void set_cabsignal();
void set_cabsignal_lock(bool);
+ void set_vigilance_suspended(bool Suspended);
bool is_blinking() const;
bool is_vigilance_blinking() const;
bool is_cabsignal_blinking() const;
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 34caced15..eaed979f0 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -152,11 +152,22 @@ void TSecuritySystem::update(double dt, double vel, bool pwr, int cab)
velocity = vel;
cabactive = cab;
- if (vigilance_enabled && velocity > AwareMinSpeed)
- vigilance_timer += dt;
+ if (vigilance_suspended)
+ {
+ // the vigilance device is switched off: neither the alerter nor the button held too long, its alarm gone with it
+ vigilance_timer = 0.0;
+ press_timer = 0.0;
+ if (!cabsignal_active)
+ alert_timer = 0.0;
+ }
+ else
+ {
+ if (vigilance_enabled && velocity > AwareMinSpeed)
+ vigilance_timer += dt;
- if (pressed && (!is_sifa || velocity > AwareMinSpeed))
- press_timer += dt;
+ if (pressed && (!is_sifa || velocity > AwareMinSpeed))
+ press_timer += dt;
+ }
if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active)
alert_timer += dt;
@@ -231,6 +242,11 @@ void TSecuritySystem::set_cabsignal_lock(bool v)
cabsignal_lock = v;
}
+void TSecuritySystem::set_vigilance_suspended(bool const Suspended)
+{
+ vigilance_suspended = Suspended;
+}
+
bool TSecuritySystem::is_engine_blocked() const
{
if (!is_sifa)
@@ -3142,6 +3158,8 @@ void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP
void TMoverParameters::SecuritySystemCheck(double dt)
{
bool isPower = Power24vIsAvailable || Power110vIsAvailable;
+ // the shunt mode of the SM42/SP42 switches their vigilance device (CA) off (eu07/maszyna#457)
+ SecuritySystem.set_vigilance_suspended(EngineType == TEngineType::DieselElectric && ShuntMode);
SecuritySystem.update(dt, Vel, isPower, CabActive);
if (!Battery || !Radio)
diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp
index 4c5ba9f53..69f6278e9 100644
--- a/tests/unit/test_cab.cpp
+++ b/tests/unit/test_cab.cpp
@@ -227,3 +227,38 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended"
CHECK(security.radiostop_available());
scenario.check();
}
+
+TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode") {
+ // eu07/maszyna#457: the shunt mode of the SM42 switches its vigilance device (CA) off, it alerts again
+ // once the shunt mode is off
+ scenario scenario{"cab/sm42 vigilance in shunt mode", motion() + brakes(), test::track{}};
+ scenario.add("sm42_v1/6d1", 1);
+ REQUIRE(scenario.start_up());
+ auto &sm42{scenario.cab()};
+ auto const &security{sm42.SecuritySystem};
+ REQUIRE(sm42.CurrentSwitch(true));
+ REQUIRE(sm42.ShuntMode);
+ scenario.get_going();
+ sm42.AnPos = 0.3;
+ sm42.IncMainCtrl(1);
+ scenario.act("unattended in shunt mode");
+ bool blinked{false};
+ for (int i = 0; i < 120; ++i) {
+ scenario.train().run(1.0, scenario.line());
+ blinked |= security.is_blinking();
+ }
+ CHECK(sm42.Vel > 1.0);
+ CHECK_FALSE(blinked);
+ CHECK(sm42.PipePress > 3.5);
+ scenario.act("shunt mode off");
+ scenario.notch_back(0);
+ REQUIRE(sm42.CurrentSwitch(false));
+ sm42.IncMainCtrl(1);
+ scenario.act("unattended");
+ for (int i = 0; i < 120; ++i) {
+ scenario.train().run(1.0, scenario.line());
+ blinked |= security.is_vigilance_blinking();
+ }
+ CHECK(blinked);
+ scenario.check();
+}
From 5bc4e7cd2e15e19d6f85ec0ace1f666941983f98 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 21:01:54 +0100
Subject: [PATCH 043/104] feat: lock field shunting at zero and on resistive
positions
New optional Cntrl. key ScndCtrlResistiveLock=Yes: IncScndCtrl() refuses
to step the shunt controller up while the master controller is at its
no-power position or on a resistive RList position (R >= 0.01), as the
interlock of the ET21, ET22 and EP09 does. Decreasing the shunt stays
allowed so it can't get stuck. The AI doesn't choose field shunting
while the lock applies. Without the key nothing changes.
Game data: the key is to be added to the Cntrl. line of the ET21
(et21_v2), ET22 (et22_v3, et22-2000_v2) and EP09 (ep09_v1, ep09_v2)
.fiz files that define it; until then they behave as before.
(eu07/maszyna#402)
---
McZapkie/MOVER.h | 3 ++
McZapkie/Mover.cpp | 9 ++++-
tests/unit/test_cntrl.cpp | 80 +++++++++++++++++++++++++++++++++++++++
vehicle/Driver.cpp | 2 +-
4 files changed, 92 insertions(+), 2 deletions(-)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..825bec6de 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -1943,6 +1943,7 @@ class TMoverParameters
double MirrorVelClose{5.0};
bool MirrorForbidden{false}; /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/
bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/
+ bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved up while the master controller is at zero or on a resistive position (ScndCtrlResistiveLock=Yes in Cntrl.)
bool SpeedCtrl = false; /*czy jest tempomat*/
speed_control SpeedCtrlUnit; /*parametry tempomatu*/
double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/
@@ -2372,6 +2373,8 @@ class TMoverParameters
bool IncScndCtrl(int CtrlSpeed);
bool DecScndCtrl(int CtrlSpeed);
int GetVirtualScndPos() const;
+ // whether ScndCtrlResistiveLock keeps the shunt controller from being moved up at the current master controller position
+ bool IsScndCtrlLockedByMainCtrl() const;
bool IsScndCtrlNoPowerPos() const;
bool IsScndCtrlMaxPowerPos() const;
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..b9d18d0b2 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -2751,7 +2751,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed)
{
// if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos= 0.01);
+}
+
int TMoverParameters::GetVirtualScndPos() const
{
if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos)
@@ -10897,6 +10903,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, "");
extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR
+ extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych
extract_value(InitialCtrlDelay, "IniCDelay", line, "");
extract_value(CtrlDelay, "SCDelay", line, "");
diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp
index 0dd3ddc20..43c983edd 100644
--- a/tests/unit/test_cntrl.cpp
+++ b/tests/unit/test_cntrl.cpp
@@ -37,3 +37,83 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh
CHECK(unit->ConverterOverloadRelayStart == start_t::automatic);
}
}
+
+namespace {
+
+// the first position of the master controller after Position without the starting resistors in the circuit
+int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) {
+ for (auto position{Position + 1}; position <= Vehicle.MainCtrlPosNo; ++position) {
+ if (Vehicle.RList[position].R < 0.01) {
+ return position;
+ }
+ }
+ return 0;
+}
+
+// the vehicle with its cab occupied, the master controller set to Position and the shunt controller off
+void controllers_at(vehicle &Vehicle, int Position) {
+ Vehicle->CabActive = 1;
+ Vehicle->MainCtrlPos = Position;
+ Vehicle->ScndCtrlPos = 0;
+}
+
+} // namespace
+
+TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and on the resistive positions (eu07/maszyna#402)") {
+ for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) {
+ CAPTURE(path);
+ vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1};
+ REQUIRE(locked->ScndCtrlResistiveLock);
+ REQUIRE(locked->ScndCtrlPosNo > 0);
+ auto const resistancefree{resistance_free_position(locked.mover())};
+ REQUIRE(resistancefree > 1);
+ REQUIRE(locked->RList[resistancefree - 1].R >= 0.01);
+
+ SUBCASE("zero") {
+ controllers_at(locked, 0);
+ CHECK(locked->IsScndCtrlLockedByMainCtrl());
+ CHECK_FALSE(locked->IncScndCtrl(1));
+ CHECK_FALSE(locked->IncScndCtrl(2));
+ CHECK(locked->ScndCtrlPos == 0);
+ }
+ SUBCASE("resistive positions") {
+ for (auto position{1}; position < resistancefree; ++position) {
+ CAPTURE(position);
+ controllers_at(locked, position);
+ CHECK_FALSE(locked->IncScndCtrl(1));
+ CHECK(locked->ScndCtrlPos == 0);
+ }
+ }
+ SUBCASE("every resistance-free position") {
+ for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.mover(), position)) {
+ CAPTURE(position);
+ controllers_at(locked, position);
+ CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl());
+ CHECK(locked->IncScndCtrl(1));
+ CHECK(locked->ScndCtrlPos == 1);
+ }
+ }
+ SUBCASE("the shunting still goes off on a resistive position") {
+ controllers_at(locked, resistancefree);
+ REQUIRE(locked->IncScndCtrl(1));
+ locked->MainCtrlPos = resistancefree - 1;
+ CHECK(locked->DecScndCtrl(1));
+ CHECK(locked->ScndCtrlPos == 0);
+ }
+ }
+}
+
+TEST_CASE("cntrl: without ScndCtrlResistiveLock the field shunting engages on any position, as before") {
+ for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) {
+ CAPTURE(path);
+ vehicle unlocked{definition::fiz(path), 0.0, "test", 1};
+ CHECK_FALSE(unlocked->ScndCtrlResistiveLock);
+ for (auto const position : {0, 1}) {
+ CAPTURE(position);
+ controllers_at(unlocked, position);
+ CHECK_FALSE(unlocked->IsScndCtrlLockedByMainCtrl());
+ CHECK(unlocked->IncScndCtrl(1));
+ CHECK(unlocked->ScndCtrlPos == 1);
+ }
+ }
+}
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..bb6ff823b 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3364,7 +3364,7 @@ bool TController::IncSpeed()
mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0));
// when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train
// (if there's only one parallel mode configuration it'll be used regardless of current speed)
- auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 &&
+ auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() &&
(useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 :
true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ?
mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 :
From 6dc1239553f41070f7439786ad3d29d86005caf8 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 21:16:19 +0100
Subject: [PATCH 044/104] fix: no multiple-unit control between electric and
diesel locomotives
An electric and a diesel locomotive got their control coupled whenever the
scenario (and so the Starter) asked for it, since the scenery coupling ignores
ControlType, or when neither coupler named a control system, so a Vectron and
an SM42 ran in multiple unit.
TMoverParameters::Attach() now leaves the control connection out between an
electric (ElectricSeriesMotor, ElectricInductionMotor) and a diesel
(DieselEngine, DieselElectric/DumbDE) traction vehicle, for the scenery, the
AI, the coupling keys and the automatic couplers alike, and logs it. Vehicles
without own traction (cars, control trailers) are not affected, nor are
permanent couplings within a unit, nor couplers that both name the same
ControlType, which stays the vehicle authors' way to allow such a pair. The
AI coupling order expects the coupling the vehicles can take, so it doesn't
wait for the control connection forever.
Existing scenarios coupling such a pair still load, without the control
connection. "controlcoupling.enginecheck no" in eu07.ini turns the check off.
No SVN data change is needed. (eu07/maszyna#520)
---
McZapkie/MOVER.h | 8 +++
McZapkie/Mover.cpp | 69 +++++++++++++++++-
tests/unit/test_couplers.cpp | 135 +++++++++++++++++++++++++++++++++++
utilities/Globals.cpp | 7 ++
utilities/Globals.h | 1 +
vehicle/Driver.cpp | 12 +++-
vehicle/DynObj.cpp | 3 +-
7 files changed, 230 insertions(+), 5 deletions(-)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..55a175145 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2453,6 +2453,14 @@ class TMoverParameters
// whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on
// contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them)
bool AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const;
+ // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other
+ // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system
+ // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check
+ // off allows it always (eu07/maszyna#520)
+ bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const;
+ // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling
+ // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole
+ int CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const;
// the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound
int SoundingHorns(int const Signal) const;
// whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light:
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..4b10f4f9c 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -599,7 +599,8 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *
}
auto &thiscoupler{Couplers[ConnectNo]};
- auto &othercoupler = ConnectTo->Couplers[ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr];
+ auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr};
+ auto &othercoupler = ConnectTo->Couplers[otherend];
auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)};
@@ -608,6 +609,18 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *
return false;
}
+ // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI
+ // or the player (eu07/maszyna#520)
+ if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType)
+ {
+ WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name));
+ CouplingType = compatible;
+ if (CouplingType == coupling::faux)
+ {
+ return false;
+ }
+ }
+
// stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie
if (thiscoupler.CouplingFlag == coupling::faux)
{
@@ -1206,6 +1219,59 @@ bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters con
return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity;
}
+namespace
+{
+
+// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes
+enum class traction_kind
+{
+ none,
+ electric,
+ diesel
+};
+
+traction_kind traction_of(TEngineType const Engine)
+{
+ switch (Engine)
+ {
+ case TEngineType::ElectricSeriesMotor:
+ case TEngineType::ElectricInductionMotor:
+ return traction_kind::electric;
+ case TEngineType::DieselEngine:
+ case TEngineType::DieselElectric:
+ return traction_kind::diesel;
+ default:
+ return traction_kind::none;
+ }
+}
+
+} // namespace
+
+bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const
+{
+ if (false == Global.control_coupling_engine_check)
+ {
+ return true;
+ }
+ // the same control system named on both couplers is the vehicle authors' word that they work together
+ if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type)
+ {
+ return true;
+ }
+ auto const traction{traction_of(EngineType)};
+ auto const othertraction{traction_of(Other.EngineType)};
+ return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction;
+}
+
+int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const
+{
+ if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd))
+ {
+ return CouplingType;
+ }
+ return CouplingType & ~coupling::control;
+}
+
int TMoverParameters::SoundingHorns(int const Signal) const
{
auto const supplied{[this](horn_supply const Supply) {
@@ -5454,6 +5520,7 @@ double TMoverParameters::CouplerForce(int const End, double dt)
{
couplingtype &= ~coupling::control;
}
+ couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype);
// too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)};
diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp
index 2a0ff6e50..bed4d7a73 100644
--- a/tests/unit/test_couplers.cpp
+++ b/tests/unit/test_couplers.cpp
@@ -525,3 +525,138 @@ TEST_CASE("couplers: a collision of coupled vehicles keeps the momentum of the p
CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) > 13.5);
CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) < 15.05 + 1e-6);
}
+
+// eu07/maszyna#520: an electric and a diesel locomotive got their control coupled (multiple-unit control) when the
+// scenario or the Starter asked for it, or when the couplers let it through, as a Vectron and an SM42 did
+
+namespace {
+
+// the given setting of the control coupling check for the test, restored after it
+class control_coupling_check_setting {
+public:
+ explicit control_coupling_check_setting(bool Enabled) { Global.control_coupling_engine_check = Enabled; }
+ ~control_coupling_check_setting() { Global.control_coupling_engine_check = m_previous; }
+ control_coupling_check_setting(control_coupling_check_setting const &) = delete;
+ control_coupling_check_setting &operator=(control_coupling_check_setting const &) = delete;
+
+private:
+ bool m_previous{Global.control_coupling_engine_check};
+};
+
+constexpr int scenario_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control};
+
+// couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the
+// first one only), returns the coupling the pair got
+int scenario_couple(vehicle &First, vehicle &Second, int Coupling = scenario_coupling) {
+ REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), Coupling, true, false));
+ CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag);
+ return First->Couplers[end::rear].CouplingFlag;
+}
+
+} // namespace
+
+TEST_CASE("couplers: an electric and a diesel locomotive don't share their control") {
+ control_coupling_check_setting const check{true};
+ // the E6ACT names no control system (ControlType), as the Vectron doesn't; the SM42 names its own, the SM03 none
+ auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}};
+ REQUIRE(electric->EngineType == TEngineType::ElectricInductionMotor);
+
+ SUBCASE("a diesel-electric one with its own control system") {
+ auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
+ REQUIRE(diesel->EngineType == TEngineType::DieselElectric);
+ CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front));
+ CHECK(scenario_couple(electric, diesel) == (scenario_coupling & ~coupling::control));
+ }
+ SUBCASE("a diesel-mechanical one without a control system named, either") {
+ auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}};
+ REQUIRE(diesel->EngineType == TEngineType::DieselEngine);
+ CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear));
+ CHECK(scenario_couple(diesel, electric) == (scenario_coupling & ~coupling::control));
+ }
+ SUBCASE("unless both name the same control system") {
+ auto diesel{vehicle{definition::fiz("sm03_v1/sm03").set("BuffCoupl", "ControlType", "shared"), 0.0, "diesel"}};
+ auto shared{vehicle{definition::fiz("e6act_v2/e6acta").set("BuffCoupl", "ControlType", "shared"), 0.0, "electric"}};
+ CHECK(scenario_couple(shared, diesel) == scenario_coupling);
+ }
+ SUBCASE("unless the vehicles make one unit, coupled for good") {
+ auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}};
+ auto const permanent{scenario_coupling | coupling::permanent};
+ CHECK(scenario_couple(electric, diesel, permanent) == permanent);
+ }
+ SUBCASE("unless the check is turned off") {
+ control_coupling_check_setting const off{false};
+ auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
+ CHECK(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front));
+ CHECK(scenario_couple(electric, diesel) == scenario_coupling);
+ }
+}
+
+TEST_CASE("couplers: locomotives of the same traction and the cars keep their control coupling") {
+ control_coupling_check_setting const check{true};
+
+ SUBCASE("two electric ones") {
+ auto first{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "first"}};
+ auto second{vehicle{definition::fiz("et22_v3/201e-w"), 0.0, "second"}};
+ CHECK(scenario_couple(first, second) == scenario_coupling);
+ }
+ SUBCASE("an electric one of each motor type") {
+ auto first{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "first"}};
+ auto second{vehicle{definition::fiz("eu04_v1/eu04-01"), 0.0, "second"}};
+ CHECK(scenario_couple(first, second) == scenario_coupling);
+ }
+ SUBCASE("two diesel ones") {
+ auto first{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "first"}};
+ auto second{vehicle{definition::fiz("wmb10_v1/wmb10"), 0.0, "second"}};
+ CHECK(scenario_couple(first, second) == scenario_coupling);
+ }
+ SUBCASE("a diesel-mechanical and a diesel-electric one") {
+ auto first{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "first"}};
+ auto second{vehicle{definition::fiz("st44_v2/m62-1151"), 0.0, "second"}};
+ CHECK(scenario_couple(first, second) == scenario_coupling);
+ }
+ SUBCASE("an electric multiple unit's motor car and its control trailer") {
+ auto trailer{vehicle{definition::fiz("en57_v1/5bgb"), 0.0, "trailer"}};
+ auto motorcar{vehicle{definition::fiz("en57_v1/6bai"), 0.0, "motorcar"}};
+ CHECK(scenario_couple(trailer, motorcar) == scenario_coupling);
+ }
+ SUBCASE("a diesel locomotive and a car") {
+ auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
+ auto car{vehicle{definition::load("wagon"), 0.0, "car"}};
+ CHECK(scenario_couple(diesel, car) == scenario_coupling);
+ }
+}
+
+TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive couple without the control connection") {
+ crash_damage_setting const crashdamage{true};
+ control_coupling_check_setting const check{true};
+ auto const flag{coupling::coupler | coupling::brakehose | coupling::control};
+ auto automatic = [flag](std::string const &Path) {
+ return definition::fiz(Path).set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", flag);
+ };
+ auto moving{vehicle{automatic("e6act_v2/e6acta"), 5.0, "moving"}};
+
+ SUBCASE("a diesel one") {
+ auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+ REQUIRE(couple_during(pair, 3.0));
+ CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose));
+ }
+ SUBCASE("an electric one") {
+ auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+ REQUIRE(couple_during(pair, 3.0));
+ CHECK(pair.coupling() == flag);
+ }
+}
+
+TEST_CASE("couplers: the AI and the player get the coupling the vehicles can take") {
+ control_coupling_check_setting const check{true};
+ auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}};
+ auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
+ auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}};
+
+ CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == (scenario_coupling & ~coupling::control));
+ CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling);
+ // nothing to take away without the control connection asked for
+ CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, coupling::coupler) == coupling::coupler);
+}
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index b4f2e14be..99a2decb9 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -751,6 +751,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
return true;
}
+ if (token == "controlcoupling.enginecheck")
+ {
+ ParseOne(Parser, control_coupling_engine_check, 1);
+ return true;
+ }
+
return false;
}
@@ -1590,6 +1596,7 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent );
export_as_text( Output, "scenario.weather.temperature", AirTemperature );
export_as_text( Output, "ai.trainman", AITrainman );
+ export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check );
export_as_text( Output, "scalespeculars", ScaleSpecularValues );
export_as_text( Output, "gfxrenderer", GfxRenderer );
export_as_text( Output, "shadows", RenderShadows );
diff --git a/utilities/Globals.h b/utilities/Globals.h
index ad216cd96..d079db2cb 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -260,6 +260,7 @@ struct global_settings {
bool captureonstart = true;
bool render_cab = true;
bool crash_damage = true;
+ bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520)
bool gui_defaultwindows = true;
bool gui_showtranscripts = true;
bool gui_trainingdefault = false;
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..b267b390b 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6907,8 +6907,14 @@ TController::UpdateConnect() {
auto *vehicle { iCouplingVehicle.value().first };
auto const couplingend { iCouplingVehicle.value().second };
auto *vehicleparameters { vehicle->MoverParameters };
- if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != iCoupler ) {
- auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] };
+ auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] };
+ // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520)
+ auto expectedcoupling { iCoupler };
+ if( neighbour.vehicle != nullptr ) {
+ auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr };
+ expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler );
+ }
+ if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) {
if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) {
// check whether we need to attach coupler adapter
auto coupleriscompatible{true};
@@ -6930,7 +6936,7 @@ TController::UpdateConnect() {
}
}
// NOTE: no else as the preceeding block can potentially establish expected connection
- if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == iCoupler ) {
+ if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) {
// jeżeli został podłączony
CheckVehicles( Connect ); // sprawdzić światła nowego składu
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index d5f60e332..659b718fa 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -1713,7 +1713,8 @@ TDynamicObject::couple( int const Side ) {
if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::control ) ) {
// ukrotnionko
if( (coupler.AllowedFlag & othercoupler.AllowedFlag & coupling::control) == coupling::control
- && coupler.control_type == othercoupler.control_type ) {
+ && coupler.control_type == othercoupler.control_type
+ && ( MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | coupling::control ) & coupling::control ) != 0 ) {
if( MoverParameters->Attach(
Side, neighbour.vehicle_end,
othervehicleparams,
From 39244a88a500d51ada0f8c33ccc3056848466d22 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 21:17:12 +0100
Subject: [PATCH 045/104] tests: wait for the pressure switches before notching
up
full_power() notched up as soon as the controlling half had closed its line
contactors. In the ET42 test the locomotive brake is still at about 2.0 bar
then, right at the pressure switch threshold, so whether the second half
starts as well depended on thousandths of a bar in its cylinder: a half whose
switch is on when the controller leaves zero doesn't close its line
contactors until the controller is back at zero. Any change to the air
brakes could tip it either way (with the corrected ESt3 the second half
stayed off and the train reached 88.7 instead of 106 km/h).
The helper now waits, as a driver does, until no pressure switch in the
train cuts the start off.
---
tests/unit/scenario.cpp | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp
index b933a0ab5..4af8be18a 100644
--- a/tests/unit/scenario.cpp
+++ b/tests/unit/scenario.cpp
@@ -5,6 +5,21 @@
namespace test {
+namespace {
+
+// whether the pressure switch of a vehicle in the train still cuts the start off: a half of a locomotive whose
+// switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero
+bool start_cut_off(consist &Train) {
+ for (std::size_t i = 0; i < Train.size(); ++i) {
+ if (Train[i].mover().ControlPressureSwitch) {
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace
+
scenario::scenario(std::string Name, std::vector Channels, track const &Track) : m_name(std::move(Name)), m_channels(std::move(Channels)), m_track(Track) {
reseed_random();
}
@@ -53,6 +68,11 @@ void scenario::get_going() {
void scenario::full_power(double Seconds) {
auto &controlling{driver().controlling};
+ // as a driver does, wait for the brakes to let go far enough for every pressure switch of the train to allow the
+ // start; otherwise whether all the halves of a locomotive start hangs on thousandths of a bar of their cylinders
+ for (int i = 0; i < 120 && start_cut_off(m_train); ++i) {
+ wait(1.0);
+ }
controlling.IncMainCtrl(1);
for (int i = 0; i < 90 && false == controlling.StLinFlag; ++i) {
wait(1.0);
From 8f51ea9a19a8900d424236deb545e978d3ff0811 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 21:32:41 +0100
Subject: [PATCH 046/104] feat(ai): suggested pantograph setup for shunting in
the .fiz (eu07/maszyna#461)
A new optional key in the AI section of the .fiz, ShuntPantstate= (bits as in
Pantstate: 1 front, 2 rear, 3 both), sets the pantographs the AI driver keeps
up while its order is Shunt or Loose_shunt, moving and standing alike: it
raises those of the setup and lowers the others once one of the setup
collects the voltage, and doesn't raise more when idling. Lowering on the
track's demand still comes first. Without the key (default 0) nothing
changes, so an ET41 no longer has to shunt on all four pantographs once its
.fiz says so.
SVN data, optional: add "AI: ShuntPantstate=<1|2|3>" to the .fiz of vehicles
that should shunt on fewer pantographs, e.g. dynamic/pkp/et41_v2/203e-a.fiz,
203e-b.fiz and their _dsa150 variants (no AI line there yet). Without it the
vehicles behave as before.
(eu07/maszyna#461)
---
McZapkie/MOVER.h | 3 +++
McZapkie/Mover.cpp | 1 +
tests/unit/test_ai_hints.cpp | 31 +++++++++++++++++++++++++
vehicle/Driver.cpp | 44 +++++++++++++++++++++++++++++++++++-
vehicle/Driver.h | 1 +
5 files changed, 79 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/test_ai_hints.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..b29f2afa9 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2300,6 +2300,9 @@ class TMoverParameters
plc::basic_controller m_plc;
int AIHintPantstate{0}; // suggested pantograph setup
+ // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front,
+ // 2 rear, 3 both; 0 (the default) shunts with the pantographs handled as in train mode
+ int AIHintShuntPantstate{0};
bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while
double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..7fb2ed8b5 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -11474,6 +11474,7 @@ void TMoverParameters::LoadFIZ_AI(std::string const &Input)
{
extract_value(AIHintPantstate, "Pantstate", Input, "");
+ extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, "");
extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, "");
extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, "");
}
diff --git a/tests/unit/test_ai_hints.cpp b/tests/unit/test_ai_hints.cpp
new file mode 100644
index 000000000..d01e421c9
--- /dev/null
+++ b/tests/unit/test_ai_hints.cpp
@@ -0,0 +1,31 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+using test::definition;
+using test::vehicle;
+
+// the hints for the AI driver from the AI section of the .fiz
+
+TEST_CASE("ai hints: without the AI section the pantographs follow the built-in logic") {
+ vehicle wagon{definition::load("wagon")};
+
+ CHECK(wagon->AIHintPantstate == 0);
+ CHECK(wagon->AIHintShuntPantstate == 0);
+ CHECK(wagon->AIHintPantUpIfIdle);
+}
+
+TEST_CASE("ai hints: the suggested pantograph setup for shunting is read apart from the one for train mode") {
+ // eu07/maszyna#461: so the ET41 doesn't shunt with all of its four pantographs up
+ vehicle shunting{definition::load("wagon").set("AI", "Pantstate", 1).set("AI", "ShuntPantstate", 2)};
+
+ CHECK(shunting->AIHintPantstate == 1);
+ CHECK(shunting->AIHintShuntPantstate == 2);
+}
+
+TEST_CASE("ai hints: a .fiz with the setup for train mode only has none for shunting") {
+ vehicle train{definition::load("wagon").set("AI", "Pantstate", 3)};
+
+ CHECK(train->AIHintPantstate == 3);
+ CHECK(train->AIHintShuntPantstate == 0);
+}
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..682061b68 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6115,6 +6115,13 @@ TController::control_pantographs() {
fActionTime = -2.0 - Random(10);
}
+ // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none
+ // or the vehicle isn't shunting
+ auto const shuntpantographsetup {
+ ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) != 0 ?
+ mvOccupied->AIHintShuntPantstate :
+ 0 };
+
// raise/lower pantographs as needed
auto const useregularpantographlayout {
pVehicle->Next(coupling::control) == nullptr // standalone
@@ -6141,7 +6148,11 @@ TController::control_pantographs() {
// jeśli nie trzeba opuszczać pantografów
// TODO: check if faction alone reduces frequency enough
if( fActionTime > 0.0 ) {
- if( mvOccupied->AIHintPantstate == 0 ) {
+ if( shuntpantographsetup != 0 ) {
+ // shunting with the pantograph setup the .fiz suggests for it
+ control_pantographs_setup( shuntpantographsetup );
+ }
+ else if( mvOccupied->AIHintPantstate == 0 ) {
// jazda na tylnym
if( iDirection >= 0 && useregularpantographlayout ) {
// jak jedzie w kierunku sprzęgu 0
@@ -6194,6 +6205,12 @@ TController::control_pantographs() {
}
}
}
+ else if( shuntpantographsetup != 0 ) {
+ // shunting with the suggested setup, also while standing, and without raising more pantographs when idling
+ if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) {
+ control_pantographs_setup( shuntpantographsetup );
+ }
+ }
else {
if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 )
{
@@ -6220,6 +6237,31 @@ TController::control_pantographs() {
}
}
+// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once
+// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way
+void
+TController::control_pantographs_setup( int const Setup ) {
+
+ auto const front { ( Setup & 1 << 0 ) != 0 };
+ auto const rear { ( Setup & 1 << 1 ) != 0 };
+ if( front ) {
+ cue_action( driver_hint::frontpantographvalveon );
+ }
+ if( rear ) {
+ cue_action( driver_hint::rearpantographvalveon );
+ }
+ if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) };
+ false == setuplive ) {
+ return;
+ }
+ if( false == front ) {
+ cue_action( driver_hint::frontpantographvalveoff );
+ }
+ if( false == rear ) {
+ cue_action( driver_hint::rearpantographvalveoff );
+ }
+}
+
void
TController::control_horns( double const Timedelta ) {
// horn control
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index f88e115ac..8c661328c 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -320,6 +320,7 @@ private:
void scan_obstacles( double const Range );
void control_wheelslip();
void control_pantographs();
+ void control_pantographs_setup( int const Setup );
void control_horns( double const Timedelta );
void control_security_system( double const Timedelta );
void control_handles();
From 30bdc3da6139d0e3896aabe61bbb2980c06c7582 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 21:33:28 +0100
Subject: [PATCH 047/104] feat: radio fuse, a cut-off in the radio's power
supply (eu07/maszyna#438)
TMoverParameters::RadioFuse, closed by default, stands for a fuse in the
cabinet, a lever on the desk or the switch on the radio's power supply.
RadioPowered() needs it closed, so with it open the radio's buttons, calls,
messages and the radio-stop stop working; opening it at a standstill resets
the radio-stop as switching the radio off does, and the radio and radio-stop
lamps go out. New commands radiofusetoggle/radiofuseenable/radiofusedisable
(no default keys), cab controls radiofuse_sw: (follows the fuse state),
radiofuseon_sw: and radiofuseoff_sw:, and radio_fuse for the Python screens.
The AI turning the radio back on closes the fuse too.
Existing vehicles don't change: the fuse starts closed and opens only from a
new cab control or a bound key. SVN data, optional: cabs that have such a
fuse or lever get one of the new controls in their .mmd, in the form of
radio_sw: (e.g. "radiofuse_sw: { rot 0 0 0 }"); lang/*.po can
translate "radio fuse".
(eu07/maszyna#438)
---
McZapkie/MOVER.h | 7 ++++--
McZapkie/Mover.cpp | 2 +-
application/driverhints.cpp | 3 ++-
input/command.cpp | 6 +++++
input/command.h | 3 +++
input/driverkeyboardinput.cpp | 3 +++
input/drivermouseinput.cpp | 9 +++++++
tests/unit/test_radio.cpp | 30 ++++++++++++++++++++++++
utilities/translation.cpp | 3 +++
vehicle/Driver.cpp | 2 +-
vehicle/DynObj.cpp | 3 ++-
vehicle/Train.cpp | 44 +++++++++++++++++++++++++++++++++--
vehicle/Train.h | 3 +++
vr/openvr_imp.cpp | 9 +++++++
14 files changed, 119 insertions(+), 8 deletions(-)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..b976174ec 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -1590,6 +1590,9 @@ class TMoverParameters
double EpForce = 0.0; /*Poziom zadanej sily EP*/
bool Signalling = false; /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/
bool Radio = false; /*Czy jest zalaczony radiotelefon*/
+ // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power
+ // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before
+ bool RadioFuse = true;
float NominalBatteryVoltage = 0.f; /*Winger - baterie w elektrykach*/
TDimension Dim; /*wymiary*/
double Cx = 0.0; /*wsp. op. aerodyn.*/
@@ -2473,10 +2476,10 @@ class TMoverParameters
auto const oilmanual{OilPump.start_type != start_t::automatic};
return (fuelmanual || oilmanual) && (false == fuelmanual || FuelPump.is_enabled) && (false == oilmanual || OilPump.is_enabled);
}
- // whether the radio is switched on and has the low voltage to work
+ // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work
bool RadioPowered() const
{
- return Radio && (Power24vIsAvailable || Power110vIsAvailable);
+ return Radio && RadioFuse && (Power24vIsAvailable || Power110vIsAvailable);
}
/*obrot kol uwzgledniajacy poslizg*/
double ComputeRotatingWheel(double WForce, double dt, double n) const;
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 330e8eb8f..dae4996a8 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -3145,7 +3145,7 @@ void TMoverParameters::SecuritySystemCheck(double dt)
bool isPower = Power24vIsAvailable || Power110vIsAvailable;
SecuritySystem.update(dt, Vel, isPower, CabActive);
- if (!Battery || !Radio)
+ if (!Battery || !Radio || !RadioFuse)
{ // wyłączenie baterii deaktywuje sprzęt
RadiostopSwitch(false);
}
diff --git a/application/driverhints.cpp b/application/driverhints.cpp
index bcfd7dbd0..cd1a43b9e 100644
--- a/application/driverhints.cpp
+++ b/application/driverhints.cpp
@@ -130,12 +130,13 @@ TController::cue_action( driver_hint const Action, float const Actionparameter )
case driver_hint::radioon: {
if( AIControllFlag ) {
mvOccupied->Radio = true;
+ mvOccupied->RadioFuse = true;
}
remove_hint( driver_hint::radiooff );
hint(
Action,
[this](float const /*Parameter*/) {
- return mvOccupied->Radio == true; } );
+ return mvOccupied->Radio && mvOccupied->RadioFuse; } );
break;
}
case driver_hint::radiochannel: {
diff --git a/input/command.cpp b/input/command.cpp
index 0ae67cfa5..574d4dca9 100644
--- a/input/command.cpp
+++ b/input/command.cpp
@@ -158,6 +158,9 @@ commanddescription_sequence Commands_descriptions = {
{"radiovolumeincrease", command_target::vehicle, command_mode::oneoff},
{"radiovolumedecrease", command_target::vehicle, command_mode::oneoff},
{"radiovolumeset", command_target::vehicle, command_mode::oneoff},
+ {"radiofusetoggle", command_target::vehicle, command_mode::oneoff},
+ {"radiofuseenable", command_target::vehicle, command_mode::oneoff},
+ {"radiofusedisable", command_target::vehicle, command_mode::oneoff},
{"cabchangeforward", command_target::vehicle, command_mode::oneoff},
{"cabchangebackward", command_target::vehicle, command_mode::oneoff},
{"modernlightdimmerdecrease", command_target::vehicle, command_mode::oneoff},
@@ -544,6 +547,9 @@ std::unordered_map const commandMap = {
{"radiovolumeincrease", user_command::radiovolumeincrease},
{"radiovolumedecrease", user_command::radiovolumedecrease},
{"radiovolumeset", user_command::radiovolumeset},
+ {"radiofusetoggle", user_command::radiofusetoggle},
+ {"radiofuseenable", user_command::radiofuseenable},
+ {"radiofusedisable", user_command::radiofusedisable},
{"cabchangeforward", user_command::cabchangeforward},
{"cabchangebackward", user_command::cabchangebackward},
{"viewturn", user_command::viewturn},
diff --git a/input/command.h b/input/command.h
index ddacef4a0..540bfc8f8 100644
--- a/input/command.h
+++ b/input/command.h
@@ -151,6 +151,9 @@ enum class user_command
radiovolumeincrease,
radiovolumedecrease,
radiovolumeset,
+ radiofusetoggle,
+ radiofuseenable,
+ radiofusedisable,
cabchangeforward,
cabchangebackward,
diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp
index e7e636b31..047f3678c 100644
--- a/input/driverkeyboardinput.cpp
+++ b/input/driverkeyboardinput.cpp
@@ -160,6 +160,9 @@ driverkeyboard_input::default_bindings() {
// radiovolumeincrease,
// radiovolumedecrease,
// radiovolumeset,
+ // radiofusetoggle,
+ // radiofuseenable,
+ // radiofusedisable,
{ cabchangeforward, {GLFW_KEY_HOME, ""} },
{ cabchangebackward, {GLFW_KEY_END, ""} },
// viewturn,
diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp
index 22562b856..8c9763bf9 100644
--- a/input/drivermouseinput.cpp
+++ b/input/drivermouseinput.cpp
@@ -783,6 +783,15 @@ drivermouse_input::default_bindings() {
{ "radiooff_sw:", {
radiodisable,
none } },
+ { "radiofuse_sw:", {
+ radiofusetoggle,
+ none } },
+ { "radiofuseon_sw:", {
+ radiofuseenable,
+ none } },
+ { "radiofuseoff_sw:", {
+ radiofusedisable,
+ none } },
{ "radiochannel_sw:", {
radiochannelincrease,
radiochanneldecrease } },
diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp
index 33a12f72d..b65cc2ced 100644
--- a/tests/unit/test_radio.cpp
+++ b/tests/unit/test_radio.cpp
@@ -26,3 +26,33 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") {
}
CHECK_FALSE(vehicle->RadioPowered());
}
+
+// the cut-off in the radio's power supply (eu07/maszyna#438): a fuse, a desk lever or the switch on the radio's
+// power supply, closed unless the driver opens it
+
+TEST_CASE("radio: the radio fuse is closed by default") {
+ test::vehicle vehicle{test::definition::load("wagon")};
+ CHECK(vehicle->RadioFuse);
+}
+
+TEST_CASE("radio: an opened radio fuse cuts the radio off") {
+ test::vehicle vehicle{test::definition::load("wagon")};
+ vehicle->Radio = true;
+ vehicle->Power24vIsAvailable = true;
+ vehicle->RadioFuse = false;
+ CHECK_FALSE(vehicle->RadioPowered());
+ vehicle->RadioFuse = true;
+ CHECK(vehicle->RadioPowered());
+}
+
+TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") {
+ test::vehicle loco{test::definition::fiz("4e_v1/4e")};
+ loco->Battery = true;
+ loco->Radio = true;
+ REQUIRE(loco->RadiostopSwitch(true));
+ loco->SecuritySystemCheck(0.1);
+ CHECK(loco->RadioStopFlag);
+ loco->RadioFuse = false;
+ loco->SecuritySystemCheck(0.1);
+ CHECK_FALSE(loco->RadioStopFlag);
+}
diff --git a/utilities/translation.cpp b/utilities/translation.cpp
index c0dbeb1a0..16e07d01c 100644
--- a/utilities/translation.cpp
+++ b/utilities/translation.cpp
@@ -271,6 +271,9 @@ std::string locale::label_cab_control(std::string const &Label)
{ "converteroff_sw:", STRN("converter") },
{ "main_sw:", STRN("line breaker") },
{ "radio_sw:", STRN("radio") },
+ { "radiofuse_sw:", STRN("radio fuse") },
+ { "radiofuseon_sw:", STRN("radio fuse") },
+ { "radiofuseoff_sw:", STRN("radio fuse") },
{ "radiochannel_sw:", STRN("radio channel") },
{ "radiochannelprev_sw:", STRN("radio channel") },
{ "radiochannelnext_sw:", STRN("radio channel") },
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..0de55551d 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6294,7 +6294,7 @@ TController::control_security_system( double const Timedelta ) {
}
}
if( iEngineActive
- && false == mvOccupied->Radio
+ && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse )
&& false == mvOccupied->RadioStopFlag ) {
// otherwise if it's safe to do so, turn the radio back on
// arbitrary 5 sec delay before switching radio back on
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index d5f60e332..89359fc39 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -7197,7 +7197,8 @@ void TDynamicObject::RadioStop()
if( Mechanik ) {
// o ile ktoś go prowadzi
if( MoverParameters->SecuritySystem.radiostop_available()
- && MoverParameters->Radio ) {
+ && MoverParameters->Radio
+ && MoverParameters->RadioFuse ) {
// jeśli pojazd ma RadioStop i jest on aktywny
// HACK cast until math types unification
glm::dvec3 pos = static_cast(vPosition);
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..bc0924ce8 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -485,6 +485,9 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = {
{user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease},
{user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease},
{user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset},
+ {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle},
+ {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable},
+ {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable},
{user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward},
{user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward},
{user_command::generictoggle0, &TTrain::OnCommand_generictoggle},
@@ -785,6 +788,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const
}
}
dict->insert("radio", mvOccupied->Radio);
+ dict->insert("radio_fuse", mvOccupied->RadioFuse);
dict->insert("radio_channel", RadioChannel());
dict->insert("radio_volume", m_radiovolume);
dict->insert("door_lock", mvOccupied->Doors.lock_enabled);
@@ -8032,6 +8036,41 @@ void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command)
}
}
+// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the
+// radio-stop flag included
+void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command)
+{
+ if (Command.action != GLFW_PRESS)
+ {
+ return;
+ }
+
+ if (Train->mvOccupied->RadioFuse)
+ {
+ OnCommand_radiofusedisable(Train, Command);
+ }
+ else
+ {
+ OnCommand_radiofuseenable(Train, Command);
+ }
+}
+
+void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command)
+{
+ if (Command.action == GLFW_PRESS)
+ {
+ Train->mvOccupied->RadioFuse = true;
+ }
+}
+
+void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command)
+{
+ if (Command.action == GLFW_PRESS)
+ {
+ Train->mvOccupied->RadioFuse = false;
+ }
+}
+
void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &Command)
{
@@ -9053,9 +9092,9 @@ bool TTrain::Update(double const Deltatime)
// KURS90
btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350);
btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450);
- btLampkaRadio.Turn(mvOccupied->Radio);
+ btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse);
btLampkaRadioMessage.Turn(radio_message_played);
- btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioStopFlag);
+ btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag);
btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0);
// NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu
if (DynamicObject->Mechanik != nullptr)
@@ -11962,6 +12001,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con
{"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled},
{"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled},
{"radio_sw:", &mvOccupied->Radio},
+ {"radiofuse_sw:", &mvOccupied->RadioFuse},
{"cablight_sw:", &Cabine[iCabn].bLight},
{"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate},
{"couplingdisconnect_sw:", &m_couplingdisconnect},
diff --git a/vehicle/Train.h b/vehicle/Train.h
index 009b349b4..7071bf212 100644
--- a/vehicle/Train.h
+++ b/vehicle/Train.h
@@ -489,6 +489,9 @@ class TTrain {
static void OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command);
static void OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command);
static void OnCommand_radiovolumeset(TTrain *Train, command_data const &Command);
+ static void OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command);
+ static void OnCommand_radiofuseenable(TTrain *Train, command_data const &Command);
+ static void OnCommand_radiofusedisable(TTrain *Train, command_data const &Command);
static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command );
static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command );
static void OnCommand_generictoggle( TTrain *Train, command_data const &Command );
diff --git a/vr/openvr_imp.cpp b/vr/openvr_imp.cpp
index 15467d006..14f901f51 100644
--- a/vr/openvr_imp.cpp
+++ b/vr/openvr_imp.cpp
@@ -669,6 +669,15 @@ std::unordered_map vr_openvr::m_buttonb
{ "radiooff_sw:", {
user_command::radiodisable,
user_command::none } },
+ { "radiofuse_sw:", {
+ user_command::radiofusetoggle,
+ user_command::none } },
+ { "radiofuseon_sw:", {
+ user_command::radiofuseenable,
+ user_command::none } },
+ { "radiofuseoff_sw:", {
+ user_command::radiofusedisable,
+ user_command::none } },
{ "radiochannel_sw:", {
user_command::radiochannelincrease,
user_command::radiochanneldecrease } },
From 292092a7aa63184f62c7ff619b7ea3c2385cceff Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 21:40:02 +0100
Subject: [PATCH 048/104] AI braking: take care of the Sonar remarks on the new
braking code
No change in what the AI does; only the structure of the code that came in
with the braking changes:
- S107: shaped_braking_demand() takes the consist brake table as a struct
instead of four separate parameters; its lambdas capture explicitly.
- S3358: brake_response_horizon() picks the BrakeDelay entry without a
nested conditional operator.
- S5276: the speed passed to braking_distance_multiplier() is converted to
float explicitly, as it was implicitly before.
- S134: the stop case of the proximity range is an else-if of its own, and
its body a method of its own, adjust_desired_speed_for_final_approach(),
with early returns instead of nested ifs. The cargo train threshold
push is a conditional subtraction instead of a nested if.
- S3776: pick_optimal_speed() hands the uncoupling stages and the uphill
stand to set_velocity_for_uncoupling() and
hold_train_coming_to_stand_uphill().
---
vehicle/Driver.cpp | 257 ++++++++++++++++++++++++---------------------
vehicle/Driver.h | 3 +
2 files changed, 141 insertions(+), 119 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 303560e98..cbdd97c62 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7239,6 +7239,59 @@ TController::handle_orders() {
UpdateChangeDirection();
}
+// the stages of uncoupling: each one sets the speed for the next
+void
+TController::set_velocity_for_uncoupling() {
+
+ if( iVehicleCount < 0 ) {
+ // 4th stage: restore initial direction
+ if( ( iDrivigFlags & movePress ) != 0 ) {
+ SetVelocity( 0, 0, stopJoin );
+ }
+ return;
+ }
+ // 3rd stage: compress buffers and uncouple
+ if( ( iDrivigFlags & movePress ) != 0 && iDirection == iDirectionOrder ) {
+ SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2
+ return;
+ }
+ // 1st stage: bring it to stop
+ // 2nd stage: apply consist brakes and change direction
+ SetVelocity( 0, 0, stopJoin );
+}
+
+// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
+// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
+// stands, and is applied for real if the train has started to roll back
+void
+TController::hold_train_coming_to_stand_uphill() {
+
+ if( ( false == is_train() )
+ || ( ( OrderCurrentGet() & Obey_train ) == 0 )
+ || ( VelNext != 0.0 )
+ || ( ActualProximityDist > fMaxProximityDist )
+ || ( fAccGravity >= -0.025 ) ) {
+ return;
+ }
+ auto const vel { DirectionalVel() };
+ if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
+ VelDesired = 0.0;
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ return;
+ }
+ if( ( vel < 0.0 )
+ || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) )
+ // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops:
+ // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any
+ // sooner and the brake takes off more of the distance than the stop was planned with
+ || ( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) {
+ // the gradient alone already slows the train down nearly this much; ask for enough on top of it that
+ // the brake is applied for sure, not held back by the margin against small corrections
+ AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() );
+ }
+}
+
void
TController::pick_optimal_speed( double const Range ) {
@@ -7274,23 +7327,7 @@ TController::pick_optimal_speed( double const Range ) {
}
// uncoupling mode changes velocity/acceleration between stages
if( ( OrderCurrentGet() & Disconnect ) != 0 ) {
- if( iVehicleCount >= 0 ) {
- // 3rd stage: compress buffers and uncouple
- if( (iDrivigFlags & movePress) != 0 && iDirection == iDirectionOrder ) {
- SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2
- }
- // 1st stage: bring it to stop
- // 2nd stage: apply consist brakes and change direction
- else {
- SetVelocity( 0, 0, stopJoin );
- }
- }
- else {
- // 4th stage: restore initial direction
- if( ( iDrivigFlags & movePress ) != 0 ) {
- SetVelocity( 0, 0, stopJoin );
- }
- }
+ set_velocity_for_uncoupling();
}
VelLimitLastDist = { VelDesired, -1 };
@@ -7343,32 +7380,8 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
- if( is_train()
- && ( ( OrderCurrentGet() & Obey_train ) != 0 )
- && ( VelNext == 0.0 )
- && ( ActualProximityDist <= fMaxProximityDist )
- && ( fAccGravity < -0.025 ) ) {
- // uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
- // brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
- // stands, and is applied for real if the train has started to roll back. done last, so that none of
- // the adjustments above, made for a train moving forward, can undo it
- auto const vel { DirectionalVel() };
- if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
- VelDesired = 0.0;
- AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
- }
- else if( ( vel < 0.0 )
- || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) )
- // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops:
- // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any
- // sooner and the brake takes off more of the distance than the stop was planned with
- || ( ( BrakeSystem == TBrakeSystem::Pneumatic )
- && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) {
- // the gradient alone already slows the train down nearly this much; ask for enough on top of it that
- // the brake is applied for sure, not held back by the margin against small corrections
- AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() );
- }
- }
+ // done last, so that none of the adjustments above, made for a train moving forward, can undo it
+ hold_train_coming_to_stand_uphill();
// if the route ahead is blocked we might need to head the other way
check_route_behind( 1000 ); // NOTE: legacy scan range value
@@ -7543,13 +7556,10 @@ brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brak
auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 };
if( Brakesystem == TBrakeSystem::Pneumatic ) {
+ // BrakeDelay holds the release and the application time in G, then the same two in P
+ auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 };
auto const isrelease { Acceleration < 0.0 };
- horizon = std::max(
- horizon,
- 0.5 * (
- Vehicle->BrakeDelayFlag > bdelay_G ?
- Vehicle->BrakeDelay[ isrelease ? 0 : 1 ] :
- Vehicle->BrakeDelay[ isrelease ? 2 : 3 ] ) );
+ horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] );
}
return horizon;
}
@@ -7569,15 +7579,26 @@ uphill_coasting_speed( double const Distance, double const Gravity ) {
// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train
// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the
// consist brake table says it does (cast iron blocks grip harder as the train slows)
+struct consist_brake_table {
+ double const *a0; // deceleration at handle position 1, by speed
+ double const *a1; // deceleration added by each quarter of a position, by speed
+ int size; // entries, up to the vehicle's top speed
+ double vmax; // the vehicle's top speed [km/h]
+
+ // deceleration [m/s2] of a full service application at Kmh
+ double full_braking( double const Kmh ) const {
+ auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) };
+ return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); }
+};
+
static double
shaped_braking_demand(
double const Velocity, double const Target, double const Distance, double const Gravity,
- double const Vmax, double const *Brakea0, double const *Brakea1, int const Tablesize ) {
+ consist_brake_table const &Table ) {
- auto const fullbraking = [&]( double const Kmh ) {
- auto const index { std::clamp( static_cast( Tablesize * Kmh / std::max( 1.0, Vmax ) ), 1, Tablesize ) };
- return std::max( 0.01, Brakea0[ index ] + 12.0 * Brakea1[ index ] ); };
- auto const travel = [&]( double const Ratio ) {
+ auto const fullbraking = [&Table]( double const Kmh ) {
+ return Table.full_braking( Kmh ); };
+ auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) {
auto const steps { 24 };
auto const step { ( Velocity - Target ) / steps };
auto distance { 0.0 };
@@ -7603,6 +7624,53 @@ shaped_braking_demand(
return Gravity - high * fullbraking( Velocity );
}
+// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel
+void
+TController::adjust_desired_speed_for_final_approach( double const Vel ) {
+
+ if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) {
+ // for cars (and others) coast at low speed until we hit min proximity range
+ VelDesired = min_speed( VelDesired, 5.0 );
+ return;
+ }
+ // trains
+ if( ( OrderCurrentGet() & ( Shunt | Connect ) )
+ && ( Obstacle.distance < 50 ) ) {
+ // crude detection of edge case, if approaching another vehicle coast slowly until min distance
+ // this should allow to bunch up trainsets more on sidings
+ VelDesired = min_speed( 5.0, VelDesired );
+ return;
+ }
+ // hamowanie tak, aby stanąć
+ if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
+ VelDesired = VelNext;
+ AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
+ AccDesired = std::min( AccDesired, fAccThreshold );
+ return;
+ }
+ // a train keeps its desired speed until the lower edge of the stopping window (a desired
+ // speed of 0 here asks for hard braking whatever the distance left), aims at the middle
+ // of the window, and asks only for what that takes
+ auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
+ AccDesired = (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ // cast iron blocks grip harder as the train comes to a stand
+ shaped_braking_demand(
+ Vel, VelNext, stoppingroom, fAccGravity,
+ { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) :
+ ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) );
+ if( ( fAccGravity < -0.025 )
+ && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
+ && ( false == uphill_brake_committed( Vel ) )
+ && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) {
+ // uphill the gradient alone would bring the train to a stand short of the
+ // middle of the stopping window; keep it rolling at the present speed until that changes,
+ // but no faster than the gradient alone can take off by the middle of the window
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
+ }
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7634,65 +7702,20 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
AccDesired = AccPreferred;
}
}
+ else if( ( ActualProximityDist > fMinProximityDist )
+ // only a stop has a final approach of its own inside the proximity range; a lower speed ahead
+ // keeps the braking curve below right up to where it begins, or the train would stop braking
+ // (and even take power) that far out
+ && ( VelNext == 0.0 )
+ && ( ActualProximityDist < fMaxProximityDist ) ) {
+ // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
+ // jak minął już maksymalny dystans po prostu hamuj (niski stopień)
+ // ma stanąć, a jest w drodze hamowania albo ma jechać
+ adjust_desired_speed_for_final_approach( vel );
+ AccDesired = std::min( AccDesired, AccPreferred );
+ }
else if (ActualProximityDist > fMinProximityDist) {
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
- // only a stop has a final approach of its own inside the proximity range; a lower speed ahead
- // keeps the braking curve below right up to where it begins, or the train would stop braking
- // (and even take power) that far out
- if( ( VelNext == 0.0 ) && ( ActualProximityDist < fMaxProximityDist ) ) {
- // jak minął już maksymalny dystans po prostu hamuj (niski stopień)
- // ma stanąć, a jest w drodze hamowania albo ma jechać
-/*
- VelDesired = min_speed( VelDesired, VelNext );
-*/
- if( VelNext == 0.0 ) {
- if( mvOccupied->CategoryFlag & 1 ) {
- // trains
- if( OrderCurrentGet() & (Shunt | Connect)
- && Obstacle.distance < 50 ) {
- // crude detection of edge case, if approaching another vehicle coast slowly until min distance
- // this should allow to bunch up trainsets more on sidings
- VelDesired = min_speed( 5.0, VelDesired );
- }
- else {
- // hamowanie tak, aby stanąć
- if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
- VelDesired = VelNext;
- AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
- AccDesired = std::min( AccDesired, fAccThreshold );
- }
- else {
- // a train keeps its desired speed until the lower edge of the stopping window (a desired
- // speed of 0 here asks for hard braking whatever the distance left), aims at the middle
- // of the window, and asks only for what that takes
- auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
- AccDesired = (
- BrakeSystem == TBrakeSystem::Pneumatic ?
- // cast iron blocks grip harder as the train comes to a stand
- shaped_braking_demand(
- vel, VelNext, stoppingroom, fAccGravity,
- mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize ) :
- ( VelNext * VelNext - vel * vel ) / ( 25.92 * stoppingroom ) );
- if( ( fAccGravity < -0.025 )
- && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
- && ( false == uphill_brake_committed( vel ) )
- && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > stopping_margin() ) ) {
- // uphill the gradient alone would bring the train to a stand short of the
- // middle of the stopping window; keep it rolling at the present speed until that changes,
- // but no faster than the gradient alone can take off by the middle of the window
- AccDesired = std::min( 0.0, AccPreferred );
- VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
- }
- }
- }
- }
- else {
- // for cars (and others) coast at low speed until we hit min proximity range
- VelDesired = min_speed( VelDesired, 5.0 );
- }
- }
- }
- else {
// outside of max safe range
AccDesired = AccPreferred;
if( vel > min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) {
@@ -7710,7 +7733,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
auto const brakingpointoffset = (
( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
stopping_margin() : // the same stopping point as the final approach
- VelNext * braking_distance_multiplier( VelNext ) );
+ VelNext * braking_distance_multiplier( static_cast( VelNext ) ) );
// a pneumatic brake acts on the state the train will be in once it has responded; while the
// train is still speeding up, plan the deceleration from there, so more is asked for at once
auto velocity { vel };
@@ -7741,7 +7764,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
deceleration = shaped_braking_demand(
velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
- mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize );
+ { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } );
}
AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
if( vel > VelNext ) {
@@ -7761,7 +7784,6 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
}
}
- }
AccDesired = std::min( AccDesired, AccPreferred );
}
else {
@@ -7885,11 +7907,8 @@ TController::adjust_desired_speed_for_current_speed() {
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( IsCargoTrain
- && fBrake_a0[0] > 0.2
- && speedestimate > holdlimit ) {
- AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
- }
+ auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit };
+ AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 );
}
// final tweaks
if( vel > EU07_AI_NOMOVEMENT ) {
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 895e638c5..846923df2 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -349,6 +349,9 @@ private:
void pick_optimal_speed( double const Range );
void adjust_desired_speed_for_obstacles();
void adjust_desired_speed_for_limits();
+ void set_velocity_for_uncoupling();
+ void hold_train_coming_to_stand_uphill();
+ void adjust_desired_speed_for_final_approach( double const Vel );
void adjust_desired_speed_for_target_speed( double const Range );
void adjust_desired_speed_for_current_speed();
void adjust_desired_speed_for_braking_test();
From 99cf46866a1c35dae84967bf86da113bb1b19541 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 22:00:30 +0100
Subject: [PATCH 049/104] AI braking, ESt3: take care of the Sonar remarks on
the braking PRs
No change in what the AI or the distributor does:
- S134: the step of the train brake sized from the consist brake table
moves out of IncBrake() into increase_train_brake(), with early returns.
- S134, S1066: while starting uphill, the check of the released brakes
leaves Ready as it was by assigning the flag instead of nesting an if.
- S6004: the uphill condition of control_uphill_start(), and the target
cylinder pressure of TNESt3::CheckState(), are declared in the
init-statement of their if.
- S5350: the loop summing the tractive force walks the consist through a
pointer to const.
- S3776: the cylinder nozzle calibration for the AL2 relay moves out of
TNESt3::SetSize() into ScaleNozzlesForAL2().
---
McZapkie/Oerlikon_ESt.cpp | 23 +++---
McZapkie/Oerlikon_ESt.h | 1 +
vehicle/Driver.cpp | 152 +++++++++++++++++++-------------------
vehicle/Driver.h | 1 +
4 files changed, 94 insertions(+), 83 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index 1e7a5be66..0717eff5d 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -379,8 +379,7 @@ void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad r
Przys_blok = false;
// sprawdzanie stanu
- double const cel{ CelBCP( CVP, VVP ) };
- if (BCP < cel - 0.01 * BVM && Przys_blok)
+ if (double const cel{ CelBCP( CVP, VVP ) }; BCP < cel - 0.01 * BVM && Przys_blok)
BrakeStatus |= b_on | b_hld; // hamowanie stopniowe;
else if (BCP - 0.1 > cel + 0.01 * BVM)
BrakeStatus &= ~( b_on | b_hld ); // luzowanie;
@@ -486,6 +485,18 @@ void TNESt3::SetLBP(double const P)
LBP = P;
}
+void TNESt3::ScaleNozzlesForAL2() // dysze cylindra przy przekladniku AL2
+{
+ if( PrzekCiagly == nullptr ) {
+ return;
+ }
+ // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9
+ Nozzles[dON] *= 0.914;
+ Nozzles[dTN] *= 0.885;
+ Nozzles[dOO] *= 0.82;
+ Nozzles[dTO] *= 0.8;
+}
+
void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie dysz (rozmiaru ZR)
{
static double const dNO1l = 1.250;
@@ -673,13 +684,7 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
Nozzles[dSd] = 1.1;
Nozzles[dSm] = 0.9;
- if( PrzekCiagly != nullptr ) {
- // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9
- Nozzles[dON] *= 0.914;
- Nozzles[dTN] *= 0.885;
- Nozzles[dOO] *= 0.82;
- Nozzles[dTO] *= 0.8;
- }
+ ScaleNozzlesForAL2();
// przeliczanie z mm^2 na l/m
for (auto &nozzle : Nozzles)
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index 02d65a285..eaae2c032 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -201,6 +201,7 @@ class TNESt3 : public TBrake {
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP) const; // napelniacz sterujacego
+ void ScaleNozzlesForAL2(); // dysze cylindra przy przekladniku AL2
double BVs(double const BCP) const; // napelniacz pomocniczego
void SetSize( int const size, std::string const ¶ms ); // ustawianie dysz (rozmiaru ZR), przekladniki
void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index cbdd97c62..5ac1ccd12 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -2934,6 +2934,75 @@ bool TController::ReleaseEngine() {
// defined further down, with the braking demand it is used for
static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 );
+// one step more of the train brake, sized from the consist brake table against the deceleration asked for
+bool
+TController::increase_train_brake() {
+
+ // dodane dla towarowego
+ float pos_corr = 0;
+
+ TDynamicObject *d;
+ d = pVehicles[0]; // pojazd na czele składu
+ while (d)
+ { // przeliczanie dodatkowego potrzebnego spadku ciśnienia
+ if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) {
+ pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass;
+ }
+ d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
+ }
+ pos_corr = pos_corr / fMass * 2.5;
+
+ if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a)
+ {
+ pos_corr += mvOccupied->Handle->GetCP()*0.2;
+
+ }
+ double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
+
+ if( deltaAcc > brake_increase_margin() )
+ {
+ if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
+ auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH
+ // HACK: stronger braking to overcome SA134 engine behaviour
+ if( is_dmu()
+ && VelNext == 0.0
+ && fBrakeDist < 200.0 ) {
+ BrakeLevelAdd(
+ fBrakeDist / ActualProximityDist < 0.8 ?
+ 0.5 :
+ 1.0 );
+ }
+ return OK;
+ }
+ auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH
+ // brake harder if the acceleration is much higher than desired
+ /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] )
+ && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) {
+ mvOccupied->BrakeLevelAdd( BrakingLevelIncrease );
+ } GBH */
+ if( deltaAcc > 2 * fBrake_a1[0]
+ && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) {
+ /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease );
+ }
+ return OK;
+ }
+ if( BrakeCtrlPosition > 0.0
+ && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
+ && ( fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] )
+ // a train falling further behind needs no full fill time to be seen not to get enough
+ || ( ( fShortfall > 0.02 )
+ && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) {
+ // the table says the present position is enough, but the brake has had its full fill
+ // time since the handle last moved and the train is still not slowing down as asked:
+ // believe the train rather than the table
+ return BrakeLevelAdd( BrakingLevelIncrease );
+ }
+ return false;
+}
+
bool TController::IncBrake()
{ // zwiększenie hamowania
auto OK { false };
@@ -3025,70 +3094,7 @@ bool TController::IncBrake()
OK = false;
}
else {
- // dodane dla towarowego
- float pos_corr = 0;
-
- TDynamicObject *d;
- d = pVehicles[0]; // pojazd na czele składu
- while (d)
- { // przeliczanie dodatkowego potrzebnego spadku ciśnienia
- if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) {
- pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass;
- }
- d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
- }
- pos_corr = pos_corr / fMass * 2.5;
-
- if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a)
- {
- pos_corr += mvOccupied->Handle->GetCP()*0.2;
-
- }
- double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
-
- if( deltaAcc > brake_increase_margin() )
- {
- if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
- OK = /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ); //GBH
- // HACK: stronger braking to overcome SA134 engine behaviour
- if( is_dmu()
- && VelNext == 0.0
- && fBrakeDist < 200.0 ) {
- BrakeLevelAdd(
- fBrakeDist / ActualProximityDist < 0.8 ?
- 0.5 :
- 1.0 );
- }
- }
- else {
- OK = /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); //GBH
- // brake harder if the acceleration is much higher than desired
- /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] )
- && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) {
- mvOccupied->BrakeLevelAdd( BrakingLevelIncrease );
- } GBH */
- if( deltaAcc > 2 * fBrake_a1[0]
- && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) {
- /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease );
- }
- }
- }
- else if( BrakeCtrlPosition > 0.0
- && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
- && ( fBrakeHeldTime > (
- mvOccupied->BrakeDelayFlag > bdelay_G ?
- mvOccupied->BrakeDelay[ 1 ] :
- mvOccupied->BrakeDelay[ 3 ] )
- // a train falling further behind needs no full fill time to be seen not to get enough
- || ( ( fShortfall > 0.02 )
- && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) {
- // the table says the present position is enough, but the brake has had its full fill
- // time since the handle last moved and the train is still not slowing down as asked:
- // believe the train rather than the table
- OK = BrakeLevelAdd( BrakingLevelIncrease );
- }
- else
- OK = false;
+ OK = increase_train_brake();
}
}
if( /*GBH mvOccupied->BrakeCtrlPos*/
@@ -5964,9 +5970,7 @@ TController::determine_consist_state() {
// once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor
// is still in the lap position while the brake pipe recharges
( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN
- if( false == heldforstart ) {
- Ready = false;
- }
+ Ready = heldforstart; // ready all the same only when the power goes on against the brake on purpose
}
// Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka...
if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy
@@ -8196,12 +8200,12 @@ bool TController::is_too_fast_uphill() const {
void TController::control_uphill_start() {
auto const velocity { DirectionalVel() };
- auto const uphill {
- ( BrakeSystem == TBrakeSystem::Pneumatic )
- && is_train()
- && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it
- && ( fAccGravity < -0.01 ) };
- if( false == uphill ) {
+ if( auto const uphill {
+ ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && is_train()
+ && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it
+ && ( fAccGravity < -0.01 ) };
+ false == uphill ) {
bUphillStart = false;
return;
}
@@ -8227,7 +8231,7 @@ void TController::control_uphill_start() {
cue_action( driver_hint::independentbrakerelease );
}
auto tractiveforce { 0.0 };
- for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
+ for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft );
}
auto const holdingforce { fMass * -fAccGravity };
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 846923df2..700b41f75 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -350,6 +350,7 @@ private:
void adjust_desired_speed_for_obstacles();
void adjust_desired_speed_for_limits();
void set_velocity_for_uncoupling();
+ bool increase_train_brake();
void hold_train_coming_to_stand_uphill();
void adjust_desired_speed_for_final_approach( double const Vel );
void adjust_desired_speed_for_target_speed( double const Range );
From 95ceb815d2f4e9d8b87ed97c0482250256ecf1c4 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 22:55:09 +0100
Subject: [PATCH 050/104] AI braking: the braking curve outside the final
approach in a method of its own
Takes care of the last two Sonar remarks, with no change in what the AI does:
- S134: the braking curve followed outside the final approach moves out of
adjust_desired_speed_for_target_speed() into
adjust_desired_speed_for_braking_curve(), with early returns.
- S6004: deltaAcc of increase_train_brake() is declared in the
init-statement of its if.
---
vehicle/Driver.cpp | 151 ++++++++++++++++++++++++---------------------
vehicle/Driver.h | 1 +
2 files changed, 81 insertions(+), 71 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5ac1ccd12..92a693532 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -2957,9 +2957,8 @@ TController::increase_train_brake() {
pos_corr += mvOccupied->Handle->GetCP()*0.2;
}
- double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
-
- if( deltaAcc > brake_increase_margin() )
+ if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
+ deltaAcc > brake_increase_margin() )
{
if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH
@@ -7628,6 +7627,83 @@ shaped_braking_demand(
return Gravity - high * fullbraking( Velocity );
}
+// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the
+// direction of travel
+void
+TController::adjust_desired_speed_for_braking_curve( double const Vel ) {
+
+ AccDesired = AccPreferred;
+ if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) {
+ return;
+ }
+ // allow to coast at reasonably low speed
+ auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) };
+ auto const slowdowndistance { (
+ mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance
+ brakingdistance :
+ std::max(
+ (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0,
+ brakingdistance ) ) };
+ if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) {
+ // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
+ return;
+ }
+ // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
+ auto const brakingpointoffset = (
+ ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
+ stopping_margin() : // the same stopping point as the final approach
+ VelNext * braking_distance_multiplier( static_cast( VelNext ) ) );
+ // a pneumatic brake acts on the state the train will be in once it has responded; while the
+ // train is still speeding up, plan the deceleration from there, so more is asked for at once
+ auto velocity { Vel };
+ auto distance { ActualProximityDist };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AbsAccS > 0.0 ) ) {
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ velocity = Vel + 3.6 * horizon * AbsAccS;
+ distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon );
+ }
+ auto const brakingroom {
+ std::max(
+ distance - brakingpointoffset,
+ std::min(
+ distance,
+ brakingpointoffset ) ) };
+ auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) {
+ // follow the shape of the consist brake force over speed rather than assume a constant
+ // deceleration, over the distance left once the brake has had time to fill (while the
+ // train is still speeding up, the prediction above has taken that off already)
+ auto room { brakingroom };
+ if( ( AbsAccS <= 0.0 )
+ && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind
+ room = std::max(
+ 0.5 * brakingroom,
+ brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
+ }
+ deceleration = shaped_braking_demand(
+ velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
+ { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } );
+ }
+ AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
+ if( Vel <= VelNext ) {
+ return;
+ }
+ if( deceleration < fAccGravity - 0.001 ) {
+ // no power while still above the speed being braked for
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( fAccGravity < -0.025 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( false == uphill_brake_committed( Vel ) )
+ && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) {
+ // uphill the gradient alone slows the train down more than it is asked to;
+ // keep it rolling at the present speed until that changes
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
+ }
+}
+
// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel
void
TController::adjust_desired_speed_for_final_approach( double const Vel ) {
@@ -7720,74 +7796,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else if (ActualProximityDist > fMinProximityDist) {
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
- // outside of max safe range
- AccDesired = AccPreferred;
- if( vel > min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) {
- // allow to coast at reasonably low speed
- auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) };
- auto const slowdowndistance { (
- mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance
- brakingdistance :
- std::max(
- (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0,
- brakingdistance ) ) };
- if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) >= ActualProximityDist - fMaxProximityDist ) {
- // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
- // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
- auto const brakingpointoffset = (
- ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
- stopping_margin() : // the same stopping point as the final approach
- VelNext * braking_distance_multiplier( static_cast( VelNext ) ) );
- // a pneumatic brake acts on the state the train will be in once it has responded; while the
- // train is still speeding up, plan the deceleration from there, so more is asked for at once
- auto velocity { vel };
- auto distance { ActualProximityDist };
- if( ( BrakeSystem == TBrakeSystem::Pneumatic )
- && ( AbsAccS > 0.0 ) ) {
- auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
- velocity = vel + 3.6 * horizon * AbsAccS;
- distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( vel + velocity ) * 0.5 / 3.6 * horizon );
- }
- auto const brakingroom {
- std::max(
- distance - brakingpointoffset,
- std::min(
- distance,
- brakingpointoffset ) ) };
- auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) };
- if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) {
- // follow the shape of the consist brake force over speed rather than assume a constant
- // deceleration, over the distance left once the brake has had time to fill (while the
- // train is still speeding up, the prediction above has taken that off already)
- auto room { brakingroom };
- if( ( AbsAccS <= 0.0 )
- && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind
- room = std::max(
- 0.5 * brakingroom,
- brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
- }
- deceleration = shaped_braking_demand(
- velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
- { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } );
- }
- AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
- if( vel > VelNext ) {
- if( deceleration < fAccGravity - 0.001 ) {
- // no power while still above the speed being braked for
- AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
- }
- else if( ( fAccGravity < -0.025 )
- && ( ( OrderCurrentGet() & Obey_train ) != 0 )
- && ( false == uphill_brake_committed( vel ) )
- && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > brakingpointoffset ) ) {
- // uphill the gradient alone slows the train down more than it is asked to;
- // keep it rolling at the present speed until that changes
- AccDesired = std::min( 0.0, AccPreferred );
- VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
- }
- }
- }
- }
+ adjust_desired_speed_for_braking_curve( vel );
AccDesired = std::min( AccDesired, AccPreferred );
}
else {
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 700b41f75..7698fedb7 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -353,6 +353,7 @@ private:
bool increase_train_brake();
void hold_train_coming_to_stand_uphill();
void adjust_desired_speed_for_final_approach( double const Vel );
+ void adjust_desired_speed_for_braking_curve( double const Vel );
void adjust_desired_speed_for_target_speed( double const Range );
void adjust_desired_speed_for_current_speed();
void adjust_desired_speed_for_braking_test();
From d3dd883700be5979ad2596b2f0f4c1d57931cdd6 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 23:13:00 +0100
Subject: [PATCH 051/104] feat: light programmer positions can switch the cab
light (eu07/maszyna#529)
An optional third column in the LightsList rows of the .fiz sets the cab
interior light when the driver moves the light preset selector to that
position: 0 off, 1 on, 3 on dimmed (bit 2 the dimmer). Rows without the
column, or with a negative value, leave the cab light to its own switch,
so the existing tables work as before; a stray note after the two light
columns (e.g. "38 38 / A") is not read as the flag.
The light follows the occupied cab, or all cabs of a JointCabs vehicle,
as with the interior light commands; the dimmer switch is moved along.
The lightsset custom position and the AI leave the cab light alone.
Covered by tests/unit/test_lights_preset_cablight.cpp.
(eu07/maszyna#529)
---
McZapkie/MOVER.h | 26 ++++++
McZapkie/Mover.cpp | 29 +++++++
tests/unit/test_lights_preset_cablight.cpp | 96 ++++++++++++++++++++++
vehicle/Train.cpp | 35 ++++++++
vehicle/Train.h | 2 +
5 files changed, 188 insertions(+)
create mode 100644 tests/unit/test_lights_preset_cablight.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 16bb207fa..3da9c8aa4 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -10,7 +10,9 @@ http://mozilla.org/MPL/2.0/.
#pragma once
//---------------------------------------------------------------------------
// Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji
+#include
#include