From 4575f61cc8d8919571a72c9023b7cd584c81cba1 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 15:52:38 +0200
Subject: [PATCH 01/90] 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 02/90] 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 03/90] 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 04/90] 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 05/90] 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 06/90] 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 07/90] 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 08/90] 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 09/90] 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 10/90] 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 11/90] 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 5fa03304eff805ca5bbe4dce8dfeebdd40c0250a Mon Sep 17 00:00:00 2001
From: maj00r
Date: Sat, 31 Oct 2026 00:45:46 +0100
Subject: [PATCH 12/90] fix(ui): keep panels in the main window when resizing
them at the screen edge
Pulling a panel's grip into the corner of the screen pushed it a couple of
pixels past the main window, and ImGui gave it an OS window of its own. Now
a panel only comes out when dragged with the cursor outside the main window.
A panel that stays in the main window needs its grips in reach, so a resize
stops at the edge, and a panel left past the edge or too big for the window
is moved back and shrunk to fit.
This is a new io.ConfigViewportsNoAutoDetach option in our copy of ImGui, so
it has to be carried over when ImGui gets updated. ImGui itself has no option
for this, as of 1.93.1.
---
application/uilayer.cpp | 2 ++
imgui/imgui.cpp | 58 +++++++++++++++++++++++++++++++++++++++--
imgui/imgui.h | 1 +
3 files changed, 59 insertions(+), 2 deletions(-)
diff --git a/application/uilayer.cpp b/application/uilayer.cpp
index 2dd771bdd..893b84e92 100644
--- a/application/uilayer.cpp
+++ b/application/uilayer.cpp
@@ -403,6 +403,8 @@ bool ui_layer::init(GLFWwindow *Window)
{
m_imguiio->ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
m_imguiio->ConfigViewportsNoTaskBarIcon = true;
+ // only dragging a panel with the cursor past the main window takes it out, not resizing it or placing it at the edge
+ m_imguiio->ConfigViewportsNoAutoDetach = true;
auto &platformio{ImGui::GetPlatformIO()};
imgui_create_window = platformio.Platform_CreateWindow;
platformio.Platform_CreateWindow = create_viewport_window;
diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp
index 573efe244..a9026b408 100644
--- a/imgui/imgui.cpp
+++ b/imgui/imgui.cpp
@@ -1294,6 +1294,7 @@ static void WindowSelectViewport(ImGuiWindow* window);
static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
+static bool WindowStaysInHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport); // MaSzyna addition
static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
static int FindPlatformMonitorForPos(const ImVec2& pos);
static int FindPlatformMonitorForRect(const ImRect& r);
@@ -1489,6 +1490,7 @@ ImGuiIO::ImGuiIO()
ConfigViewportsNoTaskBarIcon = false;
ConfigViewportsNoDecoration = true;
ConfigViewportsNoDefaultParent = false;
+ ConfigViewportsNoAutoDetach = false;
// Miscellaneous options
MouseDrawCursor = false;
@@ -6845,6 +6847,11 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
+ // MaSzyna addition: a resize stops at the edge of the host viewport, so the grips and borders can still be reached
+ ImRect resize_limit_rect(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
+ if (!window->ViewportOwned && WindowStaysInHostViewport(window, window->Viewport))
+ resize_limit_rect = window->Viewport->GetWorkRect();
+
// Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
// - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
// This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
@@ -6892,6 +6899,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
corner_target = ImClamp(corner_target, clamp_min, clamp_max);
+ corner_target = ImClamp(corner_target, resize_limit_rect.Min, resize_limit_rect.Max);
CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
}
@@ -6971,6 +6979,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
border_target = ImClamp(border_target, clamp_min, clamp_max);
+ border_target[axis] = ImClamp(border_target[axis], resize_limit_rect.Min[axis], resize_limit_rect.Max[axis]);
if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
{
ImGuiWindow* parent_window = window->ParentWindow;
@@ -7056,6 +7065,30 @@ static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_
window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
}
+// MaSzyna addition: see io.ConfigViewportsNoAutoDetach
+static inline bool IsWindowBeingMoved(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ return g.MovingWindow != NULL && g.MovingWindow->RootWindowDockTree == window->RootWindowDockTree;
+}
+
+// MaSzyna addition: a window left past the edge of its host viewport would have its grips and borders out of reach
+static inline void KeepWindowInsideRect(ImGuiWindow* window, const ImRect& rect)
+{
+ if (rect.GetWidth() <= 0.0f || rect.GetHeight() <= 0.0f)
+ return;
+
+ if (!(window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)))
+ {
+ const ImVec2 size_full = ImMin(window->SizeFull, rect.GetSize());
+ if (size_full.x != window->SizeFull.x || size_full.y != window->SizeFull.y)
+ ImGui::MarkIniSettingsDirty(window);
+ window->SizeFull = size_full;
+ window->Size = ImMin(window->Size, rect.GetSize());
+ }
+ window->Pos = ImMax(ImMin(window->Pos, rect.Max - window->Size), rect.Min);
+}
+
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
{
const ImGuiResizeBorderDef& def = resize_border_def[border_n];
@@ -7828,7 +7861,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Late create viewport if we don't fit within our current host viewport.
if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
- if (!window->Viewport->GetMainRect().Contains(window->Rect()))
+ if (!window->Viewport->GetMainRect().Contains(window->Rect()) && !WindowStaysInHostViewport(window, window->Viewport))
{
// This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
//ImGuiViewport* old_viewport = window->Viewport;
@@ -7878,6 +7911,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
ClampWindowPos(window, visibility_rect);
}
}
+
+ // MaSzyna addition: the host window of a floating dock node has its position set through the api, it's free to move all the same
+ if (!window->ViewportOwned && !IsWindowBeingMoved(window) && (!window_pos_set_by_api || (flags & ImGuiWindowFlags_DockNodeHost)) && WindowStaysInHostViewport(window, window->Viewport))
+ KeepWindowInsideRect(window, viewport_work_rect);
+
window->Pos = ImTrunc(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
@@ -15780,6 +15818,22 @@ static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
return false;
}
+// MaSzyna addition: see io.ConfigViewportsNoAutoDetach
+static bool ImGui::WindowStaysInHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
+{
+ ImGuiContext& g = *GImGui;
+ if (!g.IO.ConfigViewportsNoAutoDetach)
+ return false;
+
+ const ImGuiWindowFlags not_affected_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip;
+ if (window->Flags & not_affected_flags)
+ return false;
+
+ if (!IsWindowBeingMoved(window) || !IsMousePosValid())
+ return true;
+ return viewport->GetMainRect().Contains(g.IO.MousePos);
+}
+
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
{
ImGuiContext& g = *GImGui;
@@ -16323,7 +16377,7 @@ static void ImGui::WindowSelectViewport(ImGuiWindow* window)
// Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
if (window->Viewport == NULL)
if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
- window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
+ window->Viewport = WindowStaysInHostViewport(window, main_viewport) ? main_viewport : AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
// Mark window as allowed to protrude outside of its viewport and into the current monitor
if (!lock_viewport)
diff --git a/imgui/imgui.h b/imgui/imgui.h
index bafe97ff8..6bbc42dec 100644
--- a/imgui/imgui.h
+++ b/imgui/imgui.h
@@ -2360,6 +2360,7 @@ struct ImGuiIO
bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it.
bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size).
bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows.
+ bool ConfigViewportsNoAutoDetach; // = false // MaSzyna addition: a floating window stays inside its host viewport: a resize stops at its edge, and a window left past it, or too big for it, is moved and shrunk to fit. It gets a viewport of its own only when dragged with the mouse cursor past the host viewport. Popups and tooltips are not affected.
// Miscellaneous options
// (you can visualize and interact with all options in 'Demo->Configuration')
From 9364b03e1ad9d9711942864c4d5ab17a00f487d3 Mon Sep 17 00:00:00 2001
From: maj00r
Date: Sat, 31 Oct 2026 20:17:47 +0100
Subject: [PATCH 13/90] fix(track): what Sonar reports on the unevenness
The blockers are in the EP brake of a vehicle, older than this work: its
arrays made with new[] are vectors now, which also removes the deletes.
- The caches of the unevenness of a track are no longer mutable: what fills
them isn't const any more.
- TSegment gets back to RaPositionGet in one piece, with what the path has
to do with the others in one struct.
- Less nesting in the group of switches and in the fields of the editor,
nested conditionals written out, and the attribute is read from a
string_view. A test no longer counts in floating point.
No change in behaviour.
---
application/editormodetrack.cpp | 33 ++++-----
tests/unit/test_track_uneven.cpp | 33 ++++++---
vehicle/DynObj.cpp | 73 +++++++++----------
vehicle/DynObj.h | 2 +-
world/Segment.cpp | 77 +++++++++-----------
world/Segment.h | 29 ++++----
world/Track.h | 21 +++---
world/TrackUneven.cpp | 117 ++++++++++++++++++-------------
world/TrackUneven.h | 45 +++++++-----
9 files changed, 223 insertions(+), 207 deletions(-)
diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp
index 49059c213..0ae732d86 100644
--- a/application/editormodetrack.cpp
+++ b/application/editormodetrack.cpp
@@ -1166,26 +1166,23 @@ void editor_mode::render_path_parameters(TTrack &Track)
track->m_uneven.value = std::clamp(track->m_uneven.value, 0.f, track_uneven::most);
item_tooltip("Peak deviation of a rail on a 10 m chord. Id-14 limits: 6 mm at 160 km/h, 10 at 120, 18 at 80, 35 at 40.\nWith a sound distance set, the rails also dip at the joints. Joined switches use the lowest of their values");
finish_edit(rebuild::parameters);
- struct component
- {
- char const *label;
- float *value;
- bool shown;
- };
- auto const plain{track->eType == tt_Normal};
- for (auto const &part : {component{"Up and down (mm)", &track->m_uneven.up, true},
- component{"Sideways (mm)", &track->m_uneven.side, true},
- component{"Cross level (mm)", &track->m_uneven.cross, plain},
- component{"Diverging path (mm)", &track->m_uneven.branch, !plain},
- component{"Diverging, up and down (mm)", &track->m_uneven.branchup, !plain},
- component{"Diverging, sideways (mm)", &track->m_uneven.branchside, !plain}})
- {
- if (false == part.shown)
- continue;
- if (ImGui::InputFloat(STR_C(part.label), part.value, 0.0f, 0.0f, "%.1f"))
- *part.value = *part.value < 0.f ? -1.f : std::min(*part.value, track_uneven::most);
+ auto const component = [&](char const *Label, float &Value) {
+ if (ImGui::InputFloat(STR_C(Label), &Value, 0.0f, 0.0f, "%.1f"))
+ Value = Value < 0.f ? -1.f : std::min(Value, track_uneven::most);
item_tooltip("Set apart from the unevenness, mm. Negative: the unevenness");
finish_edit(rebuild::parameters);
+ };
+ component("Up and down (mm)", track->m_uneven.up);
+ component("Sideways (mm)", track->m_uneven.side);
+ if (track->eType == tt_Normal)
+ {
+ component("Cross level (mm)", track->m_uneven.cross);
+ }
+ else
+ {
+ component("Diverging path (mm)", track->m_uneven.branch);
+ component("Diverging, up and down (mm)", track->m_uneven.branchup);
+ component("Diverging, sideways (mm)", track->m_uneven.branchside);
}
}
if (track->eType == tt_Normal && (track->iCategoryFlag & 15) == 1)
diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp
index 65b7da6e1..06f4663b0 100644
--- a/tests/unit/test_track_uneven.cpp
+++ b/tests/unit/test_track_uneven.cpp
@@ -2,6 +2,8 @@
#include "doctest.h"
#include "world/TrackUneven.h"
+#include
+#include
#include
#include
@@ -12,19 +14,20 @@ double deviation(std::vector const &Values)
auto mean{0.0};
for (auto const value : Values)
mean += value;
- mean /= Values.size();
+ auto const count{static_cast(Values.size())};
+ mean /= count;
auto sum{0.0};
for (auto const value : Values)
sum += (value - mean) * (value - mean);
- return std::sqrt(sum / Values.size());
+ return std::sqrt(sum / count);
}
double peak(std::vector Values)
{
for (auto &value : Values)
value = std::abs(value);
- std::sort(Values.begin(), Values.end());
- return Values[static_cast(0.999 * Values.size())];
+ std::ranges::sort(Values);
+ return Values[Values.size() * 999 / 1000];
}
void add_chord(std::vector &Output, std::vector const &Line, int const Half)
@@ -44,14 +47,22 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value")
int const steps{4000};
int const base{10}; // 5 m
int const lines{36};
- double vertical{0.0}, horizontal{0.0}, twist{0.0}, wander{0.0}, level{0.0}, j{0.0}, away{0.0};
+ double vertical{0.0};
+ double horizontal{0.0};
+ double twist{0.0};
+ double wander{0.0};
+ double level{0.0};
+ double j{0.0};
+ double away{0.0};
for (int line = 0; line < lines; ++line)
{
auto const heading{glm::pi() * (line + 0.37) / lines};
glm::dvec3 const start{7919.0 * std::sin(line * 1.7), 0.0, 6577.0 * std::cos(line * 2.3)};
glm::dvec3 const along{std::cos(heading), 0.0, std::sin(heading)};
glm::dvec3 const across{-along.z, 0.0, along.x};
- std::vector up[2], side[2], middle;
+ std::array, 2> up;
+ std::array, 2> side;
+ std::vector middle;
for (int i = 0; i < steps; ++i)
{
auto const point{start + along * (i * step)};
@@ -64,7 +75,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value")
}
middle.push_back(track_uneven::field(point).y * amplitude);
}
- std::vector verticals, horizontals, twists, gauges, levels;
+ std::vector verticals;
+ std::vector horizontals;
+ std::vector twists;
+ std::vector gauges;
+ std::vector levels;
for (int rail = 0; rail < 2; ++rail)
{
add_chord(verticals, up[rail], base);
@@ -269,9 +284,9 @@ TEST_CASE("uneven track: the value along a track meets its neighbours exactly")
CHECK(track_uneven::along(18.0, 35.0, 35.0, 0.25, 0.5) == doctest::Approx(35.0).epsilon(0.01));
// no jump anywhere
auto last{track_uneven::along(18.0, 35.0, 0.0, 0.0, length)};
- for (auto distance{0.25}; distance <= length; distance += 0.25)
+ for (int step = 1; step <= 2000; ++step)
{
- auto const value{track_uneven::along(18.0, 35.0, 0.0, distance, length)};
+ auto const value{track_uneven::along(18.0, 35.0, 0.0, step * 0.25, length)};
REQUIRE(std::abs(value - last) < 0.5);
last = value;
}
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index ac87f395c..305e12020 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -3382,14 +3382,12 @@ bool TDynamicObject::Update(double dt, double dt1)
FzadED = 0; //pętla bezpieczeństwa - bez ED
auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor;
//np = 0;
- // BUG: likely memory leak, allocation per inner loop, deleted only once outside
- // TODO: sort this shit out
- bool* PrzekrF = new bool[np];
+ std::vector PrzekrF( np );
float nPrzekrF = 0;
bool test = true;
- float* FzED = new float[np];
- float* FzEP = new float[np];
- float* FmaxEP = new float[np];
+ std::vector FzED( np );
+ std::vector FzEP( np );
+ std::vector FmaxEP( np );
// 3. ustaw pojazdom sile hamowania ED
// - proporcjonalnie do mozliwosci
@@ -3548,11 +3546,6 @@ bool TDynamicObject::Update(double dt, double dt1)
}
- delete[] PrzekrF;
- delete[] FzED;
- delete[] FzEP;
- delete[] FmaxEP;
-
MED_oldFED = FzadED;
}
@@ -3661,33 +3654,32 @@ bool TDynamicObject::Update(double dt, double dt1)
1 :
ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) };
for( auto &axle : m_axlesounds ) {
- if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) ) {
- if( MoverParameters->Vel > 0.1 ) {
- // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range
- auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0;
- axle.clatter
- .pitch( frequency )
- .gain( volume )
- .play();
- // crude bump simulation, drop down on even axles, move back up on
- // the odd ones
- // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) *
- double const headroom = std::clamp(
- MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ),
- 0.0, MoverParameters->Vmax );
- double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f );
- if (MyTrack->eType == tt_Normal)
- {
- MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 );
- }
- else if (MyTrack->eType == tt_Switch)
- {
- double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1);
- MoverParameters->AccS += accHorizontal;
- MoverParameters->AccN += accHorizontal;
- MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 );
- }
- }
+ if( axle_passed_joint( axle, dDOMoveLen, directioninconsist )
+ && MoverParameters->Vel > 0.1 ) {
+ // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range
+ auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0;
+ axle.clatter
+ .pitch( frequency )
+ .gain( volume )
+ .play();
+ // crude bump simulation, drop down on even axles, move back up on
+ // the odd ones
+ // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) *
+ double const headroom = std::clamp(
+ MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ),
+ 0.0, MoverParameters->Vmax );
+ double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f );
+ if (MyTrack->eType == tt_Normal)
+ {
+ MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 );
+ }
+ else if (MyTrack->eType == tt_Switch)
+ {
+ double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1);
+ MoverParameters->AccS += accHorizontal;
+ MoverParameters->AccN += accHorizontal;
+ MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 );
+ }
}
++axleindex;
}
@@ -8072,12 +8064,11 @@ TDynamicObject::update_shake( double const Timedelta ) {
}
bool
-TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) {
+TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const {
// by the outer axle on its side of the vehicle: the two can be on different tracks
auto const &outer { Axle.offset >= 0.0 ? Axle0 : Axle1 };
- auto const railphase { outer.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) };
- if( railphase >= 0.0 ) {
+ if( auto const railphase { outer.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) }; railphase >= 0.0 ) {
// the rails under the axle, which aren't always those under the track the vehicle is on
auto const passed { Axle.atjoints && std::abs( railphase - Axle.distance ) > 0.5 * outer.GetTrack()->fSoundDistance };
Axle.distance = railphase;
diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h
index b903f0874..4fee9778e 100644
--- a/vehicle/DynObj.h
+++ b/vehicle/DynObj.h
@@ -405,7 +405,7 @@ private:
bool atjoints { false }; // distance comes from TTrack::rail_phase
};
// whether the axle has just passed a rail joint. On a track with dipping joints it goes by them, elsewhere the axle counts a rail off itself
- bool axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction );
+ bool axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const;
struct powertrain_sounds {
sound_source inverter { sound_placement::engine };
diff --git a/world/Segment.cpp b/world/Segment.cpp
index 9c0e1077e..1aff4ae42 100644
--- a/world/Segment.cpp
+++ b/world/Segment.cpp
@@ -69,10 +69,8 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N
// poprawienie przechyłki
fRoll1 = static_cast(glm::radians(fNewRoll1)); // Ra: przeliczone jest bardziej przydatne do obliczeń
fRoll2 = static_cast(glm::radians(fNewRoll2));
- m_designrolls[ 0 ] = fRoll1;
- m_designrolls[ 1 ] = fRoll2;
- m_joints[ 0 ].reset();
- m_joints[ 1 ].reset();
+ m_setting.designrolls = { fRoll1, fRoll2 };
+ m_setting.joints = {};
bCurve = bIsCurve;
if (Global.bRollFix)
{ // Ra: poprawianie przechyłki
@@ -122,7 +120,7 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N
fStoop = std::atan2(Point2.y - Point1.y, fLength); // pochylenie toru prostego, żeby nie liczyć wielokrotnie
fStep = fNewStep;
- if( m_uneven && pOwner->eType != tt_Switch ) {
+ if( m_setting.uneven && pOwner->eType != tt_Switch ) {
// dense enough for the waves; a switch keeps its division, the blades depend on it
fStep = std::min( fStep, 2.0 );
}
@@ -373,21 +371,6 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const
};
*/
-void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const {
- design_position( fDistance, position, rotation );
- if( false == m_uneven ) {
- return;
- }
- // direction and slope stay as designed: the physics takes the curve radius and the grade from them
- auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) };
- glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) };
- auto const amount { pOwner->uneven_at( fDistance, m_path ) };
- rotation.x += static_cast( track_uneven::stray_per_mm * (
- amount.up * track_uneven::roll( position, across, gauge )
- + amount.cross * track_uneven::level( position, across ) / gauge ) );
- position += track_uneven::across_only( stray( position, amount, fDistance ), across );
-}
-
glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const {
auto const field { track_uneven::field( Point ) };
glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side };
@@ -397,30 +380,25 @@ glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const
}
glm::dvec3 TSegment::uneven_bend( double const Distance ) const {
- if( false == m_uneven ) {
+ if( false == m_setting.uneven ) {
return glm::dvec3 { 0.0 };
}
// over about a bogie
auto const reach { 1.5 };
- auto const strayed = [&]( double const At ) {
- return stray( point_extended( At ), pOwner->uneven_at( At, m_path ), At ); };
+ auto const strayed = [ this ]( double const At ) {
+ // past the ends of the path straight on: the polynomial would run off on a short curved one
+ auto const on { std::clamp( At, 0.0, fLength ) };
+ auto const t { FastGetTFromS( on ) };
+ auto point { FastGetPoint( t ) };
+ if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) {
+ point += direction * ( ( At - on ) / glm::length( direction ) );
+ }
+ return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); };
return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach );
}
-glm::dvec3 TSegment::point_extended( double const Distance ) const {
- auto const on { std::clamp( Distance, 0.0, fLength ) };
- auto const t { FastGetTFromS( on ) };
- auto const point { FastGetPoint( t ) };
- if( on == Distance ) {
- return point;
- }
- auto const direction { FastGetDirection( t, 0.1 / fLength ) };
- auto const size { glm::length( direction ) };
- return size > 0.0 ? point + direction * ( ( Distance - on ) / size ) : point;
-}
-
void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const {
- if( false == m_uneven ) {
+ if( false == m_setting.uneven ) {
return;
}
// the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays
@@ -430,12 +408,12 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi
if( share <= 0.0 ) {
return;
}
- auto const amount { pOwner->uneven_at( Distance, m_path ) };
+ auto const amount { pOwner->uneven_at( Distance, m_setting.path ) };
Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge );
Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) };
}
-void TSegment::design_position(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const {
+void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const {
if (bCurve) {
// można by wprowadzić uproszczony wzór dla okręgów płaskich
auto const t = FastGetTFromS(fDistance); // aproksymacja dystansu na krzywej Beziera na parametr (t)
@@ -458,6 +436,17 @@ void TSegment::design_position(double const fDistance, glm::dvec3 &position, glm
rotation.y = static_cast(fStoop); // pochylenie toru prostego
rotation.z = static_cast(fDirection); // kierunek toru w planie
}
+ if( false == m_setting.uneven ) {
+ return;
+ }
+ // direction and slope stay as designed: the physics takes the curve radius and the grade from them
+ auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) };
+ glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) };
+ auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) };
+ rotation.x += static_cast( track_uneven::stray_per_mm * (
+ amount.up * track_uneven::roll( position, across, gauge )
+ + amount.cross * track_uneven::level( position, across ) / gauge ) );
+ position += track_uneven::across_only( stray( position, amount, fDistance ), across );
};
void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const {
@@ -523,9 +512,9 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin,
parallel1 = glm::vec3{ glm::dvec3{ FastGetPoint_1() - FastGetPoint_0() } };
}
parallel1 = glm::normalize( parallel1 );
- if( iSkip == 0 && m_joints[ 0 ] ) {
- pos1 = glm::vec3{ m_joints[ 0 ]->first - Origin };
- parallel1 = glm::vec3{ m_joints[ 0 ]->second };
+ if( iSkip == 0 && m_setting.joints[ 0 ] ) {
+ pos1 = glm::vec3{ m_setting.joints[ 0 ]->first - Origin };
+ parallel1 = glm::vec3{ m_setting.joints[ 0 ]->second };
}
if( iEnd == 0 )
iEnd = iSegCount;
@@ -572,9 +561,9 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin,
parallel2 = glm::vec3{ glm::dvec3{ FastGetPoint_1() - FastGetPoint_0() } };
}
parallel2 = glm::normalize( parallel2 );
- if( i == iSegCount && m_joints[ 1 ] ) {
- pos2 = glm::vec3{ m_joints[ 1 ]->first - Origin };
- parallel2 = glm::vec3{ m_joints[ 1 ]->second };
+ if( i == iSegCount && m_setting.joints[ 1 ] ) {
+ pos2 = glm::vec3{ m_setting.joints[ 1 ]->first - Origin };
+ parallel2 = glm::vec3{ m_setting.joints[ 1 ]->second };
}
// TODO: refactor the loop, there's no need to calculate starting points for each segment when we can copy the end points of the previous one
diff --git a/world/Segment.h b/world/Segment.h
index 75e070152..099480e36 100644
--- a/world/Segment.h
+++ b/world/Segment.h
@@ -9,7 +9,9 @@ http://mozilla.org/MPL/2.0/.
#pragma once
+#include
#include
+#include
#include "utilities/Classes.h"
#include "rendering/geometrybank.h"
@@ -50,11 +52,14 @@ class TSegment
glm::dvec3 Point2;
float fRoll1 { 0.f };
float fRoll2 { 0.f }; // przechyłka na końcach
- float m_designrolls[ 2 ] { 0.f, 0.f }; // as entered; the two above can differ at a joint
- bool m_uneven { false }; // see TrackUneven.h
- int m_path { 0 }; // which path of a switch
- // where the path meets the next one: the middle of their ends and their common vector across
- std::optional> m_joints[ 2 ];
+ // how the path sits among the others
+ struct setting {
+ std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint
+ bool uneven { false }; // see TrackUneven.h
+ int path { 0 }; // which path of a switch
+ // where the path meets the next one: the middle of their ends and their common vector across
+ std::array>, 2> joints;
+ } m_setting;
double fLength { -1.0 }; // długość policzona
std::vector fTsBuffer; // wartości parametru krzywej t dla równych odcinków s
std::vector fTsSlope; // nachylenie dt/du (= dt/ds * fStep) w tych samych punktach
@@ -79,9 +84,6 @@ class TSegment
void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const;
// displacement of a point by the unevenness, at a distance along the path
glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const;
- // a point of the path at a distance, past its ends straight on: the polynomial would run off on a short curved path
- glm::dvec3 point_extended( double const Distance ) const;
- void design_position( double const fDistance, glm::dvec3 &position, glm::vec3 &rotation ) const;
public:
bool bCurve = false;
@@ -125,20 +127,17 @@ public:
// call before Init, it sets the density of the geometry
void
set_uneven( bool const Uneven, int const Path = 0 ) {
- m_uneven = Uneven;
- m_path = Path; }
- glm::dvec3
- end_point( int const End ) const {
- return End == 0 ? Point1 : Point2; }
+ m_setting.uneven = Uneven;
+ m_setting.path = Path; }
// a point of the path and the unit vector across it in the plan
void
plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const;
float
design_roll( int const End ) const {
- return m_designrolls[ End ]; }
+ return m_setting.designrolls[ End ]; }
void
set_joint( int const End, std::optional> const &Joint, float const Roll ) {
- m_joints[ End ] = Joint;
+ m_setting.joints[ End ] = Joint;
( End == 0 ? fRoll1 : fRoll2 ) = Roll; }
// second derivative of the displacement along the path; times speed squared: acceleration of an axle
glm::dvec3
diff --git a/world/Track.h b/world/Track.h
index f5bb8c1b6..72cbd8847 100644
--- a/world/Track.h
+++ b/world/Track.h
@@ -349,15 +349,15 @@ public:
track_uneven::amounts uneven_declared( int const Path = 0 ) const;
bool is_uneven() const;
// the unevenness at a distance along a path, meeting the tracks joined at its ends
- track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ) const;
+ track_uneven::amounts uneven_at( double const Distance, int const Path = 0 );
// how much of the displacement a point of the profile at the depth takes
double uneven_bed_share( double const Depth ) const;
// closes the gaps and steps of cant between the ends of joined paths
void share_joints();
double joint_depth() const; // mm
- double joint_dip( double const Distance ) const; // m
+ double joint_dip( double const Distance ); // m
// distance from the rail joint behind; negative: the track has no joints that dip
- double rail_phase( double const Distance ) const;
+ double rail_phase( double const Distance );
void ConnectionsLog();
bool DoubleSlip() const;
static void fetch_default_profiles();
@@ -395,8 +395,8 @@ private:
double way { 1.0 }; // direction of the path along the run
int stamp { -1 };
};
- void settle_rail_run() const;
- mutable rail_run m_railrun;
+ void settle_rail_run();
+ rail_run m_railrun;
// the value along each path of a switch: the lowest of that path in the switches joined, 0 next to a track with none.
// And at the ends of the paths, by what meets there: the other path at the common end, the path of a switch joined
struct switch_stray {
@@ -404,15 +404,16 @@ private:
std::array, 2> ends;
int stamp { -1 };
};
- mutable switch_stray m_switchstray;
- switch_stray const &switch_uneven() const;
- void settle_switch_stray() const;
+ switch_stray m_switchstray;
+ switch_stray const &switch_uneven();
+ void settle_switch_stray();
+ void settle_switch_ends();
// the lowest value of the paths ending at the point
track_uneven::amounts switch_paths_at( glm::dvec3 const &Point ) const;
// what a plain track comes to at its end, where it meets the other one
- track_uneven::amounts uneven_met( TTrack const *Other, glm::dvec3 const &Point ) const;
+ track_uneven::amounts uneven_met( TTrack *Other, glm::dvec3 const &Point );
// the value of a switch where a track joined to it meets it
- track_uneven::amounts switch_uneven_at( glm::dvec3 const &Point ) const;
+ track_uneven::amounts switch_uneven_at( glm::dvec3 const &Point );
static int s_layoutstamp; // bumped when tracks are joined or changed, invalidates the two above
void create_road_profile( gfx::vertex_array &Output, bool const Forcetransition = false );
void create_road_side_profile( gfx::vertex_array &Right, gfx::vertex_array &Left, gfx::vertex_array const &Road, bool const Forcetransition = false );
diff --git a/world/TrackUneven.cpp b/world/TrackUneven.cpp
index 152449ad2..78505ac3a 100644
--- a/world/TrackUneven.cpp
+++ b/world/TrackUneven.cpp
@@ -24,42 +24,55 @@ bool is_switch( TTrack const *Track ) {
return Track != nullptr && Track->eType == tt_Switch && Track->SwitchExtension;
}
-std::array joined_to_switch( TTrack const &Switch ) {
+glm::dvec3 end_point( TSegment const &Segment, int const End ) {
+
+ return End == 0 ? Segment.FastGetPoint_0() : Segment.FastGetPoint_1();
+}
+
+std::array joined_to_switch( TTrack const &Switch ) {
auto const &extension { *Switch.SwitchExtension };
return { extension.pPrevs[ 0 ], extension.pPrevs[ 1 ], extension.pNexts[ 0 ], extension.pNexts[ 1 ] };
}
// the switch and the switches joined directly to it, and to those
-std::vector switch_group( TTrack const &Switch ) {
+std::vector switch_group( TTrack &Switch ) {
- std::vector group { &Switch };
- for( std::size_t index = 0; index < group.size(); ++index ) {
- for( auto const *other : joined_to_switch( *group[ index ] ) ) {
- if( is_switch( other ) && std::find( group.begin(), group.end(), other ) == group.end() ) {
+ std::vector group { &Switch };
+ std::vector pending { &Switch };
+ while( false == pending.empty() ) {
+ auto const *track { pending.back() };
+ pending.pop_back();
+ for( auto *other : joined_to_switch( *track ) ) {
+ if( is_switch( other ) && std::ranges::find( group, other ) == group.end() ) {
group.push_back( other );
+ pending.push_back( other );
}
}
}
return group;
}
+// a plain track with none of a component keeps the switch to its design in it, any other comes to the value of the switch
+void keep_to_plain_track( std::array &Values, TTrack const &Plain ) {
+
+ auto const theirs { Plain.uneven_declared() };
+ for( auto &path : Values ) {
+ if( theirs.up <= 0.0 ) { path.up = 0.0; }
+ if( theirs.side <= 0.0 ) { path.side = 0.0; }
+ }
+}
+
// the value along each path: the lowest of that path in the group, 0 in a component that a plain track joined has none of
-std::array group_path_values( std::vector const &Group ) {
+std::array group_path_values( std::vector const &Group ) {
std::array values { Group.front()->uneven_declared( 0 ), Group.front()->uneven_declared( 1 ) };
for( auto const *track : Group ) {
values[ 0 ] = track_uneven::least( values[ 0 ], track->uneven_declared( 0 ) );
values[ 1 ] = track_uneven::least( values[ 1 ], track->uneven_declared( 1 ) );
for( auto const *other : joined_to_switch( *track ) ) {
- if( other == nullptr || is_switch( other ) ) {
- continue;
- }
- // any other comes to the value of the switch
- auto const theirs { other->uneven_declared() };
- for( auto &path : values ) {
- if( theirs.up <= 0.0 ) { path.up = 0.0; }
- if( theirs.side <= 0.0 ) { path.side = 0.0; }
+ if( other != nullptr && false == is_switch( other ) ) {
+ keep_to_plain_track( values, *other );
}
}
}
@@ -74,7 +87,7 @@ track_uneven::amounts least_at_ends( TTrack const &Switch, glm::dvec3 const &Poi
track_uneven::amounts result { track_uneven::most, track_uneven::most, track_uneven::most };
for( int path = 0; path < 2; ++path ) {
for( int end = 0; end < 2; ++end ) {
- if( glm::length( Switch.path_segment( path )->end_point( end ) - Point ) < switch_end_reach ) {
+ if( glm::length( end_point( *Switch.path_segment( path ), end ) - Point ) < switch_end_reach ) {
result = track_uneven::least( result, Value( path, end ) );
found = true;
}
@@ -165,16 +178,16 @@ double TTrack::uneven_bed_share( double const Depth ) const {
return track_uneven::bed_share( Depth, std::abs( track_rail_profile( m_profile1.second ).front().position.y ), fTexHeight1 );
}
-track_uneven::amounts TTrack::uneven_at( double const Distance, int const Path ) const {
+track_uneven::amounts TTrack::uneven_at( double const Distance, int const Path ) {
if( eType == tt_Switch ) {
auto const &stray { switch_uneven() };
return track_uneven::along( stray.paths[ Path ], stray.ends[ Path ][ 0 ], stray.ends[ Path ][ 1 ], Distance, path_segment( Path )->GetLength() );
}
- return track_uneven::along( uneven_declared(), uneven_met( trPrev, Segment->end_point( 0 ) ), uneven_met( trNext, Segment->end_point( 1 ) ), Distance, Length() );
+ return track_uneven::along( uneven_declared(), uneven_met( trPrev, end_point( *Segment, 0 ) ), uneven_met( trNext, end_point( *Segment, 1 ) ), Distance, Length() );
}
-track_uneven::amounts TTrack::uneven_met( TTrack const *Other, glm::dvec3 const &Point ) const {
+track_uneven::amounts TTrack::uneven_met( TTrack *Other, glm::dvec3 const &Point ) {
if( Other == nullptr ) {
return {};
@@ -182,7 +195,7 @@ track_uneven::amounts TTrack::uneven_met( TTrack const *Other, glm::dvec3 const
return Other->eType == tt_Switch ? Other->switch_uneven_at( Point ) : track_uneven::least( uneven_declared(), Other->uneven_declared() );
}
-TTrack::switch_stray const &TTrack::switch_uneven() const {
+TTrack::switch_stray const &TTrack::switch_uneven() {
if( m_switchstray.stamp != s_layoutstamp ) {
settle_switch_stray();
@@ -190,26 +203,30 @@ TTrack::switch_stray const &TTrack::switch_uneven() const {
return m_switchstray;
}
-void TTrack::settle_switch_stray() const {
+void TTrack::settle_switch_stray() {
auto const group { switch_group( *this ) };
auto const values { group_path_values( group ) };
- for( auto const *track : group ) {
+ for( auto *track : group ) {
track->m_switchstray.paths = values;
track->m_switchstray.stamp = s_layoutstamp;
}
- // at the ends of the paths, with the paths known in all of the group
- for( auto const *track : group ) {
- for( int path = 0; path < 2; ++path ) {
- for( int end = 0; end < 2; ++end ) {
- auto const point { track->path_segment( path )->end_point( end ) };
- auto value { track->switch_paths_at( point ) };
- auto const *other { track->path_neighbour( path, end ) };
- if( is_switch( other ) ) {
- value = track_uneven::least( value, other->switch_paths_at( point ) );
- }
- track->m_switchstray.ends[ path ][ end ] = value;
+ // with the paths known in all of the group
+ for( auto *track : group ) {
+ track->settle_switch_ends();
+ }
+}
+
+void TTrack::settle_switch_ends() {
+
+ for( int path = 0; path < 2; ++path ) {
+ for( int end = 0; end < 2; ++end ) {
+ auto const point { end_point( *path_segment( path ), end ) };
+ auto value { switch_paths_at( point ) };
+ if( auto const *other { path_neighbour( path, end ) }; is_switch( other ) ) {
+ value = track_uneven::least( value, other->switch_paths_at( point ) );
}
+ m_switchstray.ends[ path ][ end ] = value;
}
}
}
@@ -217,13 +234,13 @@ void TTrack::settle_switch_stray() const {
track_uneven::amounts TTrack::switch_paths_at( glm::dvec3 const &Point ) const {
auto const &paths { m_switchstray.paths };
- return least_at_ends( *this, Point, track_uneven::least( paths[ 0 ], paths[ 1 ] ), [ & ]( int const Path, int ) { return paths[ Path ]; } );
+ return least_at_ends( *this, Point, track_uneven::least( paths[ 0 ], paths[ 1 ] ), [ &paths ]( int const Path, int ) { return paths[ Path ]; } );
}
-track_uneven::amounts TTrack::switch_uneven_at( glm::dvec3 const &Point ) const {
+track_uneven::amounts TTrack::switch_uneven_at( glm::dvec3 const &Point ) {
auto const &stray { switch_uneven() };
- return least_at_ends( *this, Point, track_uneven::least( stray.paths[ 0 ], stray.paths[ 1 ] ), [ & ]( int const Path, int const End ) { return stray.ends[ Path ][ End ]; } );
+ return least_at_ends( *this, Point, track_uneven::least( stray.paths[ 0 ], stray.paths[ 1 ] ), [ &stray ]( int const Path, int const End ) { return stray.ends[ Path ][ End ]; } );
}
double TTrack::joint_depth() const {
@@ -234,7 +251,7 @@ double TTrack::joint_depth() const {
return ( m_uneven.dip >= 0.f ? m_uneven.dip : track_uneven::dip_share * uneven_declared().up );
}
-double TTrack::joint_dip( double const Distance ) const {
+double TTrack::joint_dip( double const Distance ) {
auto const phase { rail_phase( Distance ) };
if( phase < 0.0 ) {
@@ -245,12 +262,12 @@ double TTrack::joint_dip( double const Distance ) const {
return 0.0;
}
auto const depth { joint_depth() };
- auto const atend = [&]( TTrack const *Other ) {
+ auto const atend = [ this, depth ]( TTrack const *Other ) {
return ( Other == nullptr || Other->fSoundDistance != fSoundDistance ? 0.0 : std::min( depth, Other->joint_depth() ) ); };
return 0.001 * track_uneven::dip( fromjoint ) * track_uneven::along( depth, atend( trPrev ), atend( trNext ), Distance, Length() );
}
-double TTrack::rail_phase( double const Distance ) const {
+double TTrack::rail_phase( double const Distance ) {
if( joint_depth() <= 0.0 || fSoundDistance <= 2.0 * track_uneven::dip_reach ) {
return -1.0;
@@ -261,22 +278,22 @@ double TTrack::rail_phase( double const Distance ) const {
return track_uneven::rail_phase( m_railrun.origin + m_railrun.way * Distance, fSoundDistance );
}
-void TTrack::settle_rail_run() const {
+void TTrack::settle_rail_run() {
// the next track of the run past an end of a track, and which of its ends is joined there
- auto const onward = []( TTrack const &Track, int const End, int &Joined ) -> TTrack const * {
- auto const *other { End == 0 ? Track.trPrev : Track.trNext };
+ auto const onward = []( TTrack const &Track, int const End, int &Joined ) -> TTrack * {
+ auto *other { End == 0 ? Track.trPrev : Track.trNext };
if( other == nullptr || other == &Track || other->joint_depth() <= 0.0 || other->fSoundDistance != Track.fSoundDistance ) {
return nullptr;
}
Joined = ( End == 0 ? Track.iPrevDirection : Track.iNextDirection ) & 1;
return other; };
// walks from this track to an end of the run
- auto const walk = [&]( int &End ) {
- auto const *track { this };
+ auto const walk = [ this, &onward ]( int &End ) {
+ auto *track { this };
int joined { 0 };
for( int step = 0; step < 1000000; ++step ) {
- auto const *next { onward( *track, End, joined ) };
+ auto *next { onward( *track, End, joined ) };
if( next == nullptr || next == this ) {
break;
}
@@ -285,15 +302,14 @@ void TTrack::settle_rail_run() const {
}
return track; };
auto const place = []( TTrack const &Track, int const End ) {
- auto const point { Track.Segment->end_point( End ) };
+ auto const point { end_point( *Track.Segment, End ) };
return std::make_pair( point.x, point.z ); };
// start at the end with the lesser coordinates, to get the same joints from any track of the run
int end { 0 };
int otherend { 1 };
- auto const *track { walk( end ) };
- auto const *other { walk( otherend ) };
- if( place( *other, otherend ) < place( *track, end ) ) {
+ auto *track { walk( end ) };
+ if( auto *other { walk( otherend ) }; place( *other, otherend ) < place( *track, end ) ) {
track = other;
end = otherend;
}
@@ -327,7 +343,8 @@ void TTrack::share_joints() {
}
}
if( eType != tt_Switch && Segment && ( iCategoryFlag & 1 ) ) {
- float roll1, roll2;
+ float roll1 { 0.f };
+ float roll2 { 0.f };
Segment->GetRolls( roll1, roll2 );
if( roll1 != 0.f || roll2 != 0.f ) {
iTrapezoid |= 1;
diff --git a/world/TrackUneven.h b/world/TrackUneven.h
index 624e6db16..2c32ad660 100644
--- a/world/TrackUneven.h
+++ b/world/TrackUneven.h
@@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/.
#include
#include
#include
+#include
#include
#include
@@ -51,18 +52,20 @@ struct wave {
// the numbers of an entry like "uneven 14;35", negative where left out
template
-std::array read_fields( std::string const &Text ) {
+std::array read_fields( std::string_view const Text ) {
std::array result;
result.fill( -1.f );
- std::size_t start { 0 };
- for( std::size_t index = 0; index < Count && start < Text.size(); ++index ) {
- auto const end { std::min( Text.find( ';', start ), Text.size() ) };
- auto value { 0.f };
- if( end > start && std::from_chars( Text.data() + start, Text.data() + end, value ).ec == std::errc {} ) {
- result[ index ] = std::clamp( value, 0.f, most );
+ auto rest { Text };
+ for( auto &field : result ) {
+ auto const end { std::min( rest.find( ';' ), rest.size() ) };
+ if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} ) {
+ field = std::clamp( value, 0.f, most );
}
- start = end + 1;
+ if( end == rest.size() ) {
+ break;
+ }
+ rest.remove_prefix( end + 1 );
}
return result;
}
@@ -100,7 +103,7 @@ struct attribute {
};
// a plain track: value;up;side;cross;dip. A switch: p1-p2;p3-p4;up of p1-p2;side of p1-p2;up of p3-p4;side of p3-p4
-inline attribute read_attribute( std::string const &Text, bool const Switch ) {
+inline attribute read_attribute( std::string_view const Text, bool const Switch ) {
auto const fields { read_fields<6>( Text ) };
attribute result;
@@ -136,15 +139,15 @@ inline std::string write_attribute( attribute const &Values, bool const Switch )
// what a path comes to from the values: what's not given takes the first value, p3-p4 those of p1-p2. Cross level on plain tracks only
inline amounts declared( attribute const &Values, bool const Plain, int const Path ) {
+ auto const given = []( float const Part, double const Otherwise ) {
+ return Part >= 0.f ? static_cast( Part ) : Otherwise; };
amounts result {
- Values.up >= 0.f ? Values.up : Values.value,
- Values.side >= 0.f ? Values.side : Values.value,
- false == Plain ? 0.f : Values.cross >= 0.f ? Values.cross : Values.value };
+ given( Values.up, Values.value ),
+ given( Values.side, Values.value ),
+ Plain ? given( Values.cross, Values.value ) : 0.0 };
if( Path == 1 ) {
- auto const branch = [ &Values ]( float const Part, double const Straight ) -> double {
- return Part >= 0.f ? Part : Values.branch >= 0.f ? Values.branch : Straight; };
- result.up = branch( Values.branchup, result.up );
- result.side = branch( Values.branchside, result.side );
+ result.up = given( Values.branchup, given( Values.branch, result.up ) );
+ result.side = given( Values.branchside, given( Values.branch, result.side ) );
}
return result;
}
@@ -160,8 +163,9 @@ wave_set make_waves( double const Turn, std::array const &
wave_set result {};
for( std::size_t i = 0; i < Count; ++i ) {
auto const number { glm::two_pi() / Lengths[ i ] };
- auto const heading { Turn + golden * i };
- result[ i ] = { number * std::cos( heading ), number * std::sin( heading ), golden * ( i + 1 ) * ( 1.0 + 3.0 * Turn ), Shares[ i ] };
+ auto const place { static_cast( i ) };
+ auto const heading { Turn + golden * place };
+ result[ i ] = { number * std::cos( heading ), number * std::sin( heading ), golden * ( place + 1.0 ) * ( 1.0 + 3.0 * Turn ), Shares[ i ] };
}
return result;
}
@@ -246,7 +250,10 @@ inline glm::dvec3 across_of( glm::dvec3 const &Direction, glm::dvec3 const &Chor
// the cant where two paths meet, theirs turned to the way of this one: a switch takes that of a plain track, alike ones meet halfway
inline float joint_roll( float const Own, float const Their, bool const Switch, bool const Theirswitch ) {
- return Switch == Theirswitch ? 0.5f * ( Own + Their ) : Switch ? Their : Own;
+ if( Switch == Theirswitch ) {
+ return 0.5f * ( Own + Their );
+ }
+ return Switch ? Their : Own;
}
// each component the same way
From 32fadd634d259595a961556fd5e6349895569dec Mon Sep 17 00:00:00 2001
From: maj00r
Date: Sat, 31 Oct 2026 20:17:47 +0100
Subject: [PATCH 14/90] refactor(tools): the grading tool in smaller functions
As Sonar asks, and a regular expression with no backtracking. The results stay
the same byte for byte on baltyk_skm1, baltyk_cargo, td and lk357.
---
tools/track_uneven_grade.py | 348 +++++++++++++++++++++---------------
1 file changed, 208 insertions(+), 140 deletions(-)
diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py
index d643f94f8..1994559d0 100644
--- a/tools/track_uneven_grade.py
+++ b/tools/track_uneven_grade.py
@@ -43,7 +43,7 @@ STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0
GOLDEN = math.pi * (3.0 - math.sqrt(5.0))
UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))]
TOKEN = re.compile(r"//[^\n]*|\S+")
-NUMBER = re.compile(r"^[-+]?\d*\.?\d+([eE][-+]?\d+)?$")
+NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$")
def limit(speed):
@@ -79,38 +79,9 @@ class Scenery:
def read(self, path, offset=(0.0, 0.0, 0.0)):
path = path.resolve()
- if path in self.seen:
- return
- self.seen.add(path)
- text = path.read_bytes().decode("latin-1")
- self.texts[path] = text
- matches = [m for m in TOKEN.finditer(text) if not m.group(0).startswith("//")]
- words = [m.group(0) for m in matches]
- lower = [w.lower() for w in words]
- origins = [offset]
- i = 0
- while i < len(words):
- word = lower[i]
- if word == "include" and i + 1 < len(words):
- end = i + 1
- while end < len(words) and lower[end] != "end":
- end += 1
- self.include(words[i + 1], words[i + 2:end], origins[-1])
- i = end
- elif word == "origin" and i + 3 < len(words) and all(NUMBER.match(w) for w in words[i + 1:i + 4]):
- origins.append(tuple(o + float(w) for o, w in zip(origins[-1], words[i + 1:i + 4])))
- i += 3
- elif word == "endorigin" and len(origins) > 1:
- origins.pop()
- elif word == "rotate" and i + 3 < len(words) and any(w.strip("0.-") for w in words[i + 1:i + 4]):
- self.notes["rotate"] += 1
- elif word == "node" and i + 4 < len(words):
- kind = lower[i + 4]
- if kind == "track":
- i = self.track(path, matches, words, lower, i, origins[-1])
- elif kind == "model" and i + 9 < len(words) and GRASS.search(lower[i + 9]) and all(NUMBER.match(w) for w in words[i + 5:i + 8]):
- self.plant(float(words[i + 5]) + origins[-1][0], float(words[i + 7]) + origins[-1][2])
- i += 1
+ if path not in self.seen:
+ self.seen.add(path)
+ FileReader(self, path, offset).run()
def include(self, name, params, origin):
path = self.root / name.replace("\\", "/")
@@ -118,21 +89,90 @@ class Scenery:
numbers = [float(w) for w in params if NUMBER.match(w)]
if GRASS.search(name.lower()) and len(numbers) >= 3:
self.plant(numbers[0] + origin[0], numbers[2] + origin[2])
- return
- if not path.is_file():
+ elif not path.is_file():
self.notes["brak pliku " + name] += 1
- return
- if params:
+ elif not params:
+ self.read(path, origin)
+ elif path.stat().st_size < 4000000 and re.search(rb"\btrack\s+(normal|switch)\b", path.read_bytes(), re.I):
# the same file can come many times with other parameters: its tracks can't be told apart in one copy
- if path.stat().st_size < 4000000 and re.search(rb"\btrack\s+(normal|switch)\b", path.read_bytes(), re.I):
- self.notes["pliki z parametrami, tory pominiete"] += 1
- return
- self.read(path, origin)
+ self.notes["pliki z parametrami, tory pominiete"] += 1
def plant(self, x, z):
self.plants[(round(x / 10), round(z / 10))].append((x, z))
- def track(self, path, matches, words, lower, i, origin):
+
+class FileReader:
+ """Goes through the words of one file. Each handler takes the place of its word and gives the place of the last word it used."""
+
+ def __init__(self, scenery, path, offset):
+ self.scenery, self.path = scenery, path
+ text = path.read_bytes().decode("latin-1")
+ scenery.texts[path] = text
+ self.matches = [m for m in TOKEN.finditer(text) if not m.group(0).startswith("//")]
+ self.words = [m.group(0) for m in self.matches]
+ self.lower = [w.lower() for w in self.words]
+ self.origins = [offset]
+ self.handlers = {"include": self.include, "origin": self.origin, "endorigin": self.endorigin, "rotate": self.rotate, "node": self.node}
+
+ def run(self):
+ i = 0
+ while i < len(self.words):
+ handler = self.handlers.get(self.lower[i])
+ i = (handler(i) if handler else i) + 1
+
+ def include(self, i):
+ if i + 1 >= len(self.words):
+ return i
+ end = i + 1
+ while end < len(self.words) and self.lower[end] != "end":
+ end += 1
+ self.scenery.include(self.words[i + 1], self.words[i + 2:end], self.origins[-1])
+ return end
+
+ def origin(self, i):
+ values = self.words[i + 1:i + 4]
+ if len(values) < 3 or not all(NUMBER.match(w) for w in values):
+ return i
+ self.origins.append(tuple(o + float(w) for o, w in zip(self.origins[-1], values)))
+ return i + 3
+
+ def endorigin(self, i):
+ if len(self.origins) > 1:
+ self.origins.pop()
+ return i
+
+ def rotate(self, i):
+ if i + 3 < len(self.words) and any(w.strip("0.-") for w in self.words[i + 1:i + 4]):
+ self.scenery.notes["rotate"] += 1
+ return i
+
+ def node(self, i):
+ if i + 4 >= len(self.words):
+ return i
+ kind = self.lower[i + 4]
+ if kind == "track":
+ return self.track(i)
+ if kind == "model" and i + 9 < len(self.words) and GRASS.search(self.lower[i + 9]) and all(NUMBER.match(w) for w in self.words[i + 5:i + 8]):
+ self.scenery.plant(float(self.words[i + 5]) + self.origins[-1][0], float(self.words[i + 7]) + self.origins[-1][2])
+ return i
+
+ def paths_from(self, cursor, count):
+ paths = []
+ origin = self.origins[-1]
+ for _ in range(count):
+ values = self.words[cursor:cursor + 15]
+ if len(values) < 15 or not all(NUMBER.match(v) for v in values):
+ return None
+ n = [float(v) for v in values]
+ part = {"p1": [n[j] + origin[j] for j in range(3)], "c1": n[4:7], "c2": n[7:10], "p2": [n[10 + j] + origin[j] for j in range(3)], "radius": abs(n[14])}
+ part["line"] = line_of(part)
+ part["length"] = sum(math.dist(a, b) for a, b in zip(part["line"], part["line"][1:]))
+ paths.append(part)
+ cursor += 15
+ return paths
+
+ def track(self, i):
+ words, lower = self.words, self.lower
at = i + 4
end = at
while end < len(words) and lower[end] != "endtrack":
@@ -142,33 +182,30 @@ class Scenery:
kind = lower[at + 1]
if kind not in ("normal", "switch", "road"):
return end
- cursor = at + 10
- rail = ballast = None
- if lower[at + 9] == "vis":
- rail, ballast = lower[cursor], lower[cursor + 2]
- cursor += 6
- paths = []
- for _ in range(2 if kind == "switch" else 1):
- values = words[cursor:cursor + 15]
- if len(values) < 15 or not all(NUMBER.match(v) for v in values):
- self.notes["tory z parametrami, pominiete"] += 1
- return end
- n = [float(v) for v in values]
- part = dict(p1=[n[j] + origin[j] for j in range(3)], c1=n[4:7], c2=n[7:10], p2=[n[10 + j] + origin[j] for j in range(3)], radius=abs(n[14]))
- part["line"] = line_of(part)
- part["length"] = sum(math.dist(a, b) for a, b in zip(part["line"], part["line"][1:]))
- paths.append(part)
- cursor += 15
- if kind == "road":
- self.roads.append(paths[0])
- return end
- block = lower[at:end]
- taken = any(w in block for w in ("uneven", "unevenup", "unevenside", "unevencross", "jointdip"))
- velocity = float(words[at + block.index("velocity") + 1]) if "velocity" in block and NUMBER.match(words[at + block.index("velocity") + 1]) else 0.0
- sound = float(words[at + 5]) if NUMBER.match(words[at + 5]) else -1.0
- self.tracks.append(dict(name=words[i + 3], kind=kind, rail=rail, ballast=ballast, sound=sound, paths=paths, speed=velocity if velocity > 0 else None, source="wpis" if velocity > 0 else None, file=path, offset=matches[end].start(), taken=taken))
+ visible = lower[at + 9] == "vis"
+ paths = self.paths_from(at + (16 if visible else 10), 2 if kind == "switch" else 1)
+ if paths is None:
+ self.scenery.notes["tory z parametrami, pominiete"] += 1
+ elif kind == "road":
+ self.scenery.roads.append(paths[0])
+ else:
+ self.add_track(i, at, end, kind, visible, paths)
return end
+ def add_track(self, i, at, end, kind, visible, paths):
+ words = self.words
+ block = self.lower[at:end]
+ velocity = 0.0
+ if "velocity" in block and NUMBER.match(words[at + block.index("velocity") + 1]):
+ velocity = float(words[at + block.index("velocity") + 1])
+ self.scenery.tracks.append({
+ "name": words[i + 3], "kind": kind,
+ "rail": self.lower[at + 10] if visible else None, "ballast": self.lower[at + 12] if visible else None,
+ "sound": float(words[at + 5]) if NUMBER.match(words[at + 5]) else -1.0,
+ "paths": paths, "speed": velocity if velocity > 0 else None, "source": "wpis" if velocity > 0 else None,
+ "file": self.path, "offset": self.matches[end].start(),
+ "taken": any(w in block for w in ("uneven", "unevenup", "unevenside", "unevencross", "jointdip"))})
+
def bezier(part, t):
a = [part["p1"][i] + part["c1"][i] for i in range(3)]
@@ -220,50 +257,67 @@ class Joints:
return found
+def plain_neighbours(t, joints):
+ return [other for key in ("p1", "p2") for other, _, _ in joints.at(t["paths"][0][key]) if other is not t and other["kind"] == "normal"]
+
+
+def plain_past_switches(t, point, joints):
+ # the plain tracks reached from a point of a track along the straight paths of switches
+ points, seen, found = [point], set(), []
+ for _ in range(6):
+ onward = []
+ for reached in points:
+ for other, part, side in joints.at(reached):
+ if other is t or id(part) in seen:
+ continue
+ seen.add(id(part))
+ if other["kind"] != "switch":
+ found.append(other)
+ elif other["paths"].index(part) != other["bent"]:
+ onward.append(part["p2" if side == "p1" else "p1"])
+ points = onward
+ return found
+
+
+def short_pieces_past_switches(t, joints):
+ return [o for key in ("p1", "p2") for o in plain_past_switches(t, t["paths"][0][key], joints) if o["paths"][0]["length"] < PIECE]
+
+
+def spread_speed(tracks, joints, reached):
+ heads = collections.deque(t for t in tracks if t["kind"] == "normal" and t["speed"])
+ while heads:
+ t = heads.popleft()
+ for other in reached(t, joints):
+ if other["speed"] is None:
+ other["speed"], other["source"] = t["speed"], "sasiad"
+ heads.append(other)
+
+
def settle_speeds(tracks, joints):
# from the nearest track on the stretch between switches, a short piece also along the straight path of a switch
- heads = collections.deque(t for t in tracks if t["kind"] == "normal" and t["speed"])
- while heads:
- t = heads.popleft()
- for key in ("p1", "p2"):
- for other, _, _ in joints.at(t["paths"][0][key]):
- if other is not t and other["kind"] == "normal" and other["speed"] is None:
- other["speed"], other["source"] = t["speed"], "sasiad"
- heads.append(other)
- heads = collections.deque(t for t in tracks if t["kind"] == "normal" and t["speed"])
- while heads:
- t = heads.popleft()
- for key in ("p1", "p2"):
- points, seen = [t["paths"][0][key]], set()
- for _ in range(6):
- onward = []
- for point in points:
- for other, part, side in joints.at(point):
- if other is t or id(part) in seen:
- continue
- seen.add(id(part))
- if other["kind"] == "switch":
- if other["paths"].index(part) != other["bent"]:
- onward.append(part["p2" if side == "p1" else "p1"])
- elif other["speed"] is None and other["paths"][0]["length"] < PIECE:
- other["speed"], other["source"] = t["speed"], "sasiad"
- heads.append(other)
- points = onward
+ spread_speed(tracks, joints, plain_neighbours)
+ spread_speed(tracks, joints, short_pieces_past_switches)
for t in tracks:
if t["speed"] is None:
t["speed"], t["source"] = NO_SPEED, "brak"
+def plain_ends(tracks):
+ for t in tracks:
+ if t["kind"] == "normal":
+ for part in t["paths"]:
+ yield part["p1"]
+ yield part["p2"]
+
+
def distances(tracks, joints, station):
best, heap = {}, []
- for t in tracks:
- for part in t["paths"]:
- for key in ("p1", "p2"):
- gap = math.dist((part[key][0], part[key][2]), station)
- node = (round(part[key][0], 1), round(part[key][2], 1))
- if gap < 300 and t["kind"] == "normal" and gap < best.get(node, math.inf):
- best[node] = gap
- heapq.heappush(heap, (gap, node, part[key]))
+ for point in plain_ends(tracks):
+ gap = math.dist((point[0], point[2]), station)
+ node = (round(point[0], 1), round(point[2], 1))
+ if gap < 300 and gap < best.get(node, math.inf):
+ best[node] = gap
+ heapq.heappush(heap, (gap, node, point))
while heap:
distance, node, point = heapq.heappop(heap)
if distance > best.get(node, math.inf):
@@ -293,30 +347,34 @@ def grass_on(part, plants):
return len(near) * 100.0 / max(part["length"], 5.0)
+def cells_under(a, b):
+ for x in range(math.floor(min(a[0], b[0]) / 50), math.floor(max(a[0], b[0]) / 50) + 1):
+ for z in range(math.floor(min(a[2], b[2]) / 50), math.floor(max(a[2], b[2]) / 50) + 1):
+ yield x, z
+
+
def road_cells(roads):
cells = collections.defaultdict(list)
for road in roads:
for a, b in zip(road["line"], road["line"][1:]):
- for x in range(math.floor(min(a[0], b[0]) / 50), math.floor(max(a[0], b[0]) / 50) + 1):
- for z in range(math.floor(min(a[2], b[2]) / 50), math.floor(max(a[2], b[2]) / 50) + 1):
- cells[(x, z)].append((a, b))
+ for cell in cells_under(a, b):
+ cells[cell].append((a, b))
return cells
+def cross_in_plan(a, b, c, d):
+ rx, rz, sx, sz = b[0] - a[0], b[2] - a[2], d[0] - c[0], d[2] - c[2]
+ k = rx * sz - rz * sx
+ if abs(k) < 1e-9:
+ return False
+ t = ((c[0] - a[0]) * sz - (c[2] - a[2]) * sx) / k
+ u = ((c[0] - a[0]) * rz - (c[2] - a[2]) * rx) / k
+ return 0 <= t <= 1 and 0 <= u <= 1
+
+
def hits_road(part, cells):
- for a, b in zip(part["line"], part["line"][1:]):
- for x in range(math.floor(min(a[0], b[0]) / 50), math.floor(max(a[0], b[0]) / 50) + 1):
- for z in range(math.floor(min(a[2], b[2]) / 50), math.floor(max(a[2], b[2]) / 50) + 1):
- for c, d in cells.get((x, z), ()):
- rx, rz, sx, sz = b[0] - a[0], b[2] - a[2], d[0] - c[0], d[2] - c[2]
- k = rx * sz - rz * sx
- if abs(k) < 1e-9:
- continue
- t = ((c[0] - a[0]) * sz - (c[2] - a[2]) * sx) / k
- u = ((c[0] - a[0]) * rz - (c[2] - a[2]) * rx) / k
- if 0 <= t <= 1 and 0 <= u <= 1:
- return True
- return False
+ line = part["line"]
+ return any(cross_in_plan(a, b, c, d) for a, b in zip(line, line[1:]) for cell in cells_under(a, b) for c, d in cells.get(cell, ()))
def heights_per_mm(t):
@@ -423,17 +481,19 @@ def fit_under_pantograph(normal):
return low
+def joint_curve_changes(t, part, key, joints):
+ own = end_curve(part, key)
+ for other, theirs, side in joints.at(part[key]):
+ if other is not t and other["kind"] == "normal":
+ their = end_curve(theirs, side)
+ if abs(own - (-their if side == key else their)) > CURVE_STEP:
+ return True
+ return False
+
+
def curve_changes(t, joints):
part = t["paths"][0]
- if abs(end_curve(part, "p1") - end_curve(part, "p2")) > CURVE_STEP:
- return True
- for key in ("p1", "p2"):
- for other, theirs, side in joints.at(part[key]):
- if other is not t and other["kind"] == "normal":
- their = end_curve(theirs, side)
- if abs(end_curve(part, key) - (-their if side == key else their)) > CURVE_STEP:
- return True
- return False
+ return abs(end_curve(part, "p1") - end_curve(part, "p2")) > CURVE_STEP or any(joint_curve_changes(t, part, key, joints) for key in ("p1", "p2"))
def move_near_limit(normal, joints, share):
@@ -458,24 +518,32 @@ def move_near_limit(normal, joints, share):
return chosen
+def value_from_plain(t, index, part, joints, product):
+ found = [o for key in ("p1", "p2") for o, theirs, _ in joints.at(part[key]) if o["kind"] == "normal" and theirs["length"] >= SHORT]
+ if not found:
+ return None
+ speed = max(o["speed"] for o in found)
+ if index == t["bent"]:
+ speed = min(speed, DIVERGING)
+ return min(limit(speed) * max(o["state"] for o in found), SWITCH_MOST, product / speed)
+
+
+def value_from_switches(t, part, joints):
+ found = []
+ for key in ("p1", "p2"):
+ for other, theirs, _ in joints.at(part[key]):
+ if other["kind"] == "switch" and other is not t:
+ found += [other["values"][i] for i, q in enumerate(other["paths"]) if q is theirs and other["values"][i] is not None]
+ return max(found) if found else None
+
+
def grade_switches(switches, joints, product):
# each path by the plain tracks it leads to, the worst of them; those only among switches from their neighbours
for t in switches:
- t["values"] = [None] * len(t["paths"])
- for index, part in enumerate(t["paths"]):
- found = [o for key in ("p1", "p2") for o, theirs, _ in joints.at(part[key]) if o["kind"] == "normal" and theirs["length"] >= SHORT]
- if found:
- speed = max(o["speed"] for o in found)
- if index == t["bent"]:
- speed = min(speed, DIVERGING)
- t["values"][index] = min(limit(speed) * max(o["state"] for o in found), SWITCH_MOST, product / speed)
+ t["values"] = [value_from_plain(t, index, part, joints, product) for index, part in enumerate(t["paths"])]
for _ in range(5):
for t in switches:
- for index, part in enumerate(t["paths"]):
- if t["values"][index] is None:
- found = [o["values"][i] for key in ("p1", "p2") for o, theirs, _ in joints.at(part[key]) if o["kind"] == "switch" and o is not t for i, q in enumerate(o["paths"]) if q is theirs and o["values"][i] is not None]
- if found:
- t["values"][index] = max(found)
+ t["values"] = [value_from_switches(t, part, joints) if value is None else value for value, part in zip(t["values"], t["paths"])]
for t in switches:
t["values"] = [min(SWITCH_MOST, product / NO_SPEED) if v is None else v for v in t["values"]]
From dbc173ebeaf0d25c839e0e3df8bbe8dce76ef775 Mon Sep 17 00:00:00 2001
From: maj00r
Date: Sat, 31 Oct 2026 20:17:47 +0100
Subject: [PATCH 15/90] docs(track): what of the cab shake goes off on an
uneven track
A table of all the sources of the shake, and what happens to each of them.
---
track_uneven_doc.md | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)
diff --git a/track_uneven_doc.md b/track_uneven_doc.md
index c7446e34d..1c3163c50 100644
--- a/track_uneven_doc.md
+++ b/track_uneven_doc.md
@@ -69,7 +69,19 @@ The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the bo
Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres.
-On a track with unevenness the track itself shakes the cab. The sway calculated from the lateral acceleration, that is from the curve radius, and the random jolts at higher speed are off. On tracks with no unevenness they work as before.
+On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before. It goes by the track under the vehicle, and a track with only dips at its joints counts too. On tracks with no unevenness everything works as before.
+
+| source of the cab shake | on a track with unevenness |
+|--------------------------------------------------------------------|----------------------------|
+| side sway from the lateral acceleration: curve radius and cant, jolts sideways on a damaged switch | off |
+| random jolts over 25 km/h | off |
+| the track itself, from the bend under the axles | added |
+| vertical jolts at the joints of a damaged track | stays |
+| fore and aft, when accelerating and braking | stays |
+| diesel engine vibration | stays |
+| hunting (`huntingspring`), set by the vehicle | stays |
+
+This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration.
A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well.
From d995674bee8b45465fd98489a1559bf4d515765a Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 1 Nov 2026 09:12:36 +0100
Subject: [PATCH 16/90] =?UTF-8?q?fix(physics):=20automatic=20couplers=20do?=
=?UTF-8?q?n't=20catch=20above=20the=20safe=20collision=E2=80=A6=20(#217)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* fix: automatic coupler crashes, horns, compressor start delay, radio and cab lever sounds
fix(cab): the line contactors lamp goes out with the pressure switch (eu07/maszyna#470)
The lamp of the open line contactors, which tells the start can be made, went out at 1 bar in the brake
cylinders, while the pressure switch cuts the start off only at 2 bar (or below 3.6 bar in the main pipe), so
with the brakes partly applied the start could be made with the lamp out. With a pressure switch fitted the lamp
now follows it; without one it goes out at 1 bar as before. The same holds for the lamp of the second unit, which
used to keep its last state between 1 bar and the cut-off. The condition is
TMoverParameters::LineContactorsLampLit().
Tests: tests/unit/test_line_contactors.cpp.
refactor: Sonar findings of PR 217
- horn_supply::pneumatic shadowed the pneumatic enumerator of the sound flags (cpp:S1117), it's horn_supply::air;
the supplies read with using enum (S6177),
- CouplerForce(): the automatic coupling refused or caught without another level of nested ifs (S134), the
same outcome: too fast, the coupling is locked; caught, coupled and locked; otherwise left to try again,
- CompressorCheck(): the power the compressor doesn't draw yet noted without a TODO (S1135),
- tests: the previous crash damage setting in an in-class initializer (S3230), the loops which stop early with
break rather than in their conditions (S886), the stand-ins of test::pair in a std::vector rather than an array
(S5945), units in the comments of the example without /* */ (S1103).
test: the cases the changes of the branch left without a test
- Cntrl.: BDelay1 to BDelay4 reach the brake delays (now through std::format), the default start types of the
ground and converter overload relays of a multiple unit and of other vehicles (out of the nested conditionals),
- the compressor: fed from the low voltage it waits from the low voltage coming on; the pressure switch stops it
above the cut-out pressure, without one the excess air is vented (the vented fraction rewritten),
- the horns: a vehicle without any air sounds as before, the threshold pressure, an electric horn on 110 V,
- the positions of a cab control below zero, and a control without position sounds.
refactor(cab): the kind of the train heating switch as a flag
Read once with the vehicle definition, rather than compared as text in each of the switch commands.
feat(cab): train heating switch springing back (MaSzyna-EU07/maszyna#85)
TrainHeating=[toggle]|impulse in the Switches: section of the vehicle definition makes the train heating switch
an unstable one: it goes up to switch the heating on, down to switch it off, and back to the middle once let go,
instead of staying where it was put. The position of such a switch isn't set from the heating state when the cab
is entered.
Tests: tests/unit/test_switches.cpp.
feat(sound): mirror sounds (MaSzyna-EU07/maszyna#84, eu07/maszyna#322)
The sound definitions of a vehicle (.mmd) take mirroropen: and mirrorclose:, played as a mirror sets off
unfolding or folding, and the locations section mirrors: ... end, the offsets along the vehicle of the
mirror pairs, as for the doors (negative ahead of the centre), each pair at the sides of the vehicle. As the
animation, only the mirrors at the occupied cab sound. The start of a move is mirror_moves::motion in
vehicle/mirrors.h.
Tests: tests/unit/test_mirrors.cpp.
feat(cab): joint oil and fuel pump switch (MaSzyna-EU07/maszyna#81)
A cab control oilfuelpump_sw: switches both the oil and the fuel pump at once, with the new command
oilfuelpumptoggle (no key by default). As a two-state switch it turns both pumps off when both are on and both on
otherwise; as an impulse switch it's held to start them, like the separate pump switches. Its position follows
the pumps when the cab is entered.
refactor(editor): text fields filled without strncpy (MaSzyna-EU07/maszyna#112)
The last three strncpy calls Sonar flags (cpp:S5816), in the road and track editors, copy the text into the
ImGui field buffers with std::string::copy and terminate it right after; the text gets cut to the buffer as
before.
fix: automatic coupler crashes, horns, compressor start delay, radio and cab lever sounds
- automatic couplers don't catch above the safe collision speed (#86): with crash damage on they couple at a
closing speed of 15 km/h at most, a faster hit locks the coupling until the vehicles part and the collision
runs its course. On the way: CollisionVelocity() read a head-on 10 + 10 km/h as 14.1 km/h (quaternions turn
by half the angle), it's now taken from the touching ends; CollisionDetect() took the other vehicle's speed
the wrong way round for vehicles facing each other. Head-on hits now derail sooner, at the intended limit,
- a single horn lever can't sound both tones at once (eu07/maszyna#392),
- a skid ends once the vehicle stops on locked wheels (eu07/maszyna#479),
- electronic destination signs are blanked at the end of the timetable (eu07/maszyna#446),
- horns need the air or the voltage to sound (eu07/maszyna#290, #76): HornType=[Pneumatic]|Electric and
Horn3Type in Cntrl.; a pneumatic horn needs 0.2 MPa in the main reservoir (or the main pipe without one),
an electric one the low voltage; the lever stays where it was put,
- compressor start delay (#67): CompressorStartDelay [s] in Brake., counted from the compressor getting its
power, after the engine starts say; none by default,
- the channel and volume buttons of a radio without power do nothing (eu07/maszyna#429); the power check of
the radio is TMoverParameters::RadioPowered(),
- a lever moved smoothly sounds the positions it passes (#83).
Sonar findings in the functions changed: nesting, nested conditionals, commented-out code, std::format,
references to const. Unit tests: test::pair for two vehicles running into each other, test_couplers,
test_horn, test_wheelslip, test_compressor, test_radio, test_gauge_positions.
* fix: review findings of PR 217
- the pressures of the mover are in bar (MinCP=7.0 in the vehicle definitions), so the 0.2 the pneumatic horns
needed was 0.2 bar; it's 2 bar now, and the tests take their pressures in bar too,
- the lamps of the ground relay and of the motor overload relays follow the pressure switch as the line
contactors one does, TMoverParameters::MainCircuitLampsEnabled(), so the lamps of one cab go out together,
- the joint oil and fuel pump switch leaves out a pump started automatically, which ignores the switching:
with one, it couldn't turn the other off, and showed off with both running (OilFuelPumpsEnabled()),
- the kind of the train heating switch comes from the occupied vehicle on entering the cab too, as in the
switch commands; in a multiple unit these are different vehicles,
- CouplerForce() put the force taken back by the other vehicle on its far coupler when the vehicles faced each
other (Couplers[1 - End] rather than the coupler it's coupled with),
- the velocity difference along the coupler axis computed once, CouplerVelocityDifference(), for CouplerForce()
and CollisionVelocity(),
- the attachcoupler flag added without the SetFlag() call with 0, the index of the mirror moves noted as by side.
Tests: the coupler force of vehicles facing each other, the joint switch with an automatic pump, the lamps of
the main circuit, the horn and compressor pressures in bar.
* fix: coupler force of vehicles facing each other taken back along the other vehicle's axis
CForce runs along the axis of its own vehicle, so the force the other vehicle takes back on its coupler of the pair
is turned around once more when the vehicles face each other (-CF * DirPatch()), as that vehicle computes it itself.
Tests: the coupler forces of the pair facing each other and facing the same way.
---
CMakeLists.txt | 1 +
McZapkie/MOVER.h | 50 +++
McZapkie/Mover.cpp | 199 +++++++-----
application/editormoderoad.cpp | 4 +-
application/editormodetrack.cpp | 7 +-
input/command.cpp | 2 +
input/command.h | 1 +
input/drivermouseinput.cpp | 3 +
tests/unit/README.md | 6 +-
tests/unit/test_cntrl.cpp | 39 +++
tests/unit/test_compressor.cpp | 115 +++++++
tests/unit/test_couplers.cpp | 458 ++++++++++++++++++++++++++++
tests/unit/test_gauge_positions.cpp | 58 ++++
tests/unit/test_horn.cpp | 121 ++++++++
tests/unit/test_line_contactors.cpp | 59 ++++
tests/unit/test_mirrors.cpp | 32 ++
tests/unit/test_pumps.cpp | 52 ++++
tests/unit/test_radio.cpp | 28 ++
tests/unit/test_switches.cpp | 16 +
tests/unit/test_wheelslip.cpp | 62 ++++
tests/unit/vehicle.cpp | 104 ++++++-
tests/unit/vehicle.h | 51 ++++
utilities/translation.cpp | 1 +
vehicle/Driver.cpp | 27 +-
vehicle/DynObj.cpp | 91 +++++-
vehicle/DynObj.h | 16 +-
vehicle/Gauge.cpp | 42 ++-
vehicle/Train.cpp | 185 ++++++-----
vehicle/Train.h | 7 +-
vehicle/gaugepositions.h | 35 +++
vehicle/horn.cpp | 24 ++
vehicle/horn.h | 24 ++
vehicle/mirrors.h | 44 +++
vr/openvr_imp.cpp | 3 +
34 files changed, 1765 insertions(+), 202 deletions(-)
create mode 100644 tests/unit/test_cntrl.cpp
create mode 100644 tests/unit/test_compressor.cpp
create mode 100644 tests/unit/test_couplers.cpp
create mode 100644 tests/unit/test_gauge_positions.cpp
create mode 100644 tests/unit/test_horn.cpp
create mode 100644 tests/unit/test_line_contactors.cpp
create mode 100644 tests/unit/test_mirrors.cpp
create mode 100644 tests/unit/test_pumps.cpp
create mode 100644 tests/unit/test_radio.cpp
create mode 100644 tests/unit/test_switches.cpp
create mode 100644 tests/unit/test_wheelslip.cpp
create mode 100644 vehicle/gaugepositions.h
create mode 100644 vehicle/horn.cpp
create mode 100644 vehicle/horn.h
create mode 100644 vehicle/mirrors.h
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 477f584e9..dfe58b66d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -462,6 +462,7 @@ set(CORE_SOURCES
"utilities/utilities.cpp"
"scripting/ladderlogic.cpp"
"vehicle/handover.cpp"
+"vehicle/horn.cpp"
)
add_library(eu07_core STATIC ${CORE_SOURCES})
target_link_libraries(eu07_core PUBLIC eu07_settings)
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 29b3e75cd..bb36694bb 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -676,6 +676,13 @@ struct TTractionParam
};
/*powyzsze parametry zwiazane sa z torem po ktorym aktualnie pojazd jedzie*/
+// what a horn needs to sound: air from the main reservoir, or the low voltage
+enum class horn_supply
+{
+ air,
+ electric
+};
+
/// High-level brake-system family.
enum class TBrakeSystem
{
@@ -1710,6 +1717,10 @@ class TMoverParameters
float DistanceCounterDoublePressPeriod = {1.f}; // czas w jakim nalezy podwojnie wcisnac przycisk, aby rozpoczac pomiar odleglosci
TSecuritySystem SecuritySystem;
int EmergencyBrakeWarningSignal{0}; // combined with basic WarningSignal when manual emergency brake is active
+ horn_supply HornSupply{horn_supply::air}; // of the low and high tone horns (WarningSignal 1 and 2)
+ horn_supply Horn3Supply{horn_supply::air}; // of the third horn (WarningSignal 4)
+ // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent
+ static constexpr double HornMinPressure{2.0};
TUniversalCtrlTable UniCtrlList; /*lista pozycji uniwersalnego nastawnika*/
int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/
bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/
@@ -2001,6 +2012,8 @@ class TMoverParameters
bool CompressorAllow = false; /*! zezwolenie na uruchomienie sprezarki NBMX*/
bool CompressorAllowLocal{true}; // local device state override (most units don't have this fitted so it's set to true not to intefere)
bool CompressorGovernorLock{false}; // indicates whether compressor pressure switch was activated due to reaching cut-out pressure
+ double CompressorStartDelay{0.0}; // time [s] the compressor waits after getting its power before it can start, after the engine starts say
+ double CompressorPowerTime{0.0}; // time [s] since the compressor got its power
bool CompressorTankValve{false}; // indicates excessive pressure is vented from compressor tank directly and instantly
start_t CompressorStart{start_t::manual}; // whether the compressor is started manually, or another way
start_t PantographCompressorStart{start_t::manual};
@@ -2228,6 +2241,7 @@ class TMoverParameters
// TODO: move these switch types where they belong, cabin definition
std::string PantSwitchType;
std::string ConvSwitchType;
+ bool HeatingSwitchImpulse{false}; // the train heating switch springs back to its middle position
std::string StLinSwitchType;
bool Heating = false; // ogrzewanie 'Winger 020304
@@ -2428,6 +2442,42 @@ class TMoverParameters
double BrakeForce(const TTrackParam &Track);
double CouplerForce(int const End, double dt);
void CollisionDetect(int const End, double const dt);
+ // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio
+ static constexpr double SafeCollisionVelocity{15.0};
+ // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler
+ // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part
+ double CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const;
+ // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the
+ // other one, along this vehicle's axis
+ double CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const;
+ // 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;
+ // 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:
+ // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied
+ bool MainCircuitLampsEnabled() const
+ {
+ return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0);
+ }
+ // whether the lamp of the open line contactors is lit, telling the start can be made
+ bool LineContactorsLampLit() const
+ {
+ return false == StLinFlag && MainCircuitLampsEnabled();
+ }
+ // whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on
+ bool OilFuelPumpsEnabled() const
+ {
+ auto const fuelmanual{FuelPump.start_type != start_t::automatic};
+ 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
+ bool RadioPowered() const
+ {
+ return Radio && (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 3b5b62153..cb17e30ad 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/Logs.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
+
+#include
//---------------------------------------------------------------------------
// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane.
@@ -1176,6 +1178,56 @@ double TMoverParameters::EngineMaxRPM() const
std::numeric_limits::max(); // shouldn't ever get here but, eh
}
+// *************************************************************************************************
+// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h
+// *************************************************************************************************
+double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const
+{
+ auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)};
+ // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower
+ return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h
+}
+
+double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const
+{
+ // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the
+ // vehicles face each other (touch with the same ends)
+ return V - Other.V * DirPatch(End, OtherEnd);
+}
+
+bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const
+{
+ return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity;
+}
+
+int TMoverParameters::SoundingHorns(int const Signal) const
+{
+ auto const supplied{[this](horn_supply const Supply) {
+ if (Supply == horn_supply::electric)
+ {
+ return Power24vIsAvailable || Power110vIsAvailable;
+ }
+ if (VeselVolume > 0.0)
+ {
+ return Compressor >= HornMinPressure;
+ }
+ // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either
+ // (a road vehicle, say) has no air to check
+ auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0};
+ return false == mainpipe || ScndPipePress >= HornMinPressure;
+ }};
+ auto horns{0};
+ if (supplied(HornSupply))
+ {
+ horns |= Signal & (1 | 2);
+ }
+ if (supplied(Horn3Supply))
+ {
+ horns |= Signal & 4;
+ }
+ return horns;
+}
+
// *************************************************************************************************
// Q: 20160716
// Wykrywanie kolizji
@@ -1192,8 +1244,11 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
+ // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each
+ // other (touch with the same ends), as in CouplerForce()
+ auto const otherdirection{DirPatch(End, otherend)};
auto velocity{V};
- auto othervehiclevelocity{othervehicle->V};
+ auto othervehiclevelocity{othervehicle->V * otherdirection};
// calculate collision force and new velocities for involved vehicles
auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)};
auto CCF{0.0};
@@ -1224,28 +1279,25 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
damage_coupler(End);
}
- if (thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out))
- { // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist
- auto const safevelocitylimit{15.0};
- auto const velocitydifference{glm::length(glm::angleAxis(Rot.Rz, glm::dvec3{0, 1, 0}) * V - glm::angleAxis(othervehicle->Rot.Rz, glm::dvec3{0, 1, 0}) * othervehicle->V) *
- 3.6}; // m/s -> km/h
+ // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist
+ auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)};
+ auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0};
- if (velocitydifference > safevelocitylimit)
+ if (velocitydifference > SafeCollisionVelocity)
+ {
+ // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio
+ if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out))
{
- // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio
- if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out))
- {
- WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h");
- }
+ WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h");
+ }
- if (velocitydifference > safevelocitylimit * (TotalMass / othervehicle->TotalMass))
- {
- Derail(COLLISION);
- }
- if (velocitydifference > safevelocitylimit * (othervehicle->TotalMass / TotalMass))
- {
- othervehicle->Derail(COLLISION);
- }
+ if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass))
+ {
+ Derail(COLLISION);
+ }
+ if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass))
+ {
+ othervehicle->Derail(COLLISION);
}
}
}
@@ -1254,21 +1306,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
if (false == TestFlag(DamageFlag, dtrain_out))
{
auto const accelerationchange{(velocity - V) / dt};
- // if( accelerationchange / AccS < 1.0 ) {
- // HACK: prevent excessive vehicle pinball cases
AccS += accelerationchange;
- // AccS = std::clamp( AccS, -2.0, 2.0 );
V = velocity;
- // }
}
if (false == TestFlag(othervehicle->DamageFlag, dtrain_out))
{
- auto const othervehicleaccelerationchange{(othervehiclevelocity - othervehicle->V) / dt};
- // if( othervehicleaccelerationchange / othervehicle->AccS < 1.0 ) {
- // HACK: prevent excessive vehicle pinball cases
+ auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis
+ auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt};
othervehicle->AccS += othervehicleaccelerationchange;
- othervehicle->V = othervehiclevelocity;
- // }
+ othervehicle->V = othervehiclenewvelocity;
}
}
@@ -4332,7 +4378,10 @@ void TMoverParameters::CompressorCheck(double dt)
}
}
- auto const compressorpower{(CompressorPower == 0 ? Mains : CompressorPower == 3 ? Mains : Power110vIsAvailable)};
+ // the main circuit, also for a compressor driven by the engine, otherwise the low voltage
+ auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? Mains : Power110vIsAvailable};
+ CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0;
+ auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay};
// TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device
auto const compressorenable{CompressorAllowLocal && (CompressorStart == start_t::automatic || CompressorAllow)};
auto const compressordisable{false == compressorenable};
@@ -4354,7 +4403,7 @@ void TMoverParameters::CompressorCheck(double dt)
auto const compressorflag{CompressorFlag};
CompressorFlag =
- compressorpower && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay));
+ compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay));
if (CompressorFlag && CompressorFlag != compressorflag)
{
@@ -4384,30 +4433,23 @@ void TMoverParameters::CompressorCheck(double dt)
{
// vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level
SetFlag(SoundFlag, sound::relay | sound::loud);
- CompressedVolume *= false == governorlockispresent ? 0.80 : // arbitrary amount
- CompressorTankValve ? MinCompressorF / MaxCompressorF : // drop to mincompressor level
- 0.999; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly
+ auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly
+ if (false == governorlockispresent)
+ {
+ ventedfraction = 0.80; // arbitrary amount
+ }
+ else if (CompressorTankValve)
+ {
+ ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level
+ }
+ CompressedVolume *= ventedfraction;
if (false == governorlockispresent || CompressorTankValve)
{
CompressorGovernorLock = false;
}
}
- // tymczasowo tylko obciążenie sprężarki, tak z 5A na sprężarkę
- // TODO: draw power from proper high- or low voltage circuit
- if (CompressorPower == 3)
- {
- // diesel-powered compressor doesn't draw power
- }
- else
- {
- // TODO: drain power from 110v circuit
- /*
- if( compressorowner != nullptr ) {
- compressorowner->TotalCurrent += 0.0015 * compressorowner->PantographVoltage;
- }
- */
- }
+ // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet
}
// *************************************************************************************************
@@ -5008,7 +5050,7 @@ void TMoverParameters::ComputeTotalForce(double dt)
}
else
{
- EngineVoltage *= DirAbsolute; // DirActive*CabActive;
+ EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers
}
} // bo nie dzialalo
else
@@ -5032,6 +5074,14 @@ void TMoverParameters::ComputeTotalForce(double dt)
{
SlippingWheels = true;
}
+ if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle...
+ && std::abs(nrot * M_PI * WheelDiameter - V) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid
+ {
+ // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle
+ // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around
+ SlippingWheels = false;
+ nrot = V / M_PI / WheelDiameter;
+ }
double temp_nrot = nrot;
if (true == SlippingWheels)
{
@@ -5286,7 +5336,7 @@ double TMoverParameters::CouplerForce(int const End, double dt)
auto const newdistance{initialdistance + 10.0 * distancedelta};
- auto const dV{V - othervehicle->V * DirPatch(End, otherend)};
+ auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)};
auto const absdV{std::abs(dV)};
// potentially generate sounds on clash or stretch
@@ -5399,25 +5449,23 @@ double TMoverParameters::CouplerForce(int const End, double dt)
couplingtype &= ~coupling::control;
}
- if (Attach(End, otherend, othervehicle, couplingtype))
- {
- // HACK: we're reusing sound enum to mark whether vehicle was connected to another
- SetFlag(AIFlag, sound::attachcoupler);
- thiscoupler.AutomaticCouplingAllowed = false;
- othercoupler.AutomaticCouplingAllowed = false;
- }
- /*
- coupler.CouplingFlag = ( coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag );
- SetFlag( coupler.sounds, sound::attachcoupler );
- */
+ // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
+ auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)};
+ auto const caught{safe && Attach(End, otherend, othervehicle, couplingtype)};
+ // HACK: we're reusing sound enum to mark whether vehicle was connected to another
+ AIFlag |= (caught ? sound::attachcoupler : 0);
+ // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down
+ thiscoupler.AutomaticCouplingAllowed = safe && false == caught;
+ othercoupler.AutomaticCouplingAllowed = safe && false == caught;
}
}
}
if (thiscoupler.CouplingFlag != coupling::faux)
{
- // uzgadnianie prawa Newtona
- othervehicle->Couplers[1 - End].CForce = -CF;
+ // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's
+ // axis: turned around once more when the vehicles face each other
+ othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend);
}
return CF;
@@ -10468,6 +10516,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line)
auto lookup = compressorpowers.find(extract_value("CompressorPower", line));
CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1;
}
+ extract_value(CompressorStartDelay, "CompressorStartDelay", line, "");
if (true == extract_value(AirLeakRate, "AirLeakRate", line, ""))
{
@@ -10684,7 +10733,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
for (int idx = 0; idx < 4; ++idx)
{
- extract_value(BrakeDelay[idx], "BDelay" + std::to_string(idx + 1), line, "");
+ extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, "");
}
// brakedelays, brakedelayflag
{
@@ -10780,6 +10829,16 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
// maksymalna predkosc dostepna na tarczce predkosciomierza
extract_value(maxTachoSpeed, "MaxTachoSpeed", line, "");
+ // horns
+ {
+ using enum horn_supply;
+ std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}};
+ auto lookup = hornsupplies.find(extract_value("HornType", line));
+ HornSupply = lookup != hornsupplies.end() ? lookup->second : air;
+ lookup = hornsupplies.find(extract_value("Horn3Type", line));
+ Horn3Supply = lookup != hornsupplies.end() ? lookup->second : HornSupply;
+ }
+
// dynamicbrake
{
std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}};
@@ -10939,14 +10998,15 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
// ground relay
{
auto lookup = starts.find(extract_value("GroundRelayStart", line));
- GroundRelayStart = lookup != starts.end() ? lookup->second : TrainType == dt_EZT ? start_t::automatic : start_t::manual;
+ auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual};
+ GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart;
}
// converter overload relay
{
auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line));
- ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second :
- TrainType == dt_EZT ? start_t::converter : // relay activates when converter is switched off
- start_t::manual;
+ // the relay of a multiple unit activates when the converter is switched off
+ auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual};
+ ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart;
}
}
@@ -11339,6 +11399,7 @@ void TMoverParameters::LoadFIZ_Switches(std::string const &Input)
extract_value(PantSwitchType, "Pantograph", Input, "");
extract_value(ConvSwitchType, "Converter", Input, "");
extract_value(StLinSwitchType, "MotorConnectors", Input, "");
+ HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse";
// because people can't make up their minds whether it's "impulse" or "Impulse"...
PantSwitchType = ToLower(PantSwitchType);
ConvSwitchType = ToLower(ConvSwitchType);
diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp
index a07da795f..9b5dc64ac 100644
--- a/application/editormoderoad.cpp
+++ b/application/editormoderoad.cpp
@@ -120,8 +120,8 @@ bool is_curved(segment_data const &Path)
void copy_text(char *Buffer, std::size_t const Size, std::string const &Text)
{
- std::strncpy(Buffer, Text.c_str(), Size - 1);
- Buffer[Size - 1] = 0;
+ // as much of the text as fits, always terminated
+ Buffer[Text.copy(Buffer, Size - 1)] = 0;
}
std::string lower_case(std::string Text)
diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp
index 0b264b784..8dfd831f9 100644
--- a/application/editormodetrack.cpp
+++ b/application/editormodetrack.cpp
@@ -1188,8 +1188,8 @@ void editor_mode::render_path_parameters(TTrack &Track)
if (m_track_material_edited[i] != nullptr)
continue;
auto const name = materials[i] ? editor_track::material_name(*materials[i]) : std::string{};
- std::strncpy(m_track_materials[i].data(), name.c_str(), m_track_materials[i].size() - 1);
- m_track_materials[i].back() = '\0';
+ auto &buffer{m_track_materials[i]};
+ buffer[name.copy(buffer.data(), buffer.size() - 1)] = '\0';
}
}
for (int i = 0; i < 3; ++i)
@@ -1238,8 +1238,7 @@ void editor_mode::render_path_circuits(TTrack &Track)
{
auto *track{&Track};
auto const copy = [](std::array &Buffer, std::string const &Text) {
- std::strncpy(Buffer.data(), Text.c_str(), Buffer.size() - 1);
- Buffer.back() = '\0';
+ Buffer[Text.copy(Buffer.data(), Buffer.size() - 1)] = '\0';
};
auto const isolated_text = [&]() {
std::string text;
diff --git a/input/command.cpp b/input/command.cpp
index d7966f37d..0ae67cfa5 100644
--- a/input/command.cpp
+++ b/input/command.cpp
@@ -405,6 +405,7 @@ commanddescription_sequence Commands_descriptions = {
{"wiperswitchincrease", command_target::vehicle, command_mode::oneoff},
{"wiperswitchdecrease", command_target::vehicle, command_mode::oneoff},
{"lightsset", command_target::vehicle, command_mode::oneoff},
+ {"oilfuelpumptoggle", command_target::vehicle, command_mode::oneoff},
};
// Maps of command and coresponding strings
@@ -789,6 +790,7 @@ std::unordered_map const commandMap = {
{"wiperswitchincrease", user_command::wiperswitchincrease},
{"wiperswitchdecrease", user_command::wiperswitchdecrease},
{"lightsset", user_command::lightsset},
+ {"oilfuelpumptoggle", user_command::oilfuelpumptoggle},
{"none", user_command::none}};
} // namespace simulation
diff --git a/input/command.h b/input/command.h
index e03622a9f..ddacef4a0 100644
--- a/input/command.h
+++ b/input/command.h
@@ -403,6 +403,7 @@ enum class user_command
wiperswitchincrease,
wiperswitchdecrease,
lightsset,
+ oilfuelpumptoggle,
none = -1
};
diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp
index ab3d0aaf8..22562b856 100644
--- a/input/drivermouseinput.cpp
+++ b/input/drivermouseinput.cpp
@@ -576,6 +576,9 @@ drivermouse_input::default_bindings() {
{ "oilpump_sw:", {
oilpumptoggle,
none } },
+ { "oilfuelpump_sw:", {
+ oilfuelpumptoggle,
+ none } },
{ "motorblowersfront_sw:", {
motorblowerstogglefront,
none } },
diff --git a/tests/unit/README.md b/tests/unit/README.md
index bca46e83b..97cc94910 100644
--- a/tests/unit/README.md
+++ b/tests/unit/README.md
@@ -56,8 +56,10 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") {
functions on the vehicle state the class calls, and the test calls them the same way: see
`vehicle/handover.h`, which `TController::TakeControl()` uses, and `test_handover.cpp`.
- `vehicle` creates the vehicle the way `TDynamicObject::Init()` does and steps it the way the
- simulation loop does, on a straight track of the given friction and gradient. Coupled vehicles
- aren't supported yet.
+ simulation loop does, on a straight track of the given friction and gradient. `pair` puts two of
+ them on that track facing each other with the given ends and runs them together, as the
+ simulation runs the vehicles of a scene: the coupler and buffer forces, collisions and automatic
+ coupling come from the physics (`test_couplers.cpp`). Longer consists aren't supported yet.
- Check behaviour (speeds, pressures, states the player sees) rather than internal flags, and make
the test check its own preconditions (`REQUIRE` that the braking skidded, before checking what a
skid leads to).
diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp
new file mode 100644
index 000000000..0dd3ddc20
--- /dev/null
+++ b/tests/unit/test_cntrl.cpp
@@ -0,0 +1,39 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+using test::definition;
+using test::vehicle;
+
+// the Cntrl. section of the vehicle definition, as read by TMoverParameters::LoadFIZ_Cntrl()
+
+TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4") {
+ vehicle wagon{definition::load("wagon").set("Cntrl", "BDelay1", 10.0).set("Cntrl", "BDelay2", 20.0).set("Cntrl", "BDelay3", 30.0).set("Cntrl", "BDelay4", 40.0)};
+ CHECK(wagon->BrakeDelay[0] == doctest::Approx(10.0));
+ // the vehicle varies the others a little, by 0.83 to 0.9 (CheckLocomotiveParameters())
+ for (auto setting{1}; setting < 4; ++setting) {
+ CAPTURE(setting);
+ auto const given{10.0 * (setting + 1)};
+ CHECK(wagon->BrakeDelay[setting] >= 0.83 * given);
+ CHECK(wagon->BrakeDelay[setting] <= 0.9 * given);
+ }
+}
+
+TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other vehicles by hand") {
+ SUBCASE("multiple unit") {
+ vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")};
+ REQUIRE(unit->TrainType == dt_EZT);
+ CHECK(unit->GroundRelayStart == start_t::automatic);
+ CHECK(unit->ConverterOverloadRelayStart == start_t::converter); // activates when the converter is switched off
+ }
+ SUBCASE("other vehicle") {
+ vehicle wagon{definition::load("wagon")};
+ CHECK(wagon->GroundRelayStart == start_t::manual);
+ CHECK(wagon->ConverterOverloadRelayStart == start_t::manual);
+ }
+ SUBCASE("given in the definition") {
+ vehicle unit{definition::load("wagon").set("Param", "Type", "ezt").set("Cntrl", "GroundRelayStart", "Manual").set("Cntrl", "ConverterOverloadRelayStart", "Automatic")};
+ CHECK(unit->GroundRelayStart == start_t::manual);
+ CHECK(unit->ConverterOverloadRelayStart == start_t::automatic);
+ }
+}
diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp
new file mode 100644
index 000000000..c5aa2fff7
--- /dev/null
+++ b/tests/unit/test_compressor.cpp
@@ -0,0 +1,115 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+using test::definition;
+using test::vehicle;
+
+// the compressor waiting a while after getting its power before it starts (CompressorStartDelay,
+// MaSzyna-EU07/maszyna#67): in a diesel it starts some time after the engine, rather than with it
+
+namespace {
+
+double const step{0.01};
+
+// a compressor which starts on its own, fed from the main circuit unless given another Power, its pressure
+// switch between MinCP and MaxCP, and an empty main reservoir for it to fill
+vehicle compressor_vehicle(double const Delay, std::string const &Power = "Main", double const MinCP = 6.5) {
+ auto definition{definition::load("wagon")};
+ definition.set("Brake", "Vv", 1.0).set("Brake", "MinCP", MinCP).set("Brake", "MaxCP", 8.0);
+ definition.set("Brake", "CompressorSpeed", 0.01);
+ if (false == Power.empty()) {
+ definition.set("Brake", "CompressorPower", Power);
+ }
+ definition.set("Cntrl", "CompressorStart", "Automatic");
+ if (Delay > 0.0) {
+ definition.set("Brake", "CompressorStartDelay", Delay);
+ }
+ vehicle vehicle{definition};
+ vehicle->CompressedVolume = 0.0;
+ vehicle->LastSwitchingTime = 10.0; // nothing was switched lately
+ return vehicle;
+}
+
+// runs the compressor for Seconds, the main circuit as it is, the time since the last switching going on as in
+// ComputeTotalForce()
+void run_compressor(vehicle &Vehicle, double const Seconds) {
+ for (auto i{std::lround(Seconds / step)}; i > 0; --i) {
+ Vehicle->LastSwitchingTime += step;
+ Vehicle->CompressorCheck(step);
+ }
+}
+
+} // namespace
+
+TEST_CASE("compressor: without a start delay the compressor starts with its power") {
+ auto vehicle{compressor_vehicle(0.0)};
+ run_compressor(vehicle, 1.0);
+ REQUIRE_FALSE(vehicle->CompressorFlag); // no power, no compressor
+
+ vehicle->Mains = true;
+ run_compressor(vehicle, step);
+ CHECK(vehicle->CompressorFlag);
+}
+
+TEST_CASE("compressor: the compressor starts the delay after getting its power") {
+ auto vehicle{compressor_vehicle(5.0)};
+ vehicle->Mains = true;
+
+ run_compressor(vehicle, 4.9);
+ CHECK_FALSE(vehicle->CompressorFlag);
+ CHECK(vehicle->Compressor == doctest::Approx(0.0));
+
+ run_compressor(vehicle, 0.2);
+ CHECK(vehicle->CompressorFlag);
+ run_compressor(vehicle, 10.0);
+ CHECK(vehicle->Compressor > 0.0); // and fills the reservoir
+}
+
+TEST_CASE("compressor: the delay starts over once the power is gone") {
+ auto vehicle{compressor_vehicle(5.0)};
+ vehicle->Mains = true;
+ run_compressor(vehicle, 10.0);
+ REQUIRE(vehicle->CompressorFlag);
+
+ vehicle->Mains = false; // the engine stopped
+ run_compressor(vehicle, 1.0);
+ CHECK_FALSE(vehicle->CompressorFlag);
+
+ vehicle->Mains = true; // and started again
+ run_compressor(vehicle, 4.9);
+ CHECK_FALSE(vehicle->CompressorFlag);
+ run_compressor(vehicle, 0.2);
+ CHECK(vehicle->CompressorFlag);
+}
+
+TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") {
+ auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V
+ vehicle->Mains = true; // which alone doesn't feed it
+ run_compressor(vehicle, 10.0);
+ REQUIRE_FALSE(vehicle->CompressorFlag);
+
+ vehicle->Power110vIsAvailable = true;
+ run_compressor(vehicle, 4.9);
+ CHECK_FALSE(vehicle->CompressorFlag);
+ run_compressor(vehicle, 0.2);
+ CHECK(vehicle->CompressorFlag);
+}
+
+TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") {
+ auto vehicle{compressor_vehicle(0.0)};
+ vehicle->Mains = true;
+ vehicle->CompressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3
+ run_compressor(vehicle, step);
+ CHECK(vehicle->CompressorGovernorLock);
+ CHECK_FALSE(vehicle->CompressorFlag);
+}
+
+TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") {
+ auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch
+ vehicle->Mains = true;
+ vehicle->CompressedVolume = 8.5;
+ run_compressor(vehicle, step);
+ REQUIRE(vehicle->CompressorFlag); // nothing stops it
+ CHECK(vehicle->CompressedVolume < 8.5 * 0.81); // a fifth of the air let out
+}
diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp
new file mode 100644
index 000000000..8787a419b
--- /dev/null
+++ b/tests/unit/test_couplers.cpp
@@ -0,0 +1,458 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+#include "utilities/Globals.h"
+
+using test::definition;
+using test::vehicle;
+
+namespace {
+
+// the wagon from data/wagon.json with automatic couplers at both ends, which couple the given connections
+definition automatic_definition(int Flag = coupling::coupler | coupling::brakehose) {
+ return definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Flag);
+}
+
+// the wagon from data/wagon.json with automatic couplers at both ends, running at the given speed [km/h]
+vehicle automatic_wagon(double Velocity, std::string const &Name) {
+ return vehicle{automatic_definition(), Velocity, Name};
+}
+
+// the same wagon, twice as heavy
+vehicle heavy_automatic_wagon(double Velocity, std::string const &Name) {
+ return vehicle{automatic_definition().set("Param", "M", 2 * 42200), Velocity, Name};
+}
+
+bool derailed(vehicle &Vehicle) {
+ return TestFlag(Vehicle->DamageFlag, dtrain_out);
+}
+
+// runs the pair for Seconds, returns whether the vehicles were coupled at any point
+bool couple_during(test::pair &Pair, double Seconds) {
+ auto coupled{false};
+ for (auto i{std::lround(Seconds / 0.01)}; i > 0; --i) {
+ Pair.step();
+ coupled = coupled || Pair.coupled();
+ }
+ return coupled;
+}
+
+// sets the crash damage setting for the test, restores it after
+class crash_damage_setting {
+public:
+ explicit crash_damage_setting(bool Enabled) { Global.crash_damage = Enabled; }
+ ~crash_damage_setting() { Global.crash_damage = m_previous; }
+ crash_damage_setting(crash_damage_setting const &) = delete;
+ crash_damage_setting &operator=(crash_damage_setting const &) = delete;
+
+private:
+ bool m_previous{Global.crash_damage};
+};
+
+} // namespace
+
+// issue #86: automatic couplers used to catch at any closing speed, so the vehicles never collided nor derailed
+
+TEST_CASE("couplers: automatic couplers catch a standing wagon hit at a walking pace") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(10.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ REQUIRE(moving->Couplers[end::front].type() == TCouplerType::Automatic);
+ REQUIRE(moving.speed() == doctest::Approx(10.0));
+
+ // the front of the moving wagon runs into the rear of the standing one
+ CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(10.0));
+ CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+ CHECK(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front));
+}
+
+TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wagons collide instead") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(30.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ REQUIRE(moving.speed() == doctest::Approx(30.0));
+
+ CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) > TMoverParameters::SafeCollisionVelocity);
+ CHECK_FALSE(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+ CHECK_FALSE(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front));
+}
+
+TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a little slower") {
+ crash_damage_setting const crashdamage{true};
+ auto faster{automatic_wagon(60.0, "faster")};
+ auto slower{automatic_wagon(50.0, "slower")};
+
+ CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(10.0));
+ CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(10.0));
+ CHECK(faster->AutomaticCouplingSafe(end::front, slower.mover(), end::rear));
+}
+
+TEST_CASE("couplers: without crash damage automatic couplers catch at any speed") {
+ crash_damage_setting const crashdamage{false};
+ auto moving{automatic_wagon(30.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+
+ CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+}
+
+// the closing speed used to treat the speed of each vehicle as a vector turned by half its heading, so for vehicles
+// facing each other it came out as the root of the sum of the squares of their speeds, rather than the sum
+
+TEST_CASE("couplers: the closing speed of a rear-end collision is the difference of the speeds") {
+ auto faster{automatic_wagon(40.0, "faster")};
+ auto slower{automatic_wagon(25.0, "slower")};
+
+ // running forwards, the front of the faster wagon hits the rear of the slower one
+ CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(15.0));
+ CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(15.0));
+ // the wagons running ahead of each other are parting
+ CHECK(slower->CollisionVelocity(end::front, faster.mover(), end::rear) == doctest::Approx(-15.0));
+
+ // backing up, the rear of the faster wagon hits the front of the slower one
+ auto backingfaster{automatic_wagon(-40.0, "backing faster")};
+ auto backingslower{automatic_wagon(-25.0, "backing slower")};
+ CHECK(backingfaster->CollisionVelocity(end::rear, backingslower.mover(), end::front) == doctest::Approx(15.0));
+ CHECK(backingslower->CollisionVelocity(end::front, backingfaster.mover(), end::rear) == doctest::Approx(15.0));
+}
+
+TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the speeds") {
+ crash_damage_setting const crashdamage{true};
+ auto first{automatic_wagon(10.0, "first")};
+ auto second{automatic_wagon(10.0, "second")};
+
+ // both wagons run forwards, their fronts meet
+ CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) == doctest::Approx(20.0));
+ CHECK(second->CollisionVelocity(end::front, first.mover(), end::front) == doctest::Approx(20.0));
+ // 20 km/h is above the limit, the couplers don't catch (the old formula gave 14.1 km/h and coupled them)
+ CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) > TMoverParameters::SafeCollisionVelocity);
+ CHECK_FALSE(first->AutomaticCouplingSafe(end::front, second.mover(), end::front));
+ CHECK_FALSE(second->AutomaticCouplingSafe(end::front, first.mover(), end::front));
+
+ // both wagons back up, their rears meet
+ auto firstbacking{automatic_wagon(-10.0, "first backing")};
+ auto secondbacking{automatic_wagon(-10.0, "second backing")};
+ CHECK(firstbacking->CollisionVelocity(end::rear, secondbacking.mover(), end::rear) == doctest::Approx(20.0));
+
+ // running back to back, the wagons part
+ CHECK(first->CollisionVelocity(end::rear, second.mover(), end::rear) == doctest::Approx(-20.0));
+ CHECK(first->AutomaticCouplingSafe(end::rear, second.mover(), end::rear));
+
+ // slow enough, the couplers catch
+ auto slowfirst{automatic_wagon(5.0, "slow first")};
+ auto slowsecond{automatic_wagon(5.0, "slow second")};
+ CHECK(slowfirst->CollisionVelocity(end::front, slowsecond.mover(), end::front) == doctest::Approx(10.0));
+ CHECK(slowfirst->AutomaticCouplingSafe(end::front, slowsecond.mover(), end::front));
+}
+
+TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the speed of the moving one, whichever way it faces") {
+ auto moving{automatic_wagon(20.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+
+ // the standing wagon faces away from the moving one
+ CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(20.0));
+ CHECK(standing->CollisionVelocity(end::rear, moving.mover(), end::front) == doctest::Approx(20.0));
+ // the standing wagon faces the moving one
+ CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::front) == doctest::Approx(20.0));
+ CHECK(standing->CollisionVelocity(end::front, moving.mover(), end::front) == doctest::Approx(20.0));
+ // the moving wagon backs up into the standing one
+ auto backing{automatic_wagon(-20.0, "backing")};
+ CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(20.0));
+ CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::rear) == doctest::Approx(20.0));
+ // the moving wagon runs away from the standing one
+ CHECK(moving->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(-20.0));
+}
+
+// the coupling as the simulation runs it: two vehicles on a track, closing in on each other until the couplers (or
+// buffers) meet, the coupler forces and the collision computed by the physics, step by step
+
+TEST_CASE("couplers: automatic couplers catch right up to the safe closing speed") {
+ crash_damage_setting const crashdamage{true};
+ auto standing{automatic_wagon(0.0, "standing")};
+
+ auto below{automatic_wagon(14.9, "below")};
+ CHECK(below->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(14.9));
+ CHECK(below->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+
+ auto above{automatic_wagon(15.1, "above")};
+ CHECK(above->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(15.1));
+ CHECK_FALSE(above->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+ auto faster{automatic_wagon(15.5, "faster")};
+ CHECK_FALSE(faster->AutomaticCouplingSafe(end::front, standing.mover(), end::rear));
+}
+
+TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(5.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+
+ pair.run(3.0);
+
+ REQUIRE(pair.coupled());
+ CHECK(moving->Couplers[end::front].CouplingFlag == (coupling::coupler | coupling::brakehose));
+ CHECK(standing->Couplers[end::rear].CouplingFlag == (coupling::coupler | coupling::brakehose));
+ CHECK(moving->Couplers[end::front].Connected == &standing.mover());
+ CHECK_FALSE(derailed(moving));
+ CHECK_FALSE(derailed(standing));
+ // coupled, they run on together
+ pair.run(2.0);
+ CHECK(moving.speed() == doctest::Approx(standing.speed()).epsilon(0.05));
+ CHECK(pair.gap() < 0.2);
+}
+
+TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor once the hit has slowed it down") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(30.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+
+ auto touched{false};
+ auto parted{false};
+ auto coupled{false};
+ auto locked{true};
+ for (int i = 0; i < 1000; ++i) {
+ pair.step();
+ // as far as the couplers know: the distance between them at the start of the step
+ auto const distance{moving->Neighbours[end::front].distance};
+ touched = touched || distance < 0.0;
+ parted = parted || (touched && distance > 0.05);
+ coupled = coupled || pair.coupled();
+ if (touched && false == parted) {
+ locked = locked && false == moving->Couplers[end::front].AutomaticCouplingAllowed && false == standing->Couplers[end::rear].AutomaticCouplingAllowed;
+ }
+ }
+
+ REQUIRE(touched);
+ CHECK_FALSE(coupled);
+ // the hit derailed and stopped them, the couplers next to each other, the automatic coupling locked all along
+ CHECK_FALSE(parted);
+ CHECK(locked);
+ CHECK(derailed(moving));
+ CHECK(derailed(standing));
+ CHECK(std::abs(moving.speed()) < 3.0);
+ CHECK(std::abs(standing.speed()) < 3.0);
+ CHECK_FALSE(couple_during(pair, 5.0));
+}
+
+TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the vehicles part") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(3.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ // as a hit too fast or manual uncoupling leaves them
+ moving->Couplers[end::front].AutomaticCouplingAllowed = false;
+ standing->Couplers[end::rear].AutomaticCouplingAllowed = false;
+
+ SUBCASE("parted by more than 5 cm, they couple on the next approach") {
+ test::pair pair{moving, end::front, standing, end::rear, 0.5};
+ pair.step();
+ CHECK(moving->Couplers[end::front].AutomaticCouplingAllowed);
+ CHECK(couple_during(pair, 3.0));
+ }
+ SUBCASE("kept together, they don't") {
+ test::pair pair{moving, end::front, standing, end::rear, 0.0};
+ auto coupled{false};
+ for (int i = 0; i < 300; ++i) {
+ pair.step();
+ if (pair.gap() > 0.05) {
+ break; // parted
+ }
+ coupled = coupled || pair.coupled();
+ }
+ CHECK_FALSE(coupled);
+ }
+}
+
+// the couplers refuse a hit by the closing speed when they meet, the derail check (CollisionDetect()) takes the one
+// left when the buffers are pressed in all the way, after their springs have slowed the hit down: for the wagons here
+// by about 7 km/h. so a hit a little over the safe closing speed only bounces the vehicles apart
+
+TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicles apart, uncoupled and on the rails") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(20.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+
+ CHECK_FALSE(couple_during(pair, 3.0));
+ CHECK_FALSE(derailed(moving));
+ CHECK_FALSE(derailed(standing));
+ CHECK(pair.gap() > 0.5);
+ CHECK(standing.speed() > moving.speed());
+}
+
+TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over the limit adjusted for their mass ratio") {
+ crash_damage_setting const crashdamage{true};
+
+ SUBCASE("equal masses: both derail") {
+ auto moving{automatic_wagon(30.0, "moving")};
+ auto standing{automatic_wagon(0.0, "standing")};
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+ CHECK_FALSE(couple_during(pair, 5.0));
+ CHECK(derailed(moving));
+ CHECK(derailed(standing));
+ }
+ SUBCASE("half the mass: between the safe closing speed and twice that, only the lighter one derails") {
+ auto light{automatic_wagon(27.0, "light")};
+ auto heavy{heavy_automatic_wagon(0.0, "heavy")};
+ test::pair pair{light, end::front, heavy, end::rear, 1.0};
+ CHECK_FALSE(couple_during(pair, 5.0));
+ CHECK(derailed(light));
+ CHECK_FALSE(derailed(heavy));
+ }
+ SUBCASE("half the mass: above twice the safe closing speed both derail") {
+ auto light{automatic_wagon(45.0, "light")};
+ auto heavy{heavy_automatic_wagon(0.0, "heavy")};
+ test::pair pair{light, end::front, heavy, end::rear, 1.0};
+ CHECK_FALSE(couple_during(pair, 5.0));
+ CHECK(derailed(light));
+ CHECK(derailed(heavy));
+ }
+ SUBCASE("half the mass: below the safe closing speed the couplers catch, nothing derails") {
+ auto light{automatic_wagon(12.0, "light")};
+ auto heavy{heavy_automatic_wagon(0.0, "heavy")};
+ test::pair pair{light, end::front, heavy, end::rear, 1.0};
+ CHECK(couple_during(pair, 5.0));
+ CHECK_FALSE(derailed(light));
+ CHECK_FALSE(derailed(heavy));
+ }
+}
+
+TEST_CASE("couplers: wagons running head-on into each other couple only up to the safe closing speed") {
+ crash_damage_setting const crashdamage{true};
+
+ SUBCASE("7 + 7 km/h, the couplers catch") {
+ auto first{automatic_wagon(7.0, "first")};
+ auto second{automatic_wagon(7.0, "second")};
+ test::pair pair{first, end::front, second, end::front, 1.0};
+ CHECK(couple_during(pair, 3.0));
+ CHECK_FALSE(derailed(first));
+ CHECK_FALSE(derailed(second));
+ }
+ SUBCASE("8 + 8 km/h, the wagons bounce apart") {
+ auto first{automatic_wagon(8.0, "first")};
+ auto second{automatic_wagon(8.0, "second")};
+ test::pair pair{first, end::front, second, end::front, 1.0};
+ CHECK_FALSE(couple_during(pair, 3.0));
+ CHECK_FALSE(derailed(first));
+ CHECK_FALSE(derailed(second));
+ // both backwards, away from each other
+ CHECK(first.speed() < 0.0);
+ CHECK(second.speed() < 0.0);
+ }
+ SUBCASE("backing up, 8 + 8 km/h, the wagons bounce apart") {
+ auto first{automatic_wagon(-8.0, "first")};
+ auto second{automatic_wagon(-8.0, "second")};
+ test::pair pair{first, end::rear, second, end::rear, 1.0};
+ CHECK_FALSE(couple_during(pair, 3.0));
+ CHECK(first.speed() > 0.0);
+ CHECK(second.speed() > 0.0);
+ }
+ SUBCASE("15 + 15 km/h, both derail") {
+ auto first{automatic_wagon(15.0, "first")};
+ auto second{automatic_wagon(15.0, "second")};
+ test::pair pair{first, end::front, second, end::front, 1.0};
+ CHECK_FALSE(couple_during(pair, 5.0));
+ CHECK(derailed(first));
+ CHECK(derailed(second));
+ }
+}
+
+// the collision used to take the speed of a vehicle facing the other way as if it faced the same way, so a wagon
+// pushed away by the buffers of the vehicle hitting it head-on counted as running into it: the hit slowed it down,
+// and the hitter bounced back as from a wall
+
+TEST_CASE("couplers: a wagon hit head-on runs off the same as one hit from behind") {
+ // without automatic couplers or crash damage, the collision alone
+ crash_damage_setting const crashdamage{false};
+ auto speeds_after_hit = [](int StruckEnd) {
+ auto moving{vehicle{definition::load("wagon"), 20.0, "moving"}};
+ auto struck{vehicle{definition::load("wagon"), 0.0, "struck"}};
+ test::pair pair{moving, end::front, struck, StruckEnd, 0.5};
+ auto touched{false};
+ for (int i = 0; i < 300; ++i) {
+ pair.step();
+ touched = touched || pair.gap() < 0.0;
+ if (touched && pair.gap() > 0.3) {
+ break; // bounced off
+ }
+ }
+ REQUIRE(touched);
+ REQUIRE(pair.gap() > 0.3);
+ REQUIRE_FALSE(pair.coupled());
+ return std::make_pair(moving.speed(), struck.speed());
+ };
+
+ auto const [hitterfrombehind, struckfrombehind]{speeds_after_hit(end::rear)};
+ auto const [hitterheadon, struckheadon]{speeds_after_hit(end::front)};
+
+ // hit from behind, the struck wagon runs off forwards, faster than the hitter
+ CHECK(struckfrombehind > 10.0);
+ CHECK(hitterfrombehind < struckfrombehind);
+ // hit head-on, it runs off backwards, as fast
+ CHECK(struckheadon == doctest::Approx(-struckfrombehind).epsilon(0.02));
+ CHECK(hitterheadon == doctest::Approx(hitterfrombehind).epsilon(0.05));
+}
+
+// the other conditions of automatic coupling
+
+TEST_CASE("couplers: an automatic coupler doesn't catch a coupler of another type") {
+ crash_damage_setting const crashdamage{true};
+ auto moving{automatic_wagon(5.0, "moving")};
+ auto standing{vehicle{definition::load("wagon"), 0.0, "standing"}};
+ REQUIRE(standing->Couplers[end::rear].type() == TCouplerType::Screw);
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+
+ CHECK_FALSE(couple_during(pair, 3.0));
+}
+
+TEST_CASE("couplers: automatic couplers of different control systems couple without the control connection") {
+ crash_damage_setting const crashdamage{true};
+ auto const flag{coupling::coupler | coupling::brakehose | coupling::control};
+ auto moving{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 5.0, "moving"}};
+
+ SUBCASE("the same control system") {
+ auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 0.0, "standing"}};
+ REQUIRE(standing->Couplers[end::rear].control_type == "first");
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+ REQUIRE(couple_during(pair, 3.0));
+ CHECK(pair.coupling() == flag);
+ }
+ SUBCASE("a different one") {
+ auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "second"), 0.0, "standing"}};
+ REQUIRE(standing->Couplers[end::rear].control_type == "second");
+ test::pair pair{moving, end::front, standing, end::rear, 1.0};
+ REQUIRE(couple_during(pair, 3.0));
+ CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose));
+ }
+}
+
+TEST_CASE("couplers: the coupler force of vehicles facing each other lands on the couplers holding them") {
+ // the force a vehicle takes from its coupler, the other one takes back on its own coupler of the pair, whichever
+ // way the vehicles face; it used to land on the far end of the other vehicle when they faced each other.
+ // CForce runs along the axis of its own vehicle, so the two forces of the pair are opposite along the track: of
+ // opposite signs for vehicles facing the same way, of the same sign for vehicles facing each other
+ auto first{automatic_wagon(5.0, "first")};
+ auto second{automatic_wagon(0.0, "second")};
+
+ SUBCASE("facing each other") {
+ test::pair pair{first, end::front, second, end::front, 1.0};
+ pair.run(5.0);
+ REQUIRE(pair.coupled());
+
+ pair.step();
+ REQUIRE(second->Couplers[end::front].CForce != 0.0);
+ CHECK(first->Couplers[end::front].CForce == doctest::Approx(second->Couplers[end::front].CForce));
+ CHECK(first->Couplers[end::rear].CForce == 0.0); // nothing there
+ CHECK(second->Couplers[end::rear].CForce == 0.0);
+ }
+ SUBCASE("facing the same way") {
+ test::pair pair{first, end::front, second, end::rear, 1.0};
+ pair.run(5.0);
+ REQUIRE(pair.coupled());
+
+ pair.step();
+ REQUIRE(second->Couplers[end::rear].CForce != 0.0);
+ CHECK(first->Couplers[end::front].CForce == doctest::Approx(-second->Couplers[end::rear].CForce));
+ CHECK(first->Couplers[end::rear].CForce == 0.0);
+ CHECK(second->Couplers[end::front].CForce == 0.0);
+ }
+}
diff --git a/tests/unit/test_gauge_positions.cpp b/tests/unit/test_gauge_positions.cpp
new file mode 100644
index 000000000..791234e9d
--- /dev/null
+++ b/tests/unit/test_gauge_positions.cpp
@@ -0,0 +1,58 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "vehicle/gaugepositions.h"
+
+#include
+
+// the sounds of the positions of a cab control (MaSzyna-EU07/maszyna#83): a brake lever moved smoothly (Num3/Num9)
+// passes its positions instead of stopping at them, and sounds each one it reaches, as it does when put there
+
+namespace {
+
+// a brake lever with sounds at positions 0, 2 and 5; values in hundredths of a position
+std::map lever_sounds() {
+ return {{0, "release"}, {2, "running"}, {5, "service"}};
+}
+
+std::string reached(int const Previous, int const Desired) {
+ auto positions{lever_sounds()};
+ auto const position{gauge_positions::last_reached(positions, Previous, Desired)};
+ return position != positions.end() ? position->second : "";
+}
+
+} // namespace
+
+TEST_CASE("gauge positions: a lever put at a position sounds it") {
+ CHECK(reached(100, 200) == "running");
+ CHECK(reached(600, 500) == "service");
+}
+
+TEST_CASE("gauge positions: a lever moved smoothly past a position sounds it (MaSzyna-EU07/maszyna#83)") {
+ CHECK(reached(190, 205) == "running"); // moving up
+ CHECK(reached(510, 495) == "service"); // moving down
+}
+
+TEST_CASE("gauge positions: of the positions passed in one go the last one reached sounds") {
+ CHECK(reached(50, 520) == "service"); // up past 2 and 5
+ CHECK(reached(520, 10) == "running"); // down past 5 and 2, short of 0
+ CHECK(reached(520, 0) == "release");
+}
+
+TEST_CASE("gauge positions: moving between the positions or off one sounds nothing") {
+ CHECK(reached(210, 290) == "");
+ CHECK(reached(200, 230) == ""); // leaving a position isn't reaching it
+ CHECK(reached(200, 170) == "");
+}
+
+TEST_CASE("gauge positions: positions below zero count the same way") {
+ // a brake lever with the release position at -1
+ std::map positions{{-1, "release"}, {0, "running"}};
+ CHECK(gauge_positions::last_reached(positions, 50, -120)->second == "release"); // down past 0 and -1
+ CHECK(gauge_positions::last_reached(positions, -150, -90)->second == "release"); // up past -1
+}
+
+TEST_CASE("gauge positions: a control without position sounds reaches none") {
+ std::map positions;
+ CHECK(gauge_positions::last_reached(positions, 0, 500) == positions.end());
+}
diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp
new file mode 100644
index 000000000..18e5c5322
--- /dev/null
+++ b/tests/unit/test_horn.cpp
@@ -0,0 +1,121 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "vehicle.h"
+
+#include "vehicle/horn.h"
+
+// the horn keys of the cab: low tone (A) and high tone (shift+A), held to sound
+
+TEST_CASE("horn: a single lever for both tones sounds one tone at a time (eu07/maszyna#392)") {
+ auto signal{0};
+ signal = horn::pressed(signal, horn::low, true);
+ REQUIRE(signal == horn::low);
+
+ // the lever moved over to the high tone while the low tone key is still held
+ signal = horn::pressed(signal, horn::high, true);
+ CHECK(signal == horn::high);
+
+ // letting go of the low tone key leaves the high tone sounding
+ signal = horn::released(signal, horn::low);
+ CHECK(signal == horn::high);
+
+ signal = horn::released(signal, horn::high);
+ CHECK(signal == 0);
+}
+
+TEST_CASE("horn: separate buttons for the tones can sound both at once") {
+ auto signal{0};
+ signal = horn::pressed(signal, horn::low, false);
+ signal = horn::pressed(signal, horn::high, false);
+ CHECK(signal == (horn::low | horn::high));
+
+ signal = horn::released(signal, horn::low);
+ CHECK(signal == horn::high);
+}
+
+TEST_CASE("horn: releasing a tone leaves the other bits of the signal alone") {
+ auto const third{4}; // the third horn, operated separately
+ CHECK(horn::released(horn::low | third, horn::low) == third);
+ CHECK(horn::pressed(third, horn::high, true) == (horn::high | third));
+}
+
+// what the horns need to sound (eu07/maszyna#290): a pneumatic horn the air of the main reservoir, an electric one
+// the low voltage. the horn lever stays where the driver put it, only the horn is silent
+namespace {
+
+test::vehicle horn_vehicle(test::definition Definition) {
+ // a main reservoir of its own
+ return test::vehicle{Definition.set("Brake", "Vv", 1.0).set("Brake", "MinCP", 6.5).set("Brake", "MaxCP", 8.0)};
+}
+
+int const allhorns{horn::low | horn::high | 4};
+
+} // namespace
+
+TEST_CASE("horn: a pneumatic horn sounds on the air of the main reservoir only") {
+ auto vehicle{horn_vehicle(test::definition::load("wagon"))};
+ REQUIRE(vehicle->HornSupply == horn_supply::air); // the default
+
+ vehicle->Compressor = 6.5;
+ CHECK(vehicle->SoundingHorns(allhorns) == allhorns);
+ vehicle->Compressor = 0.0; // the reservoir is empty
+ CHECK(vehicle->SoundingHorns(allhorns) == 0);
+}
+
+TEST_CASE("horn: a vehicle without a main reservoir takes the horn air from the main pipe") {
+ test::vehicle vehicle{test::definition::load("wagon")};
+ REQUIRE(vehicle->VeselVolume == 0.0);
+
+ vehicle->ScndPipePress = 5.0;
+ CHECK(vehicle->SoundingHorns(horn::low) == horn::low);
+ vehicle->ScndPipePress = 0.0;
+ CHECK(vehicle->SoundingHorns(horn::low) == 0);
+}
+
+TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") {
+ auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))};
+ REQUIRE(vehicle->HornSupply == horn_supply::electric);
+ REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise
+
+ vehicle->Compressor = 0.0;
+ vehicle->Power24vIsAvailable = true;
+ CHECK(vehicle->SoundingHorns(allhorns) == allhorns);
+ vehicle->Power24vIsAvailable = false;
+ CHECK(vehicle->SoundingHorns(allhorns) == 0);
+}
+
+TEST_CASE("horn: the third horn can have a supply of its own, an electric horn of a diesel say") {
+ auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "Horn3Type", "Electric"))};
+ REQUIRE(vehicle->HornSupply == horn_supply::air);
+ REQUIRE(vehicle->Horn3Supply == horn_supply::electric);
+
+ vehicle->Compressor = 0.0;
+ vehicle->Power24vIsAvailable = true;
+ CHECK(vehicle->SoundingHorns(allhorns) == 4);
+ vehicle->Compressor = 6.5;
+ vehicle->Power24vIsAvailable = false;
+ CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high));
+}
+
+TEST_CASE("horn: a vehicle without any air, a road vehicle say, sounds its pneumatic horn as before") {
+ // no main reservoir and no main pipe connection at either end
+ test::vehicle vehicle{test::definition::load("wagon").set("BuffCoupl", "AllowedFlag", 3)};
+ REQUIRE(vehicle->VeselVolume == 0.0);
+ vehicle->ScndPipePress = 0.0;
+ CHECK(vehicle->SoundingHorns(allhorns) == allhorns);
+}
+
+TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") {
+ auto vehicle{horn_vehicle(test::definition::load("wagon"))};
+ vehicle->Compressor = TMoverParameters::HornMinPressure;
+ CHECK(vehicle->SoundingHorns(horn::low) == horn::low);
+ vehicle->Compressor = TMoverParameters::HornMinPressure - 0.01;
+ CHECK(vehicle->SoundingHorns(horn::low) == 0);
+}
+
+TEST_CASE("horn: an electric horn sounds on 110 V too") {
+ auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))};
+ vehicle->Power110vIsAvailable = true;
+ CHECK(vehicle->SoundingHorns(horn::high) == horn::high);
+}
diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp
new file mode 100644
index 000000000..79c419edf
--- /dev/null
+++ b/tests/unit/test_line_contactors.cpp
@@ -0,0 +1,59 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// the lamp of the open line contactors (eu07/maszyna#470): lit, it tells the start can be made, so it should go out
+// where the start is cut off, by the pressure switch at 2 bar in the brake cylinders, not at 1 bar already
+
+namespace {
+
+test::vehicle locomotive(bool const Pressureswitch) {
+ test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)};
+ vehicle->StLinFlag = false; // the line contactors open
+ vehicle->PipePress = 5.0;
+ return vehicle;
+}
+
+} // namespace
+
+TEST_CASE("line contactors: with a pressure switch the lamp goes out with the start cut off") {
+ auto vehicle{locomotive(true)};
+ REQUIRE(vehicle->HasControlPressureSwitch);
+
+ vehicle->BrakePress = 1.5; // braked, the start can still be made
+ vehicle->MotorConnectorsCheck(); // updates the pressure switch
+ REQUIRE_FALSE(vehicle->ControlPressureSwitch);
+ CHECK(vehicle->LineContactorsLampLit());
+
+ vehicle->BrakePress = 2.5; // the pressure switch cuts the start off
+ vehicle->MotorConnectorsCheck();
+ REQUIRE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+}
+
+TEST_CASE("line contactors: without a pressure switch the lamp goes out with the brakes applied, as before") {
+ auto vehicle{locomotive(false)};
+ vehicle->BrakePress = 0.5;
+ vehicle->MotorConnectorsCheck();
+ CHECK(vehicle->LineContactorsLampLit());
+ vehicle->BrakePress = 1.5;
+ vehicle->MotorConnectorsCheck();
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+}
+
+TEST_CASE("line contactors: closed contactors put the lamp out") {
+ auto vehicle{locomotive(true)};
+ vehicle->StLinFlag = true;
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+}
+
+TEST_CASE("line contactors: the ground relay and overload lamps follow the same rule") {
+ // all the lamps of the main circuit go out together, with the pressure switch where it's fitted
+ auto vehicle{locomotive(true)};
+ vehicle->BrakePress = 1.5;
+ vehicle->MotorConnectorsCheck();
+ CHECK(vehicle->MainCircuitLampsEnabled());
+ vehicle->BrakePress = 2.5;
+ vehicle->MotorConnectorsCheck();
+ CHECK_FALSE(vehicle->MainCircuitLampsEnabled());
+}
diff --git a/tests/unit/test_mirrors.cpp b/tests/unit/test_mirrors.cpp
new file mode 100644
index 000000000..7408eeaa5
--- /dev/null
+++ b/tests/unit/test_mirrors.cpp
@@ -0,0 +1,32 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "vehicle/mirrors.h"
+
+// the sounds of the mirrors (MaSzyna-EU07/maszyna#84, eu07/maszyna#322): a mirror sounds as it sets off, unfolding
+// or folding, and not again while it keeps moving the same way
+
+using mirror_moves::event;
+
+TEST_CASE("mirrors: a mirror sounds once as it sets off") {
+ mirror_moves::motion mirror;
+ CHECK(mirror.update(0.0) == event::none); // standing folded
+ CHECK(mirror.update(0.01) == event::unfolding);
+ CHECK(mirror.update(0.01) == event::none); // still unfolding
+ CHECK(mirror.update(0.0) == event::none); // unfolded
+ CHECK(mirror.update(-0.01) == event::folding);
+ CHECK(mirror.update(-0.01) == event::none);
+}
+
+TEST_CASE("mirrors: a mirror turned back halfway sounds the other way") {
+ mirror_moves::motion mirror;
+ REQUIRE(mirror.update(0.01) == event::unfolding);
+ CHECK(mirror.update(-0.01) == event::folding); // the vehicle got too fast while it was unfolding
+}
+
+TEST_CASE("mirrors: a mirror setting off again the same way sounds again") {
+ mirror_moves::motion mirror;
+ REQUIRE(mirror.update(0.01) == event::unfolding);
+ REQUIRE(mirror.update(0.0) == event::none); // stopped, the doors lost their permit say
+ CHECK(mirror.update(0.01) == event::unfolding);
+}
diff --git a/tests/unit/test_pumps.cpp b/tests/unit/test_pumps.cpp
new file mode 100644
index 000000000..2245e3eb8
--- /dev/null
+++ b/tests/unit/test_pumps.cpp
@@ -0,0 +1,52 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// the joint oil and fuel pump switch (MaSzyna-EU07/maszyna#81) works the pumps which aren't started automatically
+
+namespace {
+
+test::vehicle pumps_vehicle(std::string const &Fuelstart, std::string const &Oilstart) {
+ return test::vehicle{test::definition::load("wagon").set("Cntrl", "FuelStart", Fuelstart).set("Cntrl", "OilStart", Oilstart)};
+}
+
+// what the two-state joint switch does when pressed, as TTrain::OnCommand_oilfuelpumptoggle()
+void press_joint_switch(test::vehicle &Vehicle) {
+ auto const enable{false == Vehicle->OilFuelPumpsEnabled()};
+ Vehicle->FuelPumpSwitch(enable, range_t::local);
+ Vehicle->FuelPumpSwitchOff(false == enable, range_t::local);
+ Vehicle->OilPumpSwitch(enable, range_t::local);
+ Vehicle->OilPumpSwitchOff(false == enable, range_t::local);
+}
+
+} // namespace
+
+TEST_CASE("pumps: the joint switch turns both manual pumps on, then off") {
+ auto vehicle{pumps_vehicle("Manual", "Manual")};
+ REQUIRE_FALSE(vehicle->OilFuelPumpsEnabled());
+ press_joint_switch(vehicle);
+ CHECK(vehicle->FuelPump.is_enabled);
+ CHECK(vehicle->OilPump.is_enabled);
+ CHECK(vehicle->OilFuelPumpsEnabled());
+ press_joint_switch(vehicle);
+ CHECK_FALSE(vehicle->FuelPump.is_enabled);
+ CHECK_FALSE(vehicle->OilPump.is_enabled);
+}
+
+TEST_CASE("pumps: with one pump started automatically the joint switch still turns the other one off") {
+ auto vehicle{pumps_vehicle("Manual", "Automatic")};
+ press_joint_switch(vehicle);
+ REQUIRE(vehicle->FuelPump.is_enabled);
+ CHECK(vehicle->OilFuelPumpsEnabled()); // the switch shows on
+ press_joint_switch(vehicle);
+ CHECK_FALSE(vehicle->FuelPump.is_enabled);
+}
+
+TEST_CASE("pumps: with one manual pump on and the other off the joint switch turns both on") {
+ auto vehicle{pumps_vehicle("Manual", "Manual")};
+ vehicle->FuelPumpSwitch(true, range_t::local);
+ REQUIRE_FALSE(vehicle->OilFuelPumpsEnabled());
+ press_joint_switch(vehicle);
+ CHECK(vehicle->FuelPump.is_enabled);
+ CHECK(vehicle->OilPump.is_enabled);
+}
diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp
new file mode 100644
index 000000000..33a12f72d
--- /dev/null
+++ b/tests/unit/test_radio.cpp
@@ -0,0 +1,28 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// the radio works only switched on and with the low voltage (eu07/maszyna#429): its channel and volume buttons,
+// the calls and the radio-stop all ask RadioPowered()
+
+TEST_CASE("radio: a radio switched on with the low voltage works") {
+ test::vehicle vehicle{test::definition::load("wagon")};
+ vehicle->Radio = true;
+ SUBCASE("24 V") { vehicle->Power24vIsAvailable = true; }
+ SUBCASE("110 V") { vehicle->Power110vIsAvailable = true; }
+ CHECK(vehicle->RadioPowered());
+}
+
+TEST_CASE("radio: a radio switched off or without the low voltage doesn't") {
+ test::vehicle vehicle{test::definition::load("wagon")};
+ SUBCASE("switched off") {
+ vehicle->Radio = false;
+ vehicle->Power24vIsAvailable = true;
+ }
+ SUBCASE("batteries off") {
+ vehicle->Radio = true;
+ vehicle->Power24vIsAvailable = false;
+ vehicle->Power110vIsAvailable = false;
+ }
+ CHECK_FALSE(vehicle->RadioPowered());
+}
diff --git a/tests/unit/test_switches.cpp b/tests/unit/test_switches.cpp
new file mode 100644
index 000000000..72b1e47ce
--- /dev/null
+++ b/tests/unit/test_switches.cpp
@@ -0,0 +1,16 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// the kinds of the cab switches, given in the Switches: section of the vehicle definition
+
+TEST_CASE("switches: the train heating switch can spring back (MaSzyna-EU07/maszyna#85)") {
+ SUBCASE("impulse") {
+ test::vehicle vehicle{test::definition::load("cab_vehicle").set("Switches", "TrainHeating", "Impulse")};
+ CHECK(vehicle->HeatingSwitchImpulse); // whichever the case it's written in
+ }
+ SUBCASE("a plain switch by default") {
+ test::vehicle vehicle{test::definition::load("cab_vehicle")};
+ CHECK_FALSE(vehicle->HeatingSwitchImpulse);
+ }
+}
diff --git a/tests/unit/test_wheelslip.cpp b/tests/unit/test_wheelslip.cpp
new file mode 100644
index 000000000..9b39e82c6
--- /dev/null
+++ b/tests/unit/test_wheelslip.cpp
@@ -0,0 +1,62 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+using test::definition;
+using test::track;
+using test::vehicle;
+
+namespace {
+
+struct braking_result {
+ bool skidded{false}; // the wheels locked while braking
+ bool stopped{false}; // came (almost) to a stop on the braking rail
+};
+
+// brakes the wagon from 40 km/h on the Braking rail until it's (nearly) stopped, then has it stand on the
+// Standing one for 30 seconds
+braking_result brake_to_stop_then_stand(vehicle &Coach, track const &Braking, track const &Standing) {
+ braking_result result;
+ Coach.hold_brake_pipe(5.0);
+ Coach.run(5.0, Braking);
+ Coach.hold_brake_pipe(3.5); // service braking
+ // a skidding wagon brakes on the sliding adhesion only, give it time
+ for (auto step = 0; step < 60000; ++step) { // 600 s in 0.01 s steps
+ result.skidded |= Coach->SlippingWheels;
+ if (auto const speed{std::abs(Coach.speed())}; speed > 0.0 && speed < 0.1) {
+ // almost stopped; a skidding wagon is still skidding at this point
+ result.stopped = true;
+ break;
+ }
+ Coach.step(Braking);
+ }
+ Coach.run(30.0, Standing);
+ return result;
+}
+
+} // namespace
+
+// the engine doesn't let a stopped, braked vehicle slip (the Vel > 0.1 trap in TMoverParameters::ComputeTotalForce),
+// so a wagon which stopped in a skid should be no different from one which stopped without it. it used to stay
+// skidding instead, with its brakes capped by the sliding adhesion, and slid or crept away (eu07/maszyna#479)
+TEST_CASE("wheelslip: a wagon which stopped in a skid holds like one which stopped without it") {
+ track const dry{0.15, 0.0};
+ track const slippery{0.02, 0.0};
+ // held only by the brakes: the sliding adhesion on this rail is too low for the slope
+ track const slipperyslope{0.02, 0.08};
+
+ vehicle normal{definition::load("wagon"), 40.0};
+ auto const normalbraking{brake_to_stop_then_stand(normal, dry, slipperyslope)};
+ vehicle skidding{definition::load("wagon"), 40.0};
+ auto const skiddingbraking{brake_to_stop_then_stand(skidding, slippery, slipperyslope)};
+
+ // the test means something only when the braking went as planned
+ REQUIRE(normalbraking.stopped);
+ REQUIRE_FALSE(normalbraking.skidded);
+ REQUIRE(skiddingbraking.stopped);
+ REQUIRE(skiddingbraking.skidded);
+
+ CHECK(std::abs(normal.speed()) < 0.1);
+ CHECK(std::abs(skidding.speed()) < 0.1);
+ CHECK_FALSE(skidding->SlippingWheels);
+}
diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp
index 135c5c2fb..c0930d134 100644
--- a/tests/unit/vehicle.cpp
+++ b/tests/unit/vehicle.cpp
@@ -1,5 +1,6 @@
#include "stdafx.h"
#include "vehicle.h"
+#include "vehicle/DynObj.h"
#include
#include
@@ -159,6 +160,18 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons
}
void vehicle::step(track const &Track, double Dt) {
+ compute_forces(Dt);
+ compute_movement(Track, Dt, TLocation{0.0, 0.0, 0.0});
+}
+
+void vehicle::compute_forces(double Dt) {
+ if (m_pipepressure >= 0.0) {
+ m_mover->Pipe->CreatePress(m_pipepressure);
+ }
+ m_mover->ComputeTotalForce(Dt);
+}
+
+double vehicle::compute_movement(track const &Track, double Dt, TLocation const &Location) {
TTrackShape shape;
shape.Len = 1000.0;
shape.dHtrack = Track.gradient;
@@ -167,13 +180,8 @@ void vehicle::step(track const &Track, double Dt) {
param.friction = Track.friction;
param.CategoryFlag = 1;
TTractionParam const traction;
- TLocation const location{0.0, 0.0, 0.0};
TRotation const rotation{0.0, 0.0, 0.0};
- if (m_pipepressure >= 0.0) {
- m_mover->Pipe->CreatePress(m_pipepressure);
- }
- m_mover->ComputeTotalForce(Dt);
- m_mover->ComputeMovement(Dt, Dt, shape, param, traction, location, rotation);
+ return m_mover->ComputeMovement(Dt, Dt, shape, param, traction, Location, rotation);
}
void vehicle::run(double Seconds, track const &Track, double Dt) {
@@ -184,4 +192,88 @@ void vehicle::run(double Seconds, track const &Track, double Dt) {
}
}
+// the physics reaches the vehicle next to it through TDynamicObject::MoverParameters only (neighbour_data). the
+// tests can't make a TDynamicObject, whose constructor and members come with the rest of the engine, so the
+// neighbour is a zeroed block of its size with just that pointer set: enough for the physics, which reads nothing
+// else of it, and never used as a whole object
+static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__);
+
+namespace {
+
+std::vector make_standin(TMoverParameters &Mover) {
+ std::vector standin(sizeof(TDynamicObject)); // zeroed
+ reinterpret_cast(standin.data())->MoverParameters = &Mover; // NOSONAR see above
+ return standin;
+}
+
+TDynamicObject *as_neighbour(std::byte *Standin) {
+ return reinterpret_cast(Standin); // NOSONAR see above
+}
+
+} // namespace
+
+pair::pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap) {
+ auto const &first{First.mover()};
+ auto const &second{Second.mover()};
+ // the first vehicle in the middle, its FirstEnd towards the second one
+ m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == end::front ? 1.0 : -1.0, make_standin(First.mover())};
+ m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == end::front ? -1.0 : 1.0, make_standin(Second.mover())};
+}
+
+pair::~pair() {
+ for (auto const &placed : m_vehicles) {
+ // the vehicles outlive the pair, they mustn't point at its stand-ins
+ for (auto &neighbour : placed.owner->mover().Neighbours) {
+ neighbour = neighbour_data();
+ }
+ }
+}
+
+void pair::find_neighbours() {
+ // as TDynamicObject::update_neighbours()
+ for (auto const &placed : m_vehicles) {
+ placed.owner->mover().Loc = TLocation{placed.position, 0.0, 0.0};
+ }
+ for (int i = 0; i < 2; ++i) {
+ auto const &self{m_vehicles[i]};
+ auto &other{m_vehicles[1 - i]}; // its stand-in is what this one points at
+ auto &mover{self.owner->mover()};
+ auto const &othermover{other.owner->mover()};
+ auto &neighbour{mover.Neighbours[self.end]};
+ neighbour.vehicle = as_neighbour(other.standin.data());
+ neighbour.vehicle_end = other.end;
+ neighbour.distance = static_cast(TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[self.end].adapter_length -
+ othermover.Couplers[other.end].adapter_length);
+ mover.Neighbours[1 - self.end] = neighbour_data();
+ }
+}
+
+void pair::step(track const &Track, double Dt) {
+ find_neighbours();
+ for (auto const &placed : m_vehicles) {
+ placed.owner->compute_forces(Dt);
+ }
+ for (auto &placed : m_vehicles) {
+ placed.position += placed.heading * placed.owner->compute_movement(Track, Dt, TLocation{placed.position, 0.0, 0.0});
+ }
+}
+
+void pair::run(double Seconds, track const &Track, double Dt) {
+ // whole steps, as in vehicle::run()
+ auto const steps{std::lround(Seconds / Dt)};
+ for (long i = 0; i < steps; ++i) {
+ step(Track, Dt);
+ }
+}
+
+double pair::gap() const {
+ auto const &first{m_vehicles[0].owner->mover()};
+ auto const &second{m_vehicles[1].owner->mover()};
+ return std::abs(m_vehicles[1].position - m_vehicles[0].position) - 0.5 * (first.Dim.L + second.Dim.L);
+}
+
+int pair::coupling() const {
+ return m_vehicles[0].owner->mover().Couplers[m_vehicles[0].end].CouplingFlag;
+}
+
} // namespace test
diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h
index ad036839e..616e75d11 100644
--- a/tests/unit/vehicle.h
+++ b/tests/unit/vehicle.h
@@ -1,8 +1,10 @@
#pragma once
+#include
#include
#include
#include
+#include
#include
@@ -64,8 +66,57 @@ public:
double speed() const { return m_mover->V * 3.6; }
private:
+ friend class pair;
+
+ // the two halves of a step: the forces, taken by all the vehicles in the scene first, then the movement,
+ // the vehicle placed at Location. returns the distance travelled [m], positive forwards
+ void compute_forces(double Dt);
+ double compute_movement(track const &Track, double Dt, TLocation const &Location);
+
std::unique_ptr m_mover;
double m_pipepressure{-1.0};
};
+// two vehicles on a straight track, the FirstEnd of the first one facing the SecondEnd of the second one Gap metres
+// away (from coupler to coupler), with nothing else around. a step runs them the way the simulation runs the
+// vehicles of a scene (vehicle_table::update()): each one finds its neighbour, then both take the forces, the
+// coupler and buffer ones among them (CouplerForce()), then both move and handle the collisions (CollisionDetect()).
+// they couple and part on their own, as the couplers let them; the speed of each runs along its own axis
+// test::pair pair{moving, end::front, standing, end::rear, 1.0}; // 1 m apart
+// pair.run(5.0); // for 5 s
+// CHECK(pair.coupled());
+class pair {
+public:
+ pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap);
+ ~pair();
+ pair(pair const &) = delete;
+ pair &operator=(pair const &) = delete;
+ // the vehicles point at the stand-ins of the pair, which stay where they are
+ pair(pair &&) = delete;
+ pair &operator=(pair &&) = delete;
+
+ // advances both vehicles by one step of Dt
+ void step(track const &Track = {}, double Dt = 0.01);
+ // advances both vehicles by Seconds in steps of Dt
+ void run(double Seconds, track const &Track = {}, double Dt = 0.01);
+ // distance between the facing couplers [m], negative while the buffers are pressed in
+ double gap() const;
+ // type of the coupling between the vehicles, coupling::faux when they aren't coupled
+ int coupling() const;
+ bool coupled() const { return coupling() != coupling::faux; }
+
+private:
+ struct placement {
+ vehicle *owner{nullptr};
+ int end{0}; // the end facing the other vehicle
+ double position{0.0}; // of the middle of the vehicle along the track [m]
+ double heading{1.0}; // +1 when the vehicle runs forwards towards the growing position, -1 otherwise
+ std::vector standin; // what the other vehicle sees as this one, see vehicle.cpp
+ };
+
+ void find_neighbours();
+
+ std::array m_vehicles;
+};
+
} // namespace test
diff --git a/utilities/translation.cpp b/utilities/translation.cpp
index b1db12275..c0dbeb1a0 100644
--- a/utilities/translation.cpp
+++ b/utilities/translation.cpp
@@ -218,6 +218,7 @@ std::string locale::label_cab_control(std::string const &Label)
{ "watercircuitslink_sw:", STRN("water circuits link") },
{ "fuelpump_sw:", STRN("fuel pump") },
{ "oilpump_sw:", STRN("oil pump") },
+ { "oilfuelpump_sw:", STRN("oil and fuel pumps") },
{ "motorblowersfront_sw:", STRN("motor blowers A") },
{ "motorblowersrear_sw:", STRN("motor blowers B") },
{ "motorblowersalloff_sw:", STRN("all motor blowers") },
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5beac4c1e..08f0c0d24 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -30,6 +30,8 @@ http://mozilla.org/MPL/2.0/.
#include "world/station.h"
#include "input/keyboardinput.h"
+#include
+
#define LOGVELOCITY 0
#define LOGORDERS 1
#define LOGSTOPS 1
@@ -1093,10 +1095,9 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub
if (Point.fDist < passengerstopmaxdistance * 0.5 ) {
// zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora)
#if LOGSTOPS
- WriteLog(
- pVehicle->asName + " as " + TrainParams.TrainName
- + ": at " + std::to_string(simulation::Time.data().wHour) + ":" + std::to_string(simulation::Time.data().wMinute)
- + " passed " + asNextStop); // informacja
+ WriteLog(std::format(
+ "{} as {}: at {}:{} passed {}",
+ pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja
#endif
// przy jakim dystansie (stanie licznika) ma przesunąć na następny postój
fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength;
@@ -1253,10 +1254,9 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub
TrainParams.StationIndexInc(); // przejście do następnej
asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania
#if LOGSTOPS
- WriteLog(
- pVehicle->asName + " as " + TrainParams.TrainName
- + ": at " + std::to_string(simulation::Time.data().wHour) + ":" + std::to_string(simulation::Time.data().wMinute)
- + " next " + asNextStop); // informacja
+ WriteLog(std::format(
+ "{} as {}: at {}:{} next {}",
+ pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja
#endif
// update consist weight, brake settings and ai braking tables
// NOTE: this calculation is expected to run after completing loading/unloading
@@ -1297,13 +1297,16 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub
else {
// jeśli dojechaliśmy do końca rozkładu
#if LOGSTOPS
- WriteLog(
- pVehicle->asName + " as " + TrainParams.TrainName
- + ": at " + std::to_string(simulation::Time.data().wHour) + ":" + std::to_string(simulation::Time.data().wMinute)
- + " end of route."); // informacja
+ WriteLog(std::format(
+ "{} as {}: at {}:{} end of route.",
+ pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja
#endif
asNextStop = TrainParams.NextStop(); // informacja o końcu trasy
TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu
+ // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają)
+ for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
+ vehicle->DestinationClear();
+ }
// ma nie podjeżdżać pod W4 i ma je pomijać
iDrivigFlags &= ~moveStopCloser;
if( false == TestFlag( iDrivigFlags, movePushPull ) ) {
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index 32ba307f7..c6793e454 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -4150,6 +4150,8 @@ bool TDynamicObject::Update(double dt, double dt1)
// mirrors
+ auto const mirrorleft { dMirrorMoveL };
+ auto const mirrorright { dMirrorMoveR };
if( MoverParameters->Vel > MoverParameters->MirrorVelClose
|| MoverParameters->CabActive == 0 && activation::mirrors
|| MoverParameters->MirrorForbidden ) {
@@ -4180,6 +4182,8 @@ bool TDynamicObject::Update(double dt, double dt1)
dMirrorMoveR + 1.0 * dt1 );
}
}
+ play_mirror_sounds( side::left, m_mirrormotion[ side::left ].update( dMirrorMoveL - mirrorleft ) );
+ play_mirror_sounds( side::right, m_mirrormotion[ side::right ].update( dMirrorMoveR - mirrorright ) );
// compartment lights
// if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself
@@ -4825,12 +4829,13 @@ void TDynamicObject::RenderSounds() {
// horns
{
- // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active
- auto const warningsignal { (
- MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ?
+ // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active;
+ // the horns without the air or the voltage they need stay silent
+ auto const warningsignal { MoverParameters->SoundingHorns(
+ ( MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ?
MoverParameters->EmergencyBrakeWarningSignal :
0 )
- | MoverParameters->WarningSignal };
+ | MoverParameters->WarningSignal ) };
if( TestFlag( warningsignal, 1 ) ) {
sHorn1.play( sound_flags::exclusive | sound_flags::looping );
@@ -6363,6 +6368,19 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co
}
}
+ else if( token == "mirroropen:" || token == "mirrorclose:" ) {
+ sound_source soundtemplate { sound_placement::general };
+ soundtemplate.deserialize( parser, sound_type::single );
+ soundtemplate.owner( this );
+ for( auto &mirror : m_mirrorsounds ) {
+ // apply configuration to all defined mirrors, but preserve their individual offsets
+ auto &sound { token == "mirroropen:" ? mirror.unfold : mirror.fold };
+ auto const mirroroffset { sound.offset() };
+ sound = soundtemplate;
+ sound.offset( mirroroffset );
+ }
+ }
+
else if( token == "doorstepclose:" ) {
sound_source soundtemplate { sound_placement::general };
soundtemplate.deserialize( parser, sound_type::single );
@@ -6576,6 +6594,27 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co
}
}
+ else if( token == "mirrors:" ) {
+ // a list of offsets along vehicle's z-axis of the mirror pairs, one at each cab; followed with "end"
+ while( (token = parser.getToken()) != ""
+ && token != "end" ) {
+ // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre
+ auto const offset { std::atof( token.c_str() ) * -1.f };
+ mirror_sounds mirror;
+ mirror.end = offset >= 0.f ? end::front : end::rear;
+ for( auto const mirrorside : { side::left, side::right } ) {
+ auto const location { glm::vec3 {
+ MoverParameters->Dim.W * ( mirrorside == side::left ? 0.5f : -0.5f ),
+ MoverParameters->Dim.H * 0.5f,
+ offset } };
+ mirror.placement = mirrorside;
+ mirror.unfold.offset( location );
+ mirror.fold.offset( location );
+ m_mirrorsounds.emplace_back( mirror );
+ }
+ }
+ }
+
else if( token == "tractionmotors:" ) {
// a list of offsets along vehicle's z-axis; followed with "end"
while( (token = parser.getToken()) != ""
@@ -7794,7 +7833,29 @@ int TDynamicObject::RouteWish(TTrack *tr)
return Mechanik ? Mechanik->CrossRoute(tr) : 0; // wg AI albo prosto
};
-void TDynamicObject::DestinationSet(std::string to, std::string numer) {
+void TDynamicObject::play_mirror_sounds( side const Side, mirror_moves::event const Event ) {
+
+ if( Event == mirror_moves::event::none ) { return; }
+ // as UpdateMirror(), only the mirrors of the occupied cab move
+ if( MoverParameters->CabOccupied == 0 ) { return; }
+ auto const cabend { MoverParameters->CabOccupied > 0 ? end::front : end::rear };
+ for( auto &mirror : m_mirrorsounds ) {
+ if( mirror.placement != Side || mirror.end != cabend ) { continue; }
+ auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold };
+ auto &other { Event == mirror_moves::event::unfolding ? mirror.fold : mirror.unfold };
+ other.stop();
+ sound.play( sound_flags::exclusive );
+ }
+}
+
+void TDynamicObject::DestinationClear() {
+
+ if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed
+ // update_destinations() shows the blank sign in place of the missing destination
+ DestinationSign.destination = null_handle;
+}
+
+void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) {
// ustawienie stacji docelowej oraz wymiennej tekstury 4, jeśli istnieje plik
// w zasadzie, to każdy wagon mógłby mieć inną stację docelową
// zwłaszcza w towarowych, pod kątem zautomatyzowania maewrów albo pracy górki
@@ -7823,6 +7884,15 @@ void TDynamicObject::DestinationSet(std::string to, std::string numer) {
if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture
if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother
+ auto const trainname { [this]() -> std::string {
+ if( ctOwner != nullptr ) { return ctOwner->TrainName(); }
+ if( Mechanik != nullptr ) { return Mechanik->TrainName(); }
+ return "none"; } }; // shouldn't get here but, eh
+ auto const instance { [this]() -> std::string {
+ if( DestinationSign.instancing == "name" ) { return MoverParameters->Name; }
+ if( DestinationSign.instancing == "type" ) { return MoverParameters->TypeName; }
+ return "none"; } };
+
std::string signrequest {
"make:"
+ DestinationSign.script
@@ -7834,17 +7904,10 @@ void TDynamicObject::DestinationSet(std::string to, std::string numer) {
ctOwner->Vehicle()->MoverParameters->Name ) // owned vehicle, safer to point to owner as carriages can have identical names
// basic instancing string
// NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys
- + "&_id1=" + (
- ctOwner != nullptr ? ctOwner->TrainName() :
- Mechanik != nullptr ? Mechanik->TrainName() :
- "none" ) }; // shouldn't get here but, eh
+ + "&_id1=" + trainname() };
// TBD, TODO: replace instancing with support for variables in extra parameters string?
if( false == DestinationSign.instancing.empty() ) {
- signrequest +=
- "&_id2=" + (
- DestinationSign.instancing == "name" ? MoverParameters->Name :
- DestinationSign.instancing == "type" ? MoverParameters->TypeName :
- "none" );
+ signrequest += "&_id2=" + instance();
}
// optionl extra parameters
if( false == DestinationSign.parameters.empty() ) {
diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h
index 36335a320..2d9636b2f 100644
--- a/vehicle/DynObj.h
+++ b/vehicle/DynObj.h
@@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/.
#include "interfaces/ITexture.h"
#include "audio/sound.h"
#include "world/Spring.h"
+#include "vehicle/mirrors.h"
#include
@@ -393,6 +394,13 @@ private:
side placement {};
};
+ struct mirror_sounds {
+ sound_source unfold { sound_placement::general };
+ sound_source fold { sound_placement::general };
+ side placement {};
+ int end {}; // of the vehicle, the mirror moves with the cab at this end occupied
+ };
+
struct exchange_sounds {
sound_source loading { sound_placement::general };
sound_source unloading { sound_placement::general };
@@ -567,6 +575,8 @@ private:
std::vector m_pantographsounds; // typically 2 but can be less (or more?)
std::vector m_doorsounds; // can expect symmetrical arrangement, but don't count on it
bool m_doorlocks { false }; // sound helper, current state of door locks
+ std::vector m_mirrorsounds;
+ std::array m_mirrormotion; // indexed by side: right, left
sound_source sHorn1 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE };
sound_source sHorn2 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE };
sound_source sHorn3 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE };
@@ -703,6 +713,8 @@ private:
void Move(double fDistance);
void FastMove(double fDistance);
void RenderSounds();
+ // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event
+ void play_mirror_sounds( side const Side, mirror_moves::event const Event );
inline glm::dvec3 GetPosition() const {
return vPosition; };
// converts location from vehicle coordinates frame to world frame
@@ -815,7 +827,9 @@ private:
void ParamSet(int what, int into);
// zapytanie do AI, po którym segmencie skrzyżowania jechać
int RouteWish(TTrack *tr);
- void DestinationSet(std::string to, std::string numer);
+ void DestinationSet(std::string const &to, std::string const &numer);
+ // blanks electronic destination sign at the end of the service; physical signs stay until changed
+ void DestinationClear();
material_handle DestinationFind( std::string Destination );
void OverheadTrack(float o);
glm::dvec3 get_future_movement() const;
diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp
index d7a41062e..af8e9a060 100644
--- a/vehicle/Gauge.cpp
+++ b/vehicle/Gauge.cpp
@@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "vehicle/Gauge.h"
+#include "vehicle/gaugepositions.h"
#include "utilities/parser.h"
#include "model/Model3d.h"
#include "vehicle/DynObj.h"
@@ -302,42 +303,37 @@ bool
TGauge::UpdateValue( float fNewDesired ) {
auto const desiredtimes100 = static_cast( std::round( 100.0 * fNewDesired ) );
- if( desiredtimes100 == static_cast( std::round( 100.0 * m_targetvalue ) ) ) {
+ auto const previoustimes100 = static_cast( std::round( 100.0 * m_targetvalue ) );
+ if( desiredtimes100 == previoustimes100 ) {
return true;
}
m_targetvalue = fNewDesired;
- // if there's any sound associated with new requested value, play it
- // check value-specific table first...
- if( auto const fullinteger { desiredtimes100 % 100 == 0 }; fullinteger ) {
- // filter out values other than full integers
- auto const lookup = m_soundfxvalues.find( desiredtimes100 / 100 );
- if( lookup != m_soundfxvalues.end() ) {
- lookup->second.play();
- return true;
- }
- }
- else {
+ if( desiredtimes100 % 100 != 0 ) {
// toggle the control to continous range/exclusive sound mode from now on
m_soundtype = sound_flags::exclusive;
}
+ // if there's any sound associated with a position reached on the way to the new requested value, play it
+ // check value-specific table first...
+ if( auto const reached = gauge_positions::last_reached( m_soundfxvalues, previoustimes100, desiredtimes100 );
+ reached != m_soundfxvalues.end() ) {
+ reached->second.play();
+ return true;
+ }
// ...and if there isn't any, fall back on the basic set...
// HACK: crude way to discern controls with continuous and quantized value range
- if( auto const currentvalue = GetValue(); currentvalue < fNewDesired ) {
+ auto const currentvalue = GetValue();
+ if( currentvalue < fNewDesired && false == m_soundfxincrease.empty() ) {
// shift up
- if( false == m_soundfxincrease.empty() ) {
- m_soundfxincrease.play( m_soundtype );
- return true;
- }
+ m_soundfxincrease.play( m_soundtype );
+ return true;
}
- else if( currentvalue > fNewDesired ) {
+ if( currentvalue > fNewDesired && false == m_soundfxdecrease.empty() ) {
// shift down
- if( false == m_soundfxdecrease.empty() ) {
- m_soundfxdecrease.play( m_soundtype );
- return true;
- }
+ m_soundfxdecrease.play( m_soundtype );
+ return true;
}
return false; // no suitable sound was found
-};
+}
void TGauge::PutValue(float fNewDesired)
{ // McZapkie-281102: natychmiastowe wpisanie wartosci
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index f0b2367f7..201b8972f 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "vehicle/Train.h"
+#include "vehicle/horn.h"
#include "utilities/Globals.h"
#include "simulation/simulation.h"
@@ -340,6 +341,7 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = {
{user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable},
{user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable},
{user_command::oilpumptoggle, &TTrain::OnCommand_oilpumptoggle},
+ {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle},
{user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable},
{user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable},
{user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle},
@@ -3995,6 +3997,37 @@ void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command
}
}
+void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Command)
+{
+ if (Command.action == GLFW_REPEAT)
+ {
+ return;
+ }
+
+ auto *vehicle{Train->mvControlled};
+ if (Train->ggOilFuelPumpButton.type() == TGaugeType::push)
+ {
+ // impulse switch, as the separate ones: held to start both pumps
+ auto const pressed{Command.action == GLFW_PRESS};
+ Train->ggOilFuelPumpButton.UpdateValue(pressed ? 1.0 : 0.0, Train->dsbSwitch);
+ vehicle->FuelPumpSwitch(pressed);
+ vehicle->OilPumpSwitch(pressed);
+ return;
+ }
+ // two-state switch, only cares about press events
+ if (Command.action != GLFW_PRESS)
+ {
+ return;
+ }
+ // both pumps go off if both were on, otherwise both go on; a pump started automatically doesn't take part
+ auto const enable{false == vehicle->OilFuelPumpsEnabled()};
+ Train->ggOilFuelPumpButton.UpdateValue(enable ? 1.0 : 0.0, Train->dsbSwitch);
+ vehicle->FuelPumpSwitch(enable);
+ vehicle->FuelPumpSwitchOff(false == enable);
+ vehicle->OilPumpSwitch(enable);
+ vehicle->OilPumpSwitchOff(false == enable);
+}
+
void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command)
{
@@ -6605,7 +6638,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command)
OnCommand_heatingdisable(Train, Command);
}
}
- else if (Command.action == GLFW_RELEASE && Train->ggTrainHeatingButton.type() == TGaugeType::push)
+ else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->mvOccupied->HeatingSwitchImpulse))
{
// impulse switch
// visual feedback
@@ -6623,6 +6656,11 @@ void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command)
// visual feedback
Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch);
}
+ else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse)
+ {
+ // the switch springs back to the middle
+ Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch);
+ }
}
void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command)
@@ -6632,8 +6670,21 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command
{
Train->mvOccupied->HeatingSwitch(false);
- // visual feedback
- Train->ggTrainHeatingButton.UpdateValue(Train->ggTrainHeatingButton.type() == TGaugeType::push ? 1.0 : 0.0, Train->dsbSwitch);
+ // visual feedback: an impulse switch is pushed the other way, down
+ auto position{0.0};
+ if (Train->mvOccupied->HeatingSwitchImpulse)
+ {
+ position = -1.0;
+ }
+ else if (Train->ggTrainHeatingButton.type() == TGaugeType::push)
+ {
+ position = 1.0;
+ }
+ Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch);
+ }
+ else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse)
+ {
+ Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch);
}
}
@@ -7841,16 +7892,10 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman
if (Command.action == GLFW_PRESS)
{
// only need to react to press, sound will continue until stopped
- if (false == TestFlag(Train->mvOccupied->WarningSignal, 1))
+ if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::low))
{
// turn on
- Train->mvOccupied->WarningSignal |= 1;
- /*
- if( true == TestFlag( Train->mvOccupied->WarningSignal, 2 ) ) {
- // low and high horn are treated as mutually exclusive
- Train->mvControlled->WarningSignal &= ~2;
- }
- */
+ Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::low, Train->has_single_horn_lever());
// visual feedback
Train->ggHornButton.UpdateValue(-1.0);
Train->ggHornLowButton.UpdateValue(1.0);
@@ -7859,13 +7904,13 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman
else if (Command.action == GLFW_RELEASE)
{
// turn off
- /*
- // NOTE: we turn off both low and high horn, due to unreliability of release event when shift key is involved
- Train->mvOccupied->WarningSignal &= ~( 1 | 2 );
- */
- Train->mvOccupied->WarningSignal &= ~1;
+ Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::low);
// visual feedback
- Train->ggHornButton.UpdateValue(0.0);
+ if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::high)))
+ {
+ // leave the single lever alone if it was moved to the other tone in the meantime
+ Train->ggHornButton.UpdateValue(0.0);
+ }
Train->ggHornLowButton.UpdateValue(0.0);
}
}
@@ -7885,16 +7930,10 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma
if (Command.action == GLFW_PRESS)
{
// only need to react to press, sound will continue until stopped
- if (false == TestFlag(Train->mvOccupied->WarningSignal, 2))
+ if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::high))
{
// turn on
- Train->mvOccupied->WarningSignal |= 2;
- /*
- if( true == TestFlag( Train->mvOccupied->WarningSignal, 1 ) ) {
- // low and high horn are treated as mutually exclusive
- Train->mvControlled->WarningSignal &= ~1;
- }
- */
+ Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::high, Train->has_single_horn_lever());
// visual feedback
Train->ggHornButton.UpdateValue(1.0);
Train->ggHornHighButton.UpdateValue(1.0);
@@ -7903,13 +7942,13 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma
else if (Command.action == GLFW_RELEASE)
{
// turn off
- /*
- // NOTE: we turn off both low and high horn, due to unreliability of release event when shift key is involved
- Train->mvOccupied->WarningSignal &= ~( 1 | 2 );
- */
- Train->mvOccupied->WarningSignal &= ~2;
+ Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::high);
// visual feedback
- Train->ggHornButton.UpdateValue(0.0);
+ if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::low)))
+ {
+ // leave the single lever alone if it was moved to the other tone in the meantime
+ Train->ggHornButton.UpdateValue(0.0);
+ }
Train->ggHornHighButton.UpdateValue(0.0);
}
}
@@ -7953,12 +7992,7 @@ void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command)
return;
}
- // NOTE: we ignore the lack of 3d model to allow system reset after receiving radio-stop signal
- /*
- if( false == Train->m_controlmapper.contains( "radio_sw:" ) ) {
- return;
- }
- */
+ // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal
// only reacting to press, so the sound can loop uninterrupted
if (false == Train->mvOccupied->Radio)
{
@@ -8003,9 +8037,13 @@ void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &C
if (Command.action == GLFW_PRESS)
{
- command_data newCommand = Command;
- newCommand.param1 = Train->RadioChannel() + 1;
- OnCommand_radiochannelset(Train, newCommand);
+ // the channel buttons of a radio switched off or without power do nothing
+ if (Train->mvOccupied->RadioPowered())
+ {
+ command_data newCommand = Command;
+ newCommand.param1 = Train->RadioChannel() + 1;
+ OnCommand_radiochannelset(Train, newCommand);
+ }
Train->ggRadioChannelNext.UpdateValue(1.0);
}
@@ -8021,9 +8059,12 @@ void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &C
if (Command.action == GLFW_PRESS)
{
- command_data newCommand = Command;
- newCommand.param1 = Train->RadioChannel() - 1;
- OnCommand_radiochannelset(Train, newCommand);
+ if (Train->mvOccupied->RadioPowered())
+ {
+ command_data newCommand = Command;
+ newCommand.param1 = Train->RadioChannel() - 1;
+ OnCommand_radiochannelset(Train, newCommand);
+ }
Train->ggRadioChannelPrevious.UpdateValue(1.0);
}
@@ -8049,7 +8090,7 @@ void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command)
if (Command.action == GLFW_PRESS)
{
- if (true == Train->mvOccupied->Radio && (Train->mvOccupied->Power24vIsAvailable || Train->mvOccupied->Power110vIsAvailable))
+ if (Train->mvOccupied->RadioPowered())
{
simulation::Region->RadioStop(Train->Dynamic()->GetPosition());
}
@@ -8067,7 +8108,7 @@ void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Comman
{
if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0)
{
- if (true == Train->mvOccupied->Radio && (Train->mvOccupied->Power24vIsAvailable || Train->mvOccupied->Power110vIsAvailable))
+ if (Train->mvOccupied->RadioPowered())
{
simulation::Region->RadioStop(Train->Dynamic()->GetPosition());
}
@@ -8090,7 +8131,7 @@ void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command)
if (Command.action == GLFW_PRESS)
{
- if (Train->RadioChannel() == 10 && true == Train->mvOccupied->Radio && (Train->mvOccupied->Power24vIsAvailable || Train->mvOccupied->Power110vIsAvailable))
+ if (Train->RadioChannel() == 10 && Train->mvOccupied->RadioPowered())
{
Train->Dynamic()->RadioStop();
}
@@ -8108,7 +8149,7 @@ void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command
{
if (Command.action == GLFW_PRESS)
{
- if (Train->RadioChannel() != 10 && true == Train->mvOccupied->Radio && (Train->mvOccupied->Power24vIsAvailable || Train->mvOccupied->Power110vIsAvailable))
+ if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered())
{
simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition());
}
@@ -8127,7 +8168,7 @@ void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command
if (Command.action == GLFW_PRESS)
{
- if (Train->RadioChannel() != 10 && true == Train->mvOccupied->Radio && (Train->mvOccupied->Power24vIsAvailable || Train->mvOccupied->Power110vIsAvailable))
+ if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered())
{
simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition());
}
@@ -8146,9 +8187,13 @@ void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Co
if (Command.action == GLFW_PRESS)
{
- command_data newCommand = Command;
- newCommand.param1 = Train->m_radiovolume + 0.125;
- OnCommand_radiovolumeset(Train, newCommand);
+ // so do the volume buttons
+ if (Train->mvOccupied->RadioPowered())
+ {
+ command_data newCommand = Command;
+ newCommand.param1 = Train->m_radiovolume + 0.125;
+ OnCommand_radiovolumeset(Train, newCommand);
+ }
Train->ggRadioVolumeNext.UpdateValue(1.0);
}
else if (Command.action == GLFW_RELEASE)
@@ -8163,9 +8208,12 @@ void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Co
if (Command.action == GLFW_PRESS)
{
- command_data newCommand = Command;
- newCommand.param1 = Train->m_radiovolume - 0.125;
- OnCommand_radiovolumeset(Train, newCommand);
+ if (Train->mvOccupied->RadioPowered())
+ {
+ command_data newCommand = Command;
+ newCommand.param1 = Train->m_radiovolume - 0.125;
+ OnCommand_radiovolumeset(Train, newCommand);
+ }
Train->ggRadioVolumePrevious.UpdateValue(1.0);
}
else if (Command.action == GLFW_RELEASE)
@@ -8931,9 +8979,9 @@ bool TTrain::Update(double const Deltatime)
btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck());
btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04
- btLampkaStyczn.Turn(!mvControlled->StLinFlag && !mvControlled->ControlPressureSwitch && mvControlled->BrakePress < 1.0); // mozna prowadzic rozruch
- btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && !mvControlled->ControlPressureSwitch && mvControlled->BrakePress < 1.0); // relay is off and needs a reset
- btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && !mvControlled->ControlPressureSwitch && mvControlled->BrakePress < 1.0); // relay is off and needs a reset
+ btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch
+ btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset
+ btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset
btLampkaUkrotnienie.Turn(TestFlag(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag, control));
btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania
// TODO: youBy wyciągnąć flagę wysokiego stopnia
@@ -9180,14 +9228,7 @@ bool TTrain::Update(double const Deltatime)
btLampkaOporyB.Turn(mover->ResistorsFlagCheck());
btLampkaBezoporowaB.Turn(true == mover->ResistorsFlagCheck() || mover->MainCtrlActualPos == 0); // do EU04
- if (mover->StLinFlag || mover->ControlPressureSwitch)
- {
- btLampkaStycznB.Turn(false);
- }
- else if (mover->BrakePress < 1.0)
- {
- btLampkaStycznB.Turn(true); // mozna prowadzic rozruch
- }
+ btLampkaStycznB.Turn(mover->LineContactorsLampLit()); // mozna prowadzic rozruch
// hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim
if (mover->SlippingWheels)
{
@@ -9583,6 +9624,7 @@ bool TTrain::Update(double const Deltatime)
ggWaterCircuitsLinkButton.Update();
ggFuelPumpButton.Update();
ggOilPumpButton.Update();
+ ggOilFuelPumpButton.Update();
ggMotorBlowersFrontButton.Update();
ggMotorBlowersRearButton.Update();
ggMotorBlowersAllOffButton.Update();
@@ -10106,7 +10148,7 @@ void TTrain::update_sounds_radio()
std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); });
}
// adjust audibility of remaining messages based on current radio conditions
- auto const radioenabled{true == mvOccupied->Radio && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)};
+ auto const radioenabled{mvOccupied->RadioPowered()};
for (auto const &[messagechannel, messagesound] : m_radiomessages)
{
auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0};
@@ -10893,7 +10935,7 @@ void TTrain::radio_message(sound_source *Message, int const Channel)
m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound));
// assign sound to the template and play it
auto &message = *m_radiomessages.back().second.get();
- auto const radioenabled{true == mvOccupied->Radio && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)};
+ auto const radioenabled{mvOccupied->RadioPowered()};
auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0};
message.copy_sounds(*Message).gain(static_cast(volume)).play();
}
@@ -11081,6 +11123,7 @@ void TTrain::clear_cab_controls()
ggWaterCircuitsLinkButton.Clear();
ggFuelPumpButton.Clear();
ggOilPumpButton.Clear();
+ ggOilFuelPumpButton.Clear();
ggMotorBlowersFrontButton.Clear();
ggMotorBlowersRearButton.Clear();
ggMotorBlowersAllOffButton.Clear();
@@ -11362,7 +11405,7 @@ void TTrain::set_cab_controls(int const Cab)
ggDoorStepButton.PutValue(mvOccupied->Doors.step_enabled ? 1.f : 0.f);
}
// heating
- if (false == ggTrainHeatingButton.is_push())
+ if (false == ggTrainHeatingButton.is_push() && false == mvOccupied->HeatingSwitchImpulse)
{
ggTrainHeatingButton.PutValue(mvControlled->Heating ? 1.f : 0.f);
}
@@ -11415,6 +11458,11 @@ void TTrain::set_cab_controls(int const Cab)
{
ggOilPumpButton.PutValue(mvControlled->OilPump.is_enabled ? 1.f : 0.f);
}
+ // joint oil and fuel pump
+ if (ggOilFuelPumpButton.type() != TGaugeType::push)
+ {
+ ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f);
+ }
// traction motor fans
if (ggMotorBlowersFrontButton.type() != TGaugeType::push)
{
@@ -11742,6 +11790,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con
{"watercircuitslink_sw:", ggWaterCircuitsLinkButton},
{"fuelpump_sw:", ggFuelPumpButton},
{"oilpump_sw:", ggOilPumpButton},
+ {"oilfuelpump_sw:", ggOilFuelPumpButton},
{"oilpressb:", ggOilPressB},
{"motorblowersfront_sw:", ggMotorBlowersFrontButton},
{"motorblowersrear_sw:", ggMotorBlowersRearButton},
diff --git a/vehicle/Train.h b/vehicle/Train.h
index 4fc11dc2c..009b349b4 100644
--- a/vehicle/Train.h
+++ b/vehicle/Train.h
@@ -195,6 +195,9 @@ class TTrain {
bool initialize_button(cParser &Parser, std::string const &Label, int const Cabindex);
// helper, returns true for EMU with oerlikon brake
bool is_eztoer() const;
+ // helper, returns true if both horn tones are operated with the same lever, without separate low and high tone buttons
+ bool has_single_horn_lever() const {
+ return ggHornButton.SubModel != nullptr && ggHornLowButton.SubModel == nullptr && ggHornHighButton.SubModel == nullptr; }
// locates nearest vehicle belonging to the consist
TDynamicObject *find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const;
// mover master controller to specified position
@@ -339,6 +342,7 @@ class TTrain {
static void OnCommand_fuelpumpenable( TTrain *Train, command_data const &Command );
static void OnCommand_fuelpumpdisable( TTrain *Train, command_data const &Command );
static void OnCommand_oilpumptoggle( TTrain *Train, command_data const &Command );
+ static void OnCommand_oilfuelpumptoggle( TTrain *Train, command_data const &Command );
static void OnCommand_oilpumpenable( TTrain *Train, command_data const &Command );
static void OnCommand_oilpumpdisable( TTrain *Train, command_data const &Command );
static void OnCommand_waterheaterbreakertoggle( TTrain *Train, command_data const &Command );
@@ -692,7 +696,8 @@ public: // reszta może by?publiczna
TGauge ggWaterHeaterButton; // water heater switch
TGauge ggWaterCircuitsLinkButton;
TGauge ggFuelPumpButton; // fuel pump switch
- TGauge ggOilPumpButton; // fuel pump switch
+ TGauge ggOilPumpButton; // oil pump switch
+ TGauge ggOilFuelPumpButton; // joint oil and fuel pump switch
TGauge ggMotorBlowersFrontButton; // front traction motor fan switch
TGauge ggMotorBlowersRearButton; // rear traction motor fan switch
TGauge ggMotorBlowersAllOffButton; // motor fans shutdown switch
diff --git a/vehicle/gaugepositions.h b/vehicle/gaugepositions.h
new file mode 100644
index 000000000..fc82ed44b
--- /dev/null
+++ b/vehicle/gaugepositions.h
@@ -0,0 +1,35 @@
+/*
+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