18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-21 02:44:58 +01:00

Merge remote-tracking branch 'origin/master' into feat/persistent-odometer-store

# Conflicts:
#	vehicle/DynObj.h
This commit is contained in:
jerrrrycho
2026-11-11 08:17:40 +01:00
70 changed files with 11421 additions and 369 deletions

View File

@@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/.
#include <map>
#include <optional>
#include "hamulce.h"
#include "couplerphysics.h"
#include "scripting/ladderlogic.h"
#include "vehicle/odometerreading.h"
@@ -1256,6 +1257,7 @@ struct TCoupling
double Dist = 0.0; /*strzalka ugiecia zderzaków*/
bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/
float stretch_duration{0.f}; // seconds, elapsed time with excessive force applied to the coupler
bool broken{false}; // the coupler broke (damage_coupler()), until it's repaired (repair_coupler())
// optional adapter piece
double adapter_length{0.0}; // meters, value added on the given end to standard vehicle (half)length
double adapter_height{0.0}; // meters, distance from rail level
@@ -1265,6 +1267,11 @@ struct TCoupling
power_coupling power_110v;
power_coupling power_24v;
// the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end,
// and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end
coupler_physics::end_parameters physics;
coupler_physics::pair_state physics_state;
int sounds{0}; // sounds emitted by the coupling devices
bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/
std::string control_type; // abstraction of control coupling interface and communication standard
@@ -2008,6 +2015,9 @@ class TMoverParameters
glm::vec3 Front{};
std::string Name; /*nazwa wlasna*/
TCoupling Couplers[2]; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami
// the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on
// (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered
bool CouplerPhysics{false};
std::array<neighbour_data, 2> Neighbours; // potential collision sources
bool Power110vIsAvailable = false; // cached availability of 110v power
bool Power24vIsAvailable = false; // cached availability of 110v power
@@ -2267,6 +2277,7 @@ class TMoverParameters
int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/
bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */
bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */
bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/
double eimv_pr = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/
double eimv[21];
static std::vector<std::string> const eimv_labels;
@@ -2384,6 +2395,10 @@ class TMoverParameters
int DettachStatus(int ConnectNo);
bool Dettach(int ConnectNo);
void damage_coupler(int const End);
// repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled
// again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there
// was a broken coupler to repair
bool repair_coupler(int const End);
void Derail(DerailReason Reason);
bool DirectionForward();
bool DirectionBackward(void); /*! kierunek ruchu*/
@@ -2441,6 +2456,15 @@ class TMoverParameters
int MainCtrlNoPowerPos() const; // highest setting of master controller which won't cause engine to generate extra power
int MainCtrlActualPowerPos() const; // current actual setting of master controller, relative to the highest setting not generating extra power
int MainCtrlPowerPos() const; // current setting of master controller, relative to the highest setting not generating extra power
// positions the master controller of the EIMCtrlType 2 (Elf) has below its own position 0, the emergency brake (0 or 1)
int EIMCtrlEmergencyPositions() const;
// whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency)
bool IsMainCtrlEmergencyPos() const;
// the master controller position sent to the coupled vehicles ("MainCtrl"), the same with and without
// EIMCtrlMainEmergency: the Elf's positions without the emergency brake one, which goes as the full braking
int MainCtrlPosForCoupled() const;
// the master controller position of this vehicle for one received from a coupled vehicle ("MainCtrl")
int MainCtrlPosFromCoupled(int Position) const;
/*! pomocniczy nastawnik:*/
bool IncScndCtrl(int CtrlSpeed);
bool DecScndCtrl(int CtrlSpeed);
@@ -2521,6 +2545,17 @@ class TMoverParameters
double BrakeForceP(double press, double velocity) const;
double BrakeForce(const TTrackParam &Track);
double CouplerForce(int const End, double dt);
// whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this
// vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all
bool coupler_physics_at(int const End) const;
// the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h
double coupler_force_physical(int const End, double const dt);
// with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and
// still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers
bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd);
// couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit
// is too fast for them to catch
void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd);
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};

View File

@@ -643,6 +643,9 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *
// stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie
if (thiscoupler.CouplingFlag == coupling::faux)
{
// a new coupling: the play of the coupling as set up anew, without the stretch of the one before
thiscoupler.physics_state.couple();
othercoupler.physics_state.couple();
// jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg
thiscoupler.Render = true; // tego rysować
othercoupler.Render = false; // a tego nie
@@ -1334,6 +1337,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
auto const physical{coupler_physics_at(End)};
if (physical && false == coupler_stop_hit(End, *othervehicle, otherend))
{
return;
}
// the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give
// for good, rather than spring back as the legacy model has it
auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0};
// 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)};
@@ -1347,12 +1359,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
{
case 0:
{
CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt;
CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt;
break; // yB: ej ej ej, a po
}
case 1:
{
CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt;
CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt;
break;
}
default:
@@ -1363,7 +1375,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
if (Global.crash_damage)
{
if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg))
// the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit())
if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg))
{
// small chance to smash the coupler if it's hit with excessive force
damage_coupler(End);
@@ -1392,18 +1405,21 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
}
}
// adjust velocity and acceleration of affected vehicles
// adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the
// integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the
// velocity once more, and the vehicles would bounce off the stop faster than they hit it
auto const accelerationspike{physical ? 0.0 : 1.0};
if (false == TestFlag(DamageFlag, dtrain_out))
{
auto const accelerationchange{(velocity - V) / dt};
AccS += accelerationchange;
AccS += accelerationchange * accelerationspike;
V = velocity;
}
if (false == TestFlag(othervehicle->DamageFlag, dtrain_out))
{
auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis
auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt};
othervehicle->AccS += othervehicleaccelerationchange;
othervehicle->AccS += othervehicleaccelerationchange * accelerationspike;
othervehicle->V = othervehiclenewvelocity;
}
}
@@ -1421,39 +1437,72 @@ void TMoverParameters::damage_coupler(int const End)
if (SetFlag(DamageFlag, dtrain_coupling))
EventFlag = true;
if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose)
auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose};
if (hosetorn)
{
// hamowanie nagle - zerwanie przewodow hamulcowych
AlarmChainFlag = true;
}
thiscoupler.CouplingFlag = 0;
thiscoupler.broken = true;
if (thiscoupler.Connected != nullptr)
{
switch (End)
// break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too
// for vehicles facing each other
auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]};
othercoupler.CouplingFlag = coupling::faux;
// the coupling broke between the two, either end can be repaired
othercoupler.broken = true;
if (hosetorn && coupler_physics_at(End))
{
// break connection with other vehicle, if there's any
case 0:
{
thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux;
break;
}
case 1:
{
thiscoupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux;
break;
}
default:
{
break;
}
// the brake pipe of the other part of the train vents through the torn hose as well
thiscoupler.Connected->AlarmChainFlag = true;
}
}
WriteLog("Bad driving: " + Name + " broke a coupler");
}
namespace
{
// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake
// hose) once neither of its couplers is broken
void repair(TMoverParameters &Vehicle, TCoupling &Coupler)
{
Coupler.broken = false;
Coupler.stretch_duration = 0.f;
Coupler.physics_state.couple();
if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken)
{
return;
}
ClearFlag(Vehicle.DamageFlag, dtrain_coupling);
// either vehicle of the pair may have been braking through the torn hose
Vehicle.AlarmChainFlag = false;
}
} // namespace
bool TMoverParameters::repair_coupler(int const End)
{
auto &thiscoupler{Couplers[End]};
if (false == thiscoupler.broken)
{
return false;
}
repair(*this, thiscoupler);
// the other half of the coupling, which may be the vehicle flagged with the damage
if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken)
{
repair(*other, other->Couplers[thiscoupler.ConnectedNr]);
}
WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear"));
return true;
}
void TMoverParameters::Derail(DerailReason const Reason)
{
if (SetFlag(DamageFlag, dtrain_out))
@@ -2626,7 +2675,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed)
if (true == OK)
{
ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones
SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //???
SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //???
SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive);
}
@@ -2752,7 +2801,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed)
if (OK)
{
ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); // hmmmm...???!!!
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!!
/*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive);
}
}
@@ -2800,7 +2849,7 @@ int TMoverParameters::MainCtrlNoPowerPos() const
}
case 2:
{
return 3;
return 3 + EIMCtrlEmergencyPositions();
}
case 3:
{
@@ -2825,6 +2874,27 @@ int TMoverParameters::MainCtrlPowerPos() const
return MainCtrlPos - MainCtrlNoPowerPos();
}
int TMoverParameters::EIMCtrlEmergencyPositions() const
{
return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0;
}
bool TMoverParameters::IsMainCtrlEmergencyPos() const
{
return MainCtrlPos < EIMCtrlEmergencyPositions();
}
int TMoverParameters::MainCtrlPosForCoupled() const
{
// the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from
return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions());
}
int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const
{
return Position + EIMCtrlEmergencyPositions();
}
// *************************************************************************************************
// Q: 20160710
// zwiększenie bocznika
@@ -2866,7 +2936,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed)
OK = false;
if (OK)
{
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //???
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //???
/*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive);
}
}
@@ -2928,7 +2998,7 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed)
OK = false;
if (OK)
{
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //???
/*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //???
/*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive);
}
}
@@ -4690,8 +4760,9 @@ void TMoverParameters::UpdatePipePressure(double dt)
// EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with
// the emergency brake (a broken coupler sets AlarmChainFlag instead)
if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() ||
// the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position
// vents the pipe only from the vehicle driven from, whatever the controllers of the others show
if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() ||
(SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) ||
(0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0))
{
@@ -5450,6 +5521,10 @@ double TMoverParameters::Adhesive(double staticfriction) const
// *************************************************************************************************
double TMoverParameters::CouplerForce(int const End, double dt)
{
if (coupler_physics_at(End))
{
return coupler_force_physical(End, dt);
}
auto &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
@@ -5563,27 +5638,9 @@ double TMoverParameters::CouplerForce(int const End, double dt)
// zderzenie
thiscoupler.CheckCollision = true;
}
if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux &&
thiscoupler.AutomaticCouplingAllowed &&
othercoupler.AutomaticCouplingAllowed)
if (-newdistance >= std::min(collisiondistance, dEpsilon))
{
// sprzeganie wagonow z samoczynnymi sprzegami
auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag};
// potentially exclude incompatible control coupling
if (thiscoupler.control_type != othercoupler.control_type)
{
couplingtype &= ~coupling::control;
}
couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype);
// too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)};
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;
automatic_coupling(End, *othervehicle, otherend);
}
}
}
@@ -5598,6 +5655,172 @@ double TMoverParameters::CouplerForce(int const End, double dt)
return CF;
}
bool TMoverParameters::coupler_physics_at(int const End) const
{
if (false == Global.coupler_physics)
{
return false;
}
if (Global.coupler_physics_all || CouplerPhysics)
{
return true;
}
// either vehicle of the pair covered takes the pair in, so both of them compute it the same way
auto const *other{Neighbours[End].vehicle};
return other != nullptr && other->MoverParameters->CouplerPhysics;
}
void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd)
{
auto &thiscoupler{Couplers[End]};
auto &othercoupler{Other.Couplers[OtherEnd]};
if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed ||
false == othercoupler.AutomaticCouplingAllowed)
{
return;
}
// sprzeganie wagonow z samoczynnymi sprzegami
auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag};
// potentially exclude incompatible control coupling
if (thiscoupler.control_type != othercoupler.control_type)
{
couplingtype &= ~coupling::control;
}
couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype);
// too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)};
auto const caught{safe && Attach(End, OtherEnd, &Other, 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;
}
namespace
{
// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train
constexpr double coupler_stretch_threshold{0.001};
// the sounds of the buffers hitting each other, and of the coupling taking up its play
struct coupler_sound_input
{
double gap{0.0}; // between the ends [m]
double previous_gap{0.0};
double gap_rate{0.0}; // [m/s]
double draw_gear{0.0}; // deflection [m]
double previous_draw_gear{0.0};
bool coupled{false};
bool adapter{false};
bool moving{false};
};
int coupler_sounds(coupler_sound_input const &Input)
{
if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter)
{
// 090503: dzwieki pracy zderzakow
return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash;
}
if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005)
{
// 090503: dzwieki pracy sprzegu
return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch;
}
return sound::none;
}
} // namespace
double TMoverParameters::coupler_force_physical(int const End, double const dt)
{
auto &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
auto const otherend{Neighbours[End].vehicle_end};
auto &othercoupler{othervehicle->Couplers[otherend]};
auto &state{thiscoupler.physics_state};
// the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since
auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)};
auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)};
// the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind
auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)};
auto const coupled{thiscoupler.CouplingFlag != coupling::faux};
auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()};
if (false == coupled && Neighbours[End].distance > 0.05)
{ // arbitrary distance
// potentially reset auto coupling lock
thiscoupler.AutomaticCouplingAllowed = true;
}
auto const previousgap{state.gap};
auto const previousdrawgear{state.draw_gear.deflection};
auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})};
SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0}));
thiscoupler.CheckCollision = state.stop != 0;
// for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end
thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0);
// the link pulled past its yield force, which the AI drivers ease off on
thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast<float>(dt) : 0.f;
if (result.broken)
{
damage_coupler(End);
}
if (false == coupled && gap < 0.0)
{
auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB};
if (-gap >= std::min(collisiondistance, dEpsilon))
{
automatic_coupling(End, *othervehicle, otherend);
}
}
// tension pulls this vehicle towards the other one
auto const force{result.force * -DirF(End)};
if (thiscoupler.CouplingFlag != coupling::faux)
{
// uzgadnianie prawa Newtona, as in CouplerForce()
othercoupler.CForce = -force * DirPatch(End, otherend);
}
return force;
}
bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd)
{
auto &thiscoupler{Couplers[End]};
auto &othercoupler{Other.Couplers[OtherEnd]};
auto &state{thiscoupler.physics_state};
// the draw gear went solid with the gap opening up, the buffers with it closing
auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)};
auto const closing{state.stop > 0 ? gaprate : -gaprate};
if (state.stop == 0 || closing <= 0.0)
{
// parting from the stop already, after the hit on the other vehicle's end
return false;
}
if (false == Global.crash_damage)
{
return true;
}
auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)};
// the other vehicle keeps the state of the pair alike
othercoupler.physics_state.elongation = state.elongation;
if (hit.broken || hit.crushed)
{
damage_coupler(End);
}
// a broken coupling lets the vehicles part
return false == hit.broken;
}
// *************************************************************************************************
// Q: 20160714
// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad)
@@ -7532,10 +7755,16 @@ void TMoverParameters::CheckEIMIC(double dt)
eimic = 0;
break;
case 2:
if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay)
if (IsMainCtrlEmergencyPos())
{
// hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure()
eimic = -1.0;
}
else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay)
{
double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01;
switch (MainCtrlPos)
// the positions below are those of the controller without the emergency brake position
switch (MainCtrlPos - EIMCtrlEmergencyPositions())
{
case 0:
case 1:
@@ -10946,6 +11175,82 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line)
extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, "");
}
namespace
{
// the value of an optional key of the line, or the default without it
double optional_value(std::string const &Line, std::string const &Key, double const Default)
{
auto value{Default};
extract_value(value, Key, Line, "");
return value;
}
// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it
double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default)
{
auto value{0.0};
return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default;
}
// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of
// an automatic coupler have about a centimetre between them, a chain hangs loose
double default_slack(TCouplerType const Type)
{
switch (Type)
{
case TCouplerType::Automatic:
return 0.005;
case TCouplerType::Chain:
return 0.05;
default:
return 0.0;
}
}
// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from
// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have:
// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in
// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9
// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one
// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks
// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it
// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid
coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line)
{
coupler_physics::end_parameters parameters;
parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)};
parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)};
// only a screw coupling can be tightened to press the buffers in, and not past their travel
auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0};
parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest);
// the legacy model sprang back at beta of the force it was loaded with
auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5};
parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0);
parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0);
// as much as the legacy model had
parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0);
// FmaxC is the rated breaking force of the coupling
auto const ultimate{std::max(Coupler.FmaxC, 1.0)};
auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)};
auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)};
parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated};
// the steel parts give a few millimetres under the rated force
parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003);
parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC));
parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95);
return parameters;
}
void scale_strength(coupler_physics::link_strength &Link, double const Factor)
{
Link.yield *= Factor;
Link.ultimate *= Factor;
}
} // namespace
void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index)
{
@@ -11024,11 +11329,21 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde
thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB);
}
thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line);
if (Index == 0)
{
// 0 indicates single entry for both couplers
Couplers[1] = Couplers[0];
}
// each coupling as made is a little stronger than its rated force, a different one at each end
for (int end = end::front; end <= end::rear; ++end)
{
if (Index == 0 || end == (Index == 2 ? end::rear : end::front))
{
scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end));
}
}
}
void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input)
@@ -11205,6 +11520,16 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, "");
extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, "");
extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, "");
// Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one
extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, "");
if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions)
{
// the old positions in the file: without the fix-up the controller would have no power position, and the
// reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions)
MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions();
ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos));
MainCtrlPosNo = elfpositions;
}
extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR
extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych
@@ -12550,9 +12875,10 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do
if (Command == "MainCtrl")
{
if (MainCtrlPosNo >= floor(CValue1))
// sent as MainCtrlPosForCoupled(), passed on unchanged
if (auto const position{MainCtrlPosFromCoupled(static_cast<int>(floor(CValue1)))}; MainCtrlPosNo >= position)
{
MainCtrlPos = static_cast<int>(floor(CValue1));
MainCtrlPos = position;
if (DelayCtrlFlag)
{
if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1)

291
McZapkie/couplerphysics.cpp Normal file
View File

@@ -0,0 +1,291 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "couplerphysics.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <tuple>
namespace coupler_physics {
namespace {
// the transition between the loading and the unloading curve of a device, to the secant stiffness of the pair: the
// friction holds the device stiffer than its springs until the force changes enough to slip it
constexpr double transition_factor{3.0};
// the force, the deflection and the energy of a curve are computed within this many iterations of the inverse
constexpr int inverse_iterations{50};
constexpr int series_iterations{60};
// a device which doesn't give at all, standing in for the buffers of an end with an adapter
constexpr spring_curve rigid{1.0, 0.0, 0.0};
double series_stiffness(double First, double Second) {
return First * Second / (First + Second);
}
// the buffers of the pair: those of both ends in series, or with an adapter on either end, the device with the shorter
// travel alone, the one of the automatic coupler which takes the push
struct pressed_devices {
spring_curve first;
spring_curve second;
double unloading{0.5};
double damping{0.0};
};
bool shorter(spring_curve const &First, spring_curve const &Second) {
return std::tie(First.travel, First.stiffness, First.progression) <= std::tie(Second.travel, Second.stiffness, Second.progression);
}
pressed_devices buffers_of(end_parameters const &First, end_parameters const &Second, bool const Adapter) {
auto const unloading{0.5 * (First.buffers_unloading + Second.buffers_unloading)};
auto const damping{0.5 * (First.damping + Second.damping)};
if (false == Adapter) {
return {First.buffers, Second.buffers, unloading, damping};
}
auto const &coupler{shorter(First.buffers, Second.buffers) ? First.buffers : Second.buffers};
return {coupler, rigid, unloading, damping};
}
pressed_devices draw_gears_of(end_parameters const &First, end_parameters const &Second) {
return {First.draw_gear, Second.draw_gear, 0.5 * (First.draw_gear_unloading + Second.draw_gear_unloading), 0.5 * (First.damping + Second.damping)};
}
struct pressed_force {
double force{0.0}; // with the friction and the damping [N]
double curve_force{0.0}; // of the loading curve [N]
double first_deflection{0.0}; // of the first device [m]
bool solid{false}; // both devices at the end of their travel
};
// the force of the devices pressed (or pulled) by the deflection growing at the rate
pressed_force press(pressed_devices const &Devices, hysteresis &State, double const Deflection, double const Rate) {
if (Deflection <= 0.0) {
State.reset();
return {};
}
auto const split{series(Devices.first, Devices.second, Deflection)};
auto const travel{Devices.first.travel + Devices.second.travel};
auto const top{std::max(Devices.first.end_force(), Devices.second.end_force())};
auto const transition{transition_factor * top / std::max(travel, 1e-3)};
auto const friction{State.update(Deflection, split.force, Devices.unloading * split.force, transition)};
// a buffer pushes, a draw gear pulls, neither the other way round however fast they spring back
return {std::max(0.0, friction + Devices.damping * Rate), split.force, split.first, Deflection >= travel};
}
bool weaker(link_strength const &First, link_strength const &Second) {
return std::tie(First.ultimate, First.yield, First.hardening) <= std::tie(Second.ultimate, Second.yield, Second.hardening);
}
} // namespace
double spring_curve::force(double const Deflection) const {
if (travel <= 0.0 || Deflection <= 0.0) {
return 0.0;
}
auto const u{std::min(Deflection / travel, 1.0)};
return end_force() * ((1.0 - progression) * u + progression * u * u * u);
}
double spring_curve::deflection(double const Force) const {
if (travel <= 0.0 || Force <= 0.0) {
return 0.0;
}
auto const f{Force / end_force()};
if (f >= 1.0) {
return travel;
}
if (progression <= 0.0) {
return f * travel;
}
// the curve is rising and convex, so Newton's method from the end of the travel closes in from above
auto u{1.0};
auto step{1.0};
for (int iteration = 0; iteration < inverse_iterations && std::abs(step) > 1e-15; ++iteration) {
auto const value{progression * u * u * u + (1.0 - progression) * u - f};
auto const slope{3.0 * progression * u * u + (1.0 - progression)};
step = value / slope;
u -= step;
}
return std::clamp(u, 0.0, 1.0) * travel;
}
double spring_curve::energy(double const Deflection) const {
if (travel <= 0.0 || Deflection <= 0.0) {
return 0.0;
}
auto const u{std::min(Deflection / travel, 1.0)};
return end_force() * travel * ((1.0 - progression) * u * u / 2.0 + progression * u * u * u * u / 4.0);
}
series_split series(spring_curve const &First, spring_curve const &Second, double const Deflection) {
if (Deflection <= 0.0) {
return {};
}
if (Second.travel <= 0.0) {
return {First.force(Deflection), std::min(Deflection, First.travel), 0.0};
}
if (First.travel <= 0.0) {
return {Second.force(Deflection), 0.0, std::min(Deflection, Second.travel)};
}
if (std::tie(First.stiffness, First.travel, First.progression) == std::tie(Second.stiffness, Second.travel, Second.progression)) {
auto const half{std::min(Deflection / 2.0, First.travel)};
return {First.force(half), half, half};
}
auto const top{std::max(First.end_force(), Second.end_force())};
if (Deflection >= First.travel + Second.travel) {
return {top, First.travel, Second.travel};
}
// the force at which the deflections of both add up to the given one. the sum doesn't depend on the order of
// the devices, so neither does the result
auto low{0.0};
auto high{top};
for (int iteration = 0; iteration < series_iterations; ++iteration) {
auto const middle{0.5 * (low + high)};
if (First.deflection(middle) + Second.deflection(middle) < Deflection) {
low = middle;
}
else {
high = middle;
}
}
auto const force{0.5 * (low + high)};
return {force, First.deflection(force), Second.deflection(force)};
}
double hysteresis::update(double const Deflection, double const Loading, double const Unloading, double const Transition) {
force = std::clamp(force + Transition * (Deflection - deflection), std::min(Unloading, Loading), Loading);
deflection = Deflection;
return force;
}
void hysteresis::reset() {
force = 0.0;
deflection = 0.0;
}
double plastic_elongation(link_strength const &Link, double const Force, double const Elongation) {
if (false == Link.breakable || Force <= Link.yield) {
return Elongation;
}
return std::max(Elongation, (Force - Link.yield) / Link.hardening);
}
double impact_force(double const Velocity, double const Stiffness, double const Mass1, double const Mass2) {
if (Velocity <= 0.0 || Mass1 <= 0.0 || Mass2 <= 0.0) {
return 0.0;
}
auto const mass{Mass1 * Mass2 / (Mass1 + Mass2)};
return Velocity * std::sqrt(Stiffness * mass);
}
double strength_scatter(std::string_view const Name, int const End) {
// FNV-1a, which std::hash isn't on every compiler
std::uint64_t hash{14695981039346656037ULL};
auto const mix = [&hash](unsigned char const Byte) {
hash ^= Byte;
hash *= 1099511628211ULL;
};
for (auto const character : Name) {
mix(static_cast<unsigned char>(character));
}
mix(static_cast<unsigned char>(End));
// the 53 high bits, as a fraction
auto const fraction{static_cast<double>(hash >> 11) / 9007199254740992.0};
return 1.0 + 0.2 * fraction;
}
link_strength weaker_link(end_parameters const &First, end_parameters const &Second) {
auto link{weaker(First.link, Second.link) ? First.link : Second.link};
// an articulated joint holds whatever the end of the other section is set up to
link.breakable = First.link.breakable && Second.link.breakable;
return link;
}
double solid_hit_loss(end_parameters const &First, end_parameters const &Second) {
// the collision needs some bounce left (ComputeCollision() asserts it)
auto const restitution{std::clamp(0.5 * (First.solid_restitution + Second.solid_restitution), 0.05, 0.95)};
return 1.0 - restitution * restitution;
}
void pair_state::couple() {
draw_gear.reset();
elongation = 0.0;
}
pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input) {
pair_result result;
State.stop = 0;
State.stop_force = 0.0;
pressed_force pulled;
if (Input.coupled) {
auto const play{First.slack + Second.slack + State.elongation};
pulled = press(draw_gears_of(First, Second), State.draw_gear, Input.gap - play, Input.gap_rate);
}
else {
State.draw_gear.reset();
}
auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)};
result.tension = pulled.force;
result.compression = pushed.force;
result.buffers_deflection = Input.adapter ? 0.0 : pushed.first_deflection;
if (pulled.solid) {
State.stop = 1;
State.stop_force = pulled.curve_force;
}
else if (pushed.solid) {
State.stop = -1;
State.stop_force = pushed.curve_force;
}
if (Input.coupled) {
auto const link{weaker_link(First, Second)};
result.overloaded = result.tension > link.yield;
if (Input.damage && link.breakable && result.tension >= link.ultimate) {
result.broken = true;
result.tension = 0.0;
State.draw_gear.reset();
State.stop = std::min(State.stop, 0);
}
else if (Input.damage) {
State.elongation = plastic_elongation(link, result.tension, State.elongation);
}
}
result.force = result.tension - result.compression;
State.gap = Input.gap;
return result;
}
impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double const Velocity, double const Mass1, double const Mass2) {
impact_result result;
if (State.stop == 0 || Velocity <= 0.0) {
return result;
}
auto const stiffness{series_stiffness(First.link_stiffness, Second.link_stiffness)};
result.force = State.stop_force + impact_force(Velocity, stiffness, Mass1, Mass2);
if (State.stop > 0) {
auto const link{weaker_link(First, Second)};
result.broken = link.breakable && result.force >= link.ultimate;
if (false == result.broken) {
State.elongation = plastic_elongation(link, result.force, State.elongation);
}
}
else {
result.crushed = result.force >= std::min(First.crush_force, Second.crush_force);
}
return result;
}
} // namespace coupler_physics

140
McZapkie/couplerphysics.h Normal file
View File

@@ -0,0 +1,140 @@
#pragma once
#include <limits>
#include <string_view>
// the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of
// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive
// springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack)
// in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its
// yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack
namespace coupler_physics {
// force-deflection characteristic of the spring device of one vehicle end, its buffers or its draw gear:
// F(d) = F_end * ((1 - p) * u + p * u^3), u = d / travel, F_end = stiffness * travel
// p (the progression) 0 gives a linear spring; towards 1 it's soft at first and stiffens towards the end of the
// travel, as ring springs and elastomer pads do
struct spring_curve {
double stiffness{1.0}; // secant stiffness, up to the end of the travel [N/m]
double travel{0.1}; // [m]
double progression{0.0}; // 0 to 0.9
double end_force() const { return stiffness * travel; }
// force at the deflection [N], the deflection held within the travel
double force(double Deflection) const;
// deflection at the force [m]: the end of the travel at the end force and past it
double deflection(double Force) const;
// energy the device takes in along the curve up to the deflection [J]
double energy(double Deflection) const;
};
// the devices of both ends pressed against each other: they carry the same force, their deflections add up. past
// the end of the travel of one, the other one takes the rest. the result doesn't depend on the order of the two
struct series_split {
double force{0.0}; // [N]
double first{0.0}; // deflection of the first device [m]
double second{0.0}; // of the second one [m]
};
series_split series(spring_curve const &First, spring_curve const &Second, double Deflection);
// friction (Coulomb) hysteresis of a spring device: the force follows the loading curve while the deflection grows,
// drops to the unloading curve when it shrinks, and in between moves along a stiff transition line, as the friction
// of ring springs or of the wedges of a draw gear holds the device until the force changes enough
struct hysteresis {
double force{0.0}; // carried at the last update [N]
double deflection{0.0}; // at the last update [m]
// the force at the new deflection, given the force of the loading and of the unloading curve there, and the
// stiffness of the transition between them [N/m]
double update(double Deflection, double Loading, double Unloading, double Transition);
void reset();
};
// steel link of the coupling (the screw coupling and the hook, the knuckle of an automatic coupler): elastic up to
// the yield force, stretched for good past it (the hardening gives the force for each metre of it), broken at the
// ultimate force
struct link_strength {
double yield{std::numeric_limits<double>::max()}; // [N]
double ultimate{std::numeric_limits<double>::max()}; // [N]
double hardening{1.0}; // [N/m]
bool breakable{false}; // an articulated joint, or an end without a coupler set up, holds whatever
};
// the permanent elongation [m] the link has after carrying the force, given the one it had
double plastic_elongation(link_strength const &Link, double Force, double Elongation);
// peak force [N] of an elastic hit of two masses [kg] at the closing velocity [m/s] on a stop of the stiffness [N/m]:
// the kinetic energy of their relative motion all goes into the stop
double impact_force(double Velocity, double Stiffness, double Mass1, double Mass2);
// spread of the strength of the couplings as made: 1.0 to 1.2 of the rated force, fixed for the vehicle end, and the
// same on every compiler
double strength_scatter(std::string_view Name, int End);
// what the model takes of one vehicle end
struct end_parameters {
spring_curve buffers;
spring_curve draw_gear;
double slack{0.0}; // play of the coupling in tension [m], negative for the buffers pressed in by a tightened screw coupling
double buffers_unloading{0.5}; // force of the unloading curve to that of the loading one
double draw_gear_unloading{0.5};
double damping{0.0}; // viscous damping of the devices, while pressed [N s/m]
double link_stiffness{1.0}; // of the steel parts of the end, past the travel of the springs [N/m]
double crush_force{std::numeric_limits<double>::max()}; // a hit on the buffers past their travel with this force crushes them [N]
// coefficient of restitution of a hit on the springs gone solid: the steel of the housings and the underframe gives
// for good rather than springing back, so the vehicles share their momentum rather than pass it on
double solid_restitution{0.2};
link_strength link;
};
// the share of the energy of the relative motion a hit on the solid springs of the two ends takes, as the legacy
// collision (ComputeCollision()) takes it: 1 - e^2
double solid_hit_loss(end_parameters const &First, end_parameters const &Second);
// the weaker of the links of the two ends, which gives first; the same whichever end asks
link_strength weaker_link(end_parameters const &First, end_parameters const &Second);
// state of the coupling of two vehicle ends, which both vehicles keep alike: each updates its own copy with the same
// gap, so the copies stay the same
struct pair_state {
hysteresis draw_gear;
hysteresis buffers;
double elongation{0.0}; // permanent, of the link [m]; it adds to the slack until the vehicles are coupled again
double gap{0.0}; // at the last update [m]
int stop{0}; // at the last update: 1 the draw gear went solid, -1 the buffers did, 0 neither
double stop_force{0.0}; // the springs carried at the stop [N]
// a new coupling of the ends: the link adjusted (a screw coupling tightened anew), the draw gear released
void couple();
};
struct pair_input {
double gap{0.0}; // between the ends [m], negative with the buffers pressed in
double gap_rate{0.0}; // [m/s]
bool coupled{false};
bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone
bool damage{false}; // the link can stretch and break (crash damage on)
};
struct pair_result {
double force{0.0}; // between the ends, tension positive [N]
double tension{0.0}; // carried by the link [N]
double compression{0.0}; // carried by the buffers [N]
double buffers_deflection{0.0}; // of the buffers of the first end [m]
bool overloaded{false}; // the link was pulled past its yield force
bool broken{false}; // the link broke, it carries nothing now
};
// the force between the first end and the second one at the gap, updating the state of the pair
pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input);
// what a hit on the stop does to the ends
struct impact_result {
double force{0.0}; // peak force of the hit [N]
bool broken{false}; // the link broke under it
bool crushed{false}; // the buffers or the coupler of an end were crushed by it
};
// the hit on the stop the pair went solid against at the last update (State.stop), at the closing velocity [m/s], of
// the vehicles of the masses [kg]: stretches or breaks the link of a coupled pair, may crush the buffers
impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double Velocity, double Mass1, double Mass2);
} // namespace coupler_physics