18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-21 03:54:57 +01:00

feat(physics): physical coupler model with slack, hysteresis and breaking

This commit is contained in:
2026-11-11 01:43:46 +01:00
parent 39e855d3a5
commit c85aab4f3f
8 changed files with 1168 additions and 41 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"
class cParser;
@@ -1264,6 +1265,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
@@ -2529,6 +2535,14 @@ class TMoverParameters
double BrakeForceP(double press, double velocity) const;
double BrakeForce(const TTrackParam &Track);
double CouplerForce(int const End, double dt);
// 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,11 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
if (Global.coupler_physics && false == coupler_stop_hit(End, *othervehicle, otherend))
{
return;
}
// 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)};
@@ -1363,7 +1371,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 == Global.coupler_physics && -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 +1401,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{Global.coupler_physics ? 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,7 +1433,8 @@ 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;
@@ -1431,23 +1444,13 @@ void TMoverParameters::damage_coupler(int const End)
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
thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].CouplingFlag = coupling::faux;
if (hosetorn && Global.coupler_physics)
{
// 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;
}
}
@@ -5470,6 +5473,10 @@ double TMoverParameters::Adhesive(double staticfriction) const
// *************************************************************************************************
double TMoverParameters::CouplerForce(int const End, double dt)
{
if (Global.coupler_physics)
{
return coupler_force_physical(End, dt);
}
auto &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
@@ -5583,27 +5590,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);
}
}
}
@@ -5618,6 +5607,157 @@ double TMoverParameters::CouplerForce(int const End, double dt)
return CF;
}
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)
@@ -10972,6 +11112,80 @@ 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
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));
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)
{
@@ -11050,11 +11264,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)

285
McZapkie/couplerphysics.cpp Normal file
View File

@@ -0,0 +1,285 @@
/*
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;
}
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

133
McZapkie/couplerphysics.h Normal file
View File

@@ -0,0 +1,133 @@
#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]
link_strength link;
};
// 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