18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-05 16:55:32 +01:00

feat(physics): the motion of a derailed vehicle on the ground

With physics.derailment new a vehicle off the rails gets a motion of its
own on the ground (vehicle/derailmotion.h, in eu07_core): it runs on along
its heading, turned out of the curve by the sideways speed it left the
rail with, slides across it down slopes steeper than the friction holds,
follows the height and the slope of the ground under its supports, and
tips over about the wheels of one side (while still guided by the curve,
or on a slope, or sliding sideways) until it lies on its side.

The vehicle holds the motion and what derailed it (the cause, the lateral
acceleration out of the curve, the side a coupling pulled it to). While
the motion runs, its friction (0.1 tipping on the outer wheels, 0.3
upright, up to 0.5 on its side) and the grade under it go into the
longitudinal force. Off the end of the track the vehicle now slides on
with the friction of the ballast instead of stopping within g, and a
coupling can pull a vehicle off the rails (pull_off). Nothing of it with
physics.derailment monitor, old or off.
This commit is contained in:
jerrrrycho
2026-11-23 02:40:52 +01:00
parent f15ea40575
commit c428f00fff
6 changed files with 1270 additions and 10 deletions
+1
View File
@@ -549,6 +549,7 @@ set(CORE_SOURCES
"McZapkie/couplerphysics.cpp"
"McZapkie/derailment.cpp"
"McZapkie/collision.cpp"
"vehicle/derailmotion.cpp"
"world/TrackCheck.cpp"
"McZapkie/Oerlikon_ESt.cpp"
"utilities/parser.cpp"
+17
View File
@@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/.
#include "derailment.h"
#include "collision.h"
#include "scripting/ladderlogic.h"
#include "vehicle/derailmotion.h"
#include "vehicle/odometerreading.h"
class cParser;
@@ -2553,6 +2554,22 @@ class TMoverParameters
// derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the
// forces of the vehicles coupled to it acting on it)
derailment::outcome Derailed{derailment::outcome::none};
// physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h):
// what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a
// buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1
// the right; 0 the side the acceleration throws it to, from the track)
derail_motion::cause DerailCause{derail_motion::cause::off_rails};
double DerailAcceleration{0.0};
int DerailSide{0};
// the vehicle off the track, on the ground: begun and stepped by TDynamicObject, which knows the ground; its friction
// and the grade under it go into the forces of this one
derail_motion::body OffTrack;
// physics.derailment new: the vehicle derailed by the physical criteria, the end of the track or a collision has to
// leave the track and its motion on the ground isn't begun yet. never with physics.derailment monitor, old or off
bool leaves_track() const;
// physics.derailment new: a coupling of a vehicle off the track pulls this one off the rails sideways, to the Side
// (1 the left of its front, -1 the right), with the lateral acceleration [m/s2] of the pull on it
void pull_off(int Side, double Acceleration, std::string const &Why);
// physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the
// height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit
collision::vehicle_kind collision_kind() const;
+64 -10
View File
@@ -82,6 +82,15 @@ bool legacy_derailed_slides(TMoverParameters const &Vehicle)
Vehicle.Derailed == derailment::outcome::none;
}
// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency
void tear_brake_hoses(TMoverParameters &Vehicle)
{
if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; }))
{
Vehicle.AlarmChainFlag = true;
}
}
} // namespace
int DirF(int CouplerN)
@@ -1605,6 +1614,9 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin
}
// upright, it slides on the sleepers and keeps passing the forces on
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::collision;
DerailAcceleration = 0.0;
DerailSide = 0;
CollisionDerail = Reason;
EventFlag = true;
MainSwitch(false, range_t::local);
@@ -1615,10 +1627,7 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin
SlippingWheels = false;
}
// the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency
if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; }))
{
AlarmChainFlag = true;
}
tear_brake_hoses(*this);
derailment_monitor.reset();
pushed_off_monitor.reset();
ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why));
@@ -2082,13 +2091,14 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve
return;
}
Derailed = Verdict.result;
DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails;
// out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve
DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration;
DerailSide = 0;
EventFlag = true;
MainSwitch(false, range_t::local);
// the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency
if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; }))
{
AlarmChainFlag = true;
}
tear_brake_hoses(*this);
ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{}));
if (Track.buckle_curvature != 0.0)
{
@@ -2101,6 +2111,9 @@ void TMoverParameters::rerail()
{
ClearFlag(DamageFlag, dtrain_out);
Derailed = derailment::outcome::none;
// and back on the track
OffTrack.reset();
DerailSide = 0;
derailment_monitor.reset();
derailment_distance = 0.0;
derailment_reported.reset();
@@ -2154,6 +2167,16 @@ void TMoverParameters::Derail(DerailReason const Reason)
nrot = 0.0;
SlippingWheels = false;
}
// physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the
// ground as the vehicles the criteria derail do, and its brake hoses tear
if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1))
{
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::end_of_track;
DerailAcceleration = 0.0;
DerailSide = 0;
tear_brake_hoses(*this);
}
// Print a message in the log.
if (Reason == END_OF_TRACK)
@@ -2171,6 +2194,30 @@ void TMoverParameters::Derail(DerailReason const Reason)
}
}
bool TMoverParameters::leaves_track() const
{
return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none &&
false == OffTrack.active();
}
void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why)
{
if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out))
{
return;
}
// upright, its flange climbs the rail the coupling pulls it over
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::pulled_off;
DerailAcceleration = Acceleration;
DerailSide = Side;
EventFlag = true;
MainSwitch(false, range_t::local);
tear_brake_hoses(*this);
derailment_monitor.reset();
ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why));
}
void TMoverParameters::change_train_velocity(double const Change)
{
// the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one
@@ -2215,6 +2262,11 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap
// abs(ElectricTraction.TractionResistivity * Itot *
// 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci
}
else if (OffTrack.active())
{
// off the track the grade is that of the ground under it, along its heading
RunningShape.dHtrack = Shape.dHtrack;
}
if (CategoryFlag == 4)
OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0);
@@ -6201,8 +6253,10 @@ void TMoverParameters::ComputeTotalForce(double dt)
{
if (Derailed != derailment::outcome::none)
{
// off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side
FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g;
// off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side;
// off the track on the ground, as far as it tipped over (physics.derailment new)
auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(Derailed)};
FStand = friction * (TotalMass - Mred) * g;
}
else if (legacy_derailed_slides(*this))
{
+469
View File
@@ -0,0 +1,469 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
#include "vehicle/derailmotion.h"
#include "McZapkie/derailment.h"
#include "McZapkie/MOVER.h"
#include "utilities/Globals.h"
#include <cmath>
#include <format>
#include <numbers>
// a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what
// the vehicle of TMoverParameters makes of it
using test::definition;
using test::vehicle;
namespace dm = derail_motion;
namespace dr = derailment;
namespace {
constexpr double kmh{1.0 / 3.6};
constexpr double degree{std::numbers::pi / 180.0};
// the given model of derailment for the test, restored after it
class model_setting {
public:
explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; }
~model_setting() { Global.derailment = m_previous; }
model_setting(model_setting const &) = delete;
model_setting &operator=(model_setting const &) = delete;
private:
global_settings::derailment_model m_previous;
};
// EU07 (4E of data/fiz): its dimensions and the centre of gravity of its body
dm::vehicle_shape eu07() {
dm::vehicle_shape shape;
shape.length = 15.915;
shape.width = 2.903;
shape.height = 4.348;
shape.centre_of_gravity = dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered);
shape.contact_spacing = dr::contact_spacing(1.435);
shape.base = 8.0;
return shape;
}
// the lateral acceleration [m/s2] the wheels of EU07 lift at: the wheel unloading of derailment.h reaches 1
double const eu07_tipping{dr::overturning_acceleration(eu07().centre_of_gravity, dr::contact_spacing(1.435))};
// the track along +z at the height 0, its left (+x) the outside of the curve
dm::start leaving(double const Speed, dm::cause const Reason, int const Outward = 0, double const Acceleration = 0.0) {
dm::start start;
start.position = glm::dvec3{0.0};
start.front = glm::dvec3{0.0, 0.0, 1.0};
start.line = start.front;
start.speed = Speed;
start.reason = Reason;
start.outward = Outward;
start.acceleration = Acceleration;
return start;
}
// the ground across the track, along +z: the top of the ballast 0.2 m under the rails out to 3 m each side, then the
// Slope (rise per metre outwards, negative down) to the Depth under the top (above it, rising). as a scenery has it,
// a level ground lies under it all, at the lowest of it: what is over the ceiling asked for isn't found, that is
class profile final : public dm::ground {
public:
profile(double const Slope, double const Depth, bool const Bothsides = false) : m_slope{Slope}, m_depth{Depth}, m_bothsides{Bothsides} {}
std::optional<double> height(double const X, double, double const Ceiling) const override {
constexpr double top{-0.2};
constexpr double edge{3.0};
auto const across{m_bothsides ? std::abs(X) : X};
auto const floor{std::min(top, top + std::clamp(m_slope * 1e6, -std::abs(m_depth), std::abs(m_depth)))};
auto surface{top};
if (across > edge) {
surface += std::clamp(m_slope * (across - edge), -std::abs(m_depth), std::abs(m_depth));
}
return surface <= Ceiling ? surface : floor;
}
private:
double m_slope;
double m_depth;
bool m_bothsides;
};
struct outcome {
double time{0.0};
double travelled{0.0};
double along{0.0};
double across{0.0};
double tipping{0.0};
double roll{0.0};
double height{0.0};
bool lying{false};
double lying_at{-1.0}; // the time it came to lie on its side, -1 never
};
// the vehicle slides as TMoverParameters drives it: its speed along the heading falls with the friction of the motion
// and the gravity of the grade under it, the distance of each step goes to the motion
outcome slide(dm::start const &Start, dm::ground const &Ground, double const Dt = 0.01, dm::vehicle_shape const &Shape = eu07(), double const Seconds = 60.0) {
dm::body body;
body.begin(Start, Shape, Ground);
auto speed{Start.speed};
outcome result;
while (result.time < Seconds) {
auto const direction{speed >= 0.0 ? 1.0 : -1.0};
auto const deceleration{dm::gravity * (body.friction() * direction + body.grade())};
auto next{speed - deceleration * Dt};
if (next * speed <= 0.0 && std::abs(body.grade()) <= body.friction()) {
next = 0.0;
}
body.step(Dt, 0.5 * (speed + next) * Dt, next, Ground);
speed = next;
result.time += Dt;
if (body.lying() && result.lying_at < 0.0) {
result.lying_at = result.time;
}
if (body.at_rest()) {
break;
}
}
result.travelled = body.travelled();
result.along = body.along();
result.across = body.across();
result.tipping = body.tipping();
result.roll = body.roll();
result.height = body.current().position.y;
result.lying = body.lying();
return result;
}
dm::flat_ground const ballast{-0.2};
} // namespace
TEST_CASE("derail motion: the distance it slides goes with the square of the speed and against the friction") {
auto const fast{dm::stopping_distance(133.0 * kmh, dr::off_rails_friction)};
auto const slow{dm::stopping_distance(40.0 * kmh, dr::off_rails_friction)};
REQUIRE(fast.has_value());
REQUIRE(slow.has_value());
CHECK(*fast == doctest::Approx(232.0).epsilon(0.01));
CHECK(*slow == doctest::Approx(21.0).epsilon(0.01));
CHECK(*fast / *slow == doctest::Approx(133.0 * 133.0 / (40.0 * 40.0)).epsilon(1e-9));
// on its side
CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * 0.3 / 0.5).epsilon(1e-9));
// uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop
CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow);
CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow);
CHECK_FALSE(dm::stopping_distance(40.0 * kmh, 0.3, -0.4).has_value());
SUBCASE("the vehicle off the end of the track slides as far, straight on, upright") {
for (auto const speed : {133.0, 40.0}) {
CAPTURE(speed);
auto const result{slide(leaving(speed * kmh, dm::cause::end_of_track), ballast)};
MESSAGE(std::format("off the end of the track at {:.0f} km/h: {:.1f} m in {:.1f} s", speed, result.travelled, result.time));
CHECK(result.travelled == doctest::Approx(*dm::stopping_distance(speed * kmh, dr::off_rails_friction)).epsilon(0.02));
CHECK(result.along == doctest::Approx(result.travelled).epsilon(1e-6));
CHECK(std::abs(result.across) < 1e-6);
CHECK(result.tipping == 0.0);
// on the top of the ballast, not on the rails nor under the ground
CHECK(result.height == doctest::Approx(-0.2));
}
}
SUBCASE("the friction along it rises from the one on its wheels to the one on its side") {
CHECK(dm::sliding_friction(0.0, false) == dr::off_rails_friction);
CHECK(dm::sliding_friction(dm::body::half_turn, false) == dr::overturned_friction);
CHECK(dm::sliding_friction(0.5 * dm::body::half_turn, false) == doctest::Approx(0.5 * (dr::off_rails_friction + dr::overturned_friction)));
CHECK(dm::sliding_friction(0.0, true) == dm::guided_friction);
}
}
TEST_CASE("derail motion: the way it leaves the track by what derailed it") {
SUBCASE("off the end of the track and in a collision: straight on") {
CHECK(dm::departure_angle(dm::cause::end_of_track, 30.0, 10.0) == 0.0);
CHECK(dm::departure_angle(dm::cause::collision, 30.0, 10.0) == 0.0);
auto const result{slide(leaving(100.0 * kmh, dm::cause::collision, 1, 5.0), ballast)};
CHECK(std::abs(result.across) < 1e-6);
}
SUBCASE("the flange climbing the rail: towards the rail it climbed, out of the curve, upright") {
for (auto const outward : {1, -1}) {
CAPTURE(outward);
auto const result{slide(leaving(100.0 * kmh, dm::cause::off_rails, outward, 3.0), ballast)};
MESSAGE(std::format("climbed out of the curve to the {}: {:.1f} m across in {:.1f} m", outward > 0 ? "left" : "right", result.across, result.travelled));
CHECK(result.across * outward > 1.0);
CHECK(result.tipping == 0.0);
CHECK_FALSE(result.lying);
}
// the faster the speed against the sideways one, the smaller the angle
CHECK(dm::departure_angle(dm::cause::off_rails, 40.0, 3.0) < dm::departure_angle(dm::cause::off_rails, 10.0, 3.0));
CHECK(dm::departure_angle(dm::cause::off_rails, 0.1, 1000.0) == dm::most_departure);
}
SUBCASE("backwards, out of the curve as well") {
auto const result{slide(leaving(-100.0 * kmh, dm::cause::off_rails, 1, 3.0), ballast)};
CHECK(result.along < -10.0);
CHECK(result.across > 1.0);
}
SUBCASE("overturned: out of the curve, falling on its side there") {
for (auto const outward : {1, -1}) {
CAPTURE(outward);
auto const result{slide(leaving(120.0 * kmh, dm::cause::overturned, outward, 2.0 * eu07_tipping), ballast)};
MESSAGE(std::format("overturned to the {}: {:.1f} m across in {:.1f} m, on its side after {:.2f} s", outward > 0 ? "left" : "right", result.across, result.travelled, result.lying_at));
CHECK(result.across * outward > 1.0);
CHECK(result.lying);
CHECK(result.tipping * outward == doctest::Approx(dm::body::half_turn));
CHECK(result.roll * outward == doctest::Approx(dm::body::half_turn));
// lying on its side on the top of the ballast, the origin of its model is half the width of its body up
CHECK(result.height == doctest::Approx(-0.2 + 0.5 * eu07().width));
}
}
SUBCASE("pulled off by a coupling: to the side it is pulled to") {
auto const result{slide(leaving(50.0 * kmh, dm::cause::pulled_off, -1, 2.0), ballast)};
CHECK(result.across < -0.1);
}
}
TEST_CASE("derail motion: tipping over goes as far as the overturning went over its limit") {
// the curve keeps pushing it out while its outer wheels are on the rail: the further over the limit, the sooner it lies
auto const barely{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 1.2 * eu07_tipping), ballast)};
auto const well{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping), ballast)};
auto const hard{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 5.0 * eu07_tipping), ballast)};
MESSAGE(std::format("on its side after {:.2f} / {:.2f} / {:.2f} s at a wheel unloading of 1.2 / 2 / 5", barely.lying_at, well.lying_at, hard.lying_at));
REQUIRE(barely.lying);
REQUIRE(well.lying);
REQUIRE(hard.lying);
CHECK(barely.lying_at > well.lying_at);
CHECK(well.lying_at > hard.lying_at);
// it takes its time to fall over, it doesn't jump onto its side
CHECK(hard.lying_at > 0.3);
SUBCASE("a body on the rails stays upright, on a level ground it isn't tipped by anything") {
auto const upright{slide(leaving(120.0 * kmh, dm::cause::off_rails, 1, 2.0 * eu07_tipping), ballast)};
CHECK(upright.tipping == 0.0);
}
SUBCASE("slowing down below the limit, the curve doesn't tip it any more") {
dm::body body;
body.begin(leaving(30.0 * kmh, dm::cause::overturned, 1, 1.05 * eu07_tipping), eu07(), ballast);
// stopped at once: the curve pushes it out no more, it falls back on its wheels
body.step(0.01, 0.0, 0.0, ballast);
for (int step = 0; step < 300; ++step) {
body.step(0.01, 0.0, 0.0, ballast);
}
CHECK_FALSE(body.guided());
CHECK(body.tipping() == 0.0);
}
}
TEST_CASE("derail motion: the ground under it") {
SUBCASE("off the edge of an embankment it slides down the slope and falls on its side towards the bottom") {
// 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 60 km/h
profile const embankment{-1.0 / 1.5, 4.0};
auto start{leaving(60.0 * kmh, dm::cause::off_rails)};
start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)};
auto const result{slide(start, embankment)};
MESSAGE(std::format("down the embankment: {:.1f} m across, {:.1f} m down, tipped {:.0f} degrees, after {:.1f} m", result.across, -0.2 - result.height, result.tipping / degree, result.travelled));
CHECK(result.across > 4.0);
// lying on the slope, its body half its width up off the ground
CHECK(result.height < -1.5);
CHECK(result.lying);
CHECK(result.tipping > 0.0);
}
SUBCASE("on a gentle slope it stays upright, leaning with the ground") {
profile const gentle{-1.0 / 6.0, 4.0};
auto start{leaving(80.0 * kmh, dm::cause::off_rails)};
start.front = glm::dvec3{std::sin(6.0 * degree), 0.0, std::cos(6.0 * degree)};
auto const result{slide(start, gentle)};
CHECK_FALSE(result.lying);
CHECK(result.tipping == 0.0);
// leaning left, down the slope
CHECK(result.roll == doctest::Approx(std::atan(1.0 / 6.0)).epsilon(0.05));
}
SUBCASE("a lower centre of gravity tips over on a steeper slope only") {
// a 1:2.2 slope, 24 degrees: the steepest one EU07 stands on is 1:2.8 (20 degrees), a flat wagon tips past 1:1.7
profile const slope{-1.0 / 2.2, 6.0};
auto start{leaving(50.0 * kmh, dm::cause::off_rails)};
start.front = glm::dvec3{std::sin(10.0 * degree), 0.0, std::cos(10.0 * degree)};
auto low{eu07()};
low.centre_of_gravity = 0.9;
low.height = 2.0;
CHECK(slide(start, slope).lying);
CHECK_FALSE(slide(start, slope, 0.01, low).lying);
}
SUBCASE("in a cutting it climbs the bank, stops sooner and leans (here falls) back towards the track") {
profile const cutting{1.0 / 1.5, 4.0};
auto start{leaving(60.0 * kmh, dm::cause::off_rails)};
start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)};
auto const level{slide(start, ballast)};
auto const result{slide(start, cutting)};
MESSAGE(std::format("into a cutting: {:.1f} m against {:.1f} m on a level ground, roll {:.0f} degrees", result.travelled, level.travelled, result.roll / degree));
CHECK(result.travelled < level.travelled);
CHECK(result.height > -0.2);
CHECK(result.roll < 0.0);
}
SUBCASE("it doesn't sink into the ground, it falls off a step") {
// off a wall 3 m high
profile const wall{-100.0, 3.0};
auto start{leaving(40.0 * kmh, dm::cause::off_rails)};
start.front = glm::dvec3{std::sin(20.0 * degree), 0.0, std::cos(20.0 * degree)};
dm::body body;
body.begin(start, eu07(), wall);
auto lowest{0.0};
auto speed{start.speed};
for (int index = 0; index < 1000; ++index) {
auto const next{std::max(0.0, speed - dm::gravity * body.friction() * 0.01)};
body.step(0.01, 0.5 * (speed + next) * 0.01, next, wall);
speed = next;
auto const &position{body.current().position};
auto const ground{*wall.height(position.x, position.z, 1e9)};
CHECK(position.y >= ground - 1e-9);
lowest = std::min(lowest, position.y);
}
CHECK(lowest < -3.0);
}
}
TEST_CASE("derail motion: the same with steps of 0.01, 0.03 and 0.05 s") {
profile const embankment{-1.0 / 1.5, 4.0};
auto down{leaving(60.0 * kmh, dm::cause::off_rails)};
down.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)};
auto const overturning{leaving(120.0 * kmh, dm::cause::overturned, -1, 2.0 * eu07_tipping)};
auto const climbing{leaving(100.0 * kmh, dm::cause::off_rails, 1, 3.0)};
auto const fine{slide(down, embankment, 0.01)};
auto const finetip{slide(overturning, ballast, 0.01)};
auto const fineclimb{slide(climbing, ballast, 0.01)};
for (auto const dt : {0.03, 0.05}) {
CAPTURE(dt);
auto const coarse{slide(down, embankment, dt)};
CHECK(coarse.travelled == doctest::Approx(fine.travelled).epsilon(0.02));
CHECK(coarse.across == doctest::Approx(fine.across).epsilon(0.05));
CHECK(coarse.lying == fine.lying);
auto const coarsetip{slide(overturning, ballast, dt)};
CHECK(coarsetip.travelled == doctest::Approx(finetip.travelled).epsilon(0.02));
CHECK(coarsetip.across == doctest::Approx(finetip.across).epsilon(0.02));
CHECK(coarsetip.lying_at == doctest::Approx(finetip.lying_at).epsilon(0.1));
auto const coarseclimb{slide(climbing, ballast, dt)};
CHECK(coarseclimb.across == doctest::Approx(fineclimb.across).epsilon(0.02));
}
}
TEST_CASE("derail motion: the ground of the scenery") {
SUBCASE("the triangles of the terrain") {
std::vector<dm::mesh_ground::triangle> triangles;
// a square 10 m wide at 2 m rising to 4 m along x, and a roof over half of it at 10 m
triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}});
triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}, glm::dvec3{0.0, 2.0, 10.0}});
triangles.push_back({glm::dvec3{0.0, 10.0, 0.0}, glm::dvec3{5.0, 10.0, 0.0}, glm::dvec3{0.0, 10.0, 10.0}});
dm::mesh_ground const terrain{triangles, glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0}, 2.0};
CHECK(terrain.size() == 3);
CHECK(*terrain.height(5.0, 5.0, 8.0) == doctest::Approx(3.0));
CHECK(*terrain.height(7.5, 2.5, 8.0) == doctest::Approx(3.5));
// under the roof the ground, over it the roof
CHECK(*terrain.height(1.0, 1.0, 8.0) == doctest::Approx(2.2));
CHECK(*terrain.height(1.0, 1.0, 12.0) == doctest::Approx(10.0));
CHECK_FALSE(terrain.height(12.0, 5.0, 8.0).has_value());
CHECK_FALSE(terrain.height(50.0, 5.0, 8.0).has_value());
CHECK(terrain.covers(14.0, -4.0));
CHECK_FALSE(terrain.covers(16.0, 0.0));
}
SUBCASE("the bed of the track over the terrain, level ground without one") {
dm::formation bed;
bed.point = glm::dvec3{0.0, 10.0, 0.0};
bed.direction = glm::dvec3{0.0, 0.0, 1.0};
bed.half_width = 2.0;
CHECK(bed.height(1.5, 100.0) == doctest::Approx(9.8));
CHECK(bed.height(-2.0, -50.0) == doctest::Approx(9.8));
CHECK(bed.height(3.5, 0.0) == doctest::Approx(9.8 - 1.0));
dm::flat_ground const low{7.0};
dm::site const embankment{&low, bed};
CHECK(*embankment.height(0.0, 0.0, 12.0) == doctest::Approx(9.8));
CHECK(*embankment.height(4.0, 0.0, 12.0) == doctest::Approx(9.8 - 2.0 / 1.5));
CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0));
dm::site const bare{nullptr, bed};
CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8));
}
}
TEST_CASE("derail motion: a coupling pulling sideways") {
// EU07, 80 t on 4 axles: a wheel carries 98 kN
CHECK(dm::pull_ratio(300e3, 0.0, 80e3, 4) == 0.0);
CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) == doctest::Approx(0.5 * 150e3 / (80e3 * dm::gravity / 8.0)));
CHECK(dm::pull_ratio(-300e3, -30.0 * degree, 80e3, 4) == dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4));
// an empty wagon of 20 t goes over the climbing limit with a force the locomotive takes
CHECK(dm::pull_ratio(300e3, 30.0 * degree, 20e3, 4) > dr::climbing_limit);
CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) < dr::climbing_limit);
}
TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment new only") {
test::track curve;
curve.radius = 300.0;
auto const critical{dr::overturning_speed(300.0, 0.0, eu07().centre_of_gravity, 1.435) / kmh};
SUBCASE("new: derailed by the criteria it leaves the track, then slides with the friction of the motion") {
model_setting const physical{global_settings::derailment_model::physical};
vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 20.0};
for (int step = 0; step < 10; ++step) {
eu07vehicle.step(curve);
}
REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned);
CHECK(eu07vehicle->DerailCause == dm::cause::overturned);
CHECK(eu07vehicle->DerailAcceleration > eu07_tipping);
CHECK(eu07vehicle->leaves_track());
eu07vehicle->OffTrack.begin(leaving(eu07vehicle->V, eu07vehicle->DerailCause, 1, eu07vehicle->DerailAcceleration), eu07(), ballast);
CHECK_FALSE(eu07vehicle->leaves_track());
// tipping over on its outer wheels it hardly slows down
auto const start{eu07vehicle->V};
for (int step = 0; step < 20; ++step) {
eu07vehicle.step(curve);
}
auto const deceleration{(start - eu07vehicle->V) / 0.2};
CHECK(deceleration == doctest::Approx(dm::guided_friction * dr::gravity * 80.0 / 96.0).epsilon(0.1));
// back on the rails, not off the track any more
eu07vehicle->repair_damage();
CHECK_FALSE(eu07vehicle->OffTrack.active());
CHECK_FALSE(eu07vehicle->leaves_track());
}
SUBCASE("new: off the end of the track it slides on its wheels, straight on") {
model_setting const physical{global_settings::derailment_model::physical};
vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 40.0};
eu07vehicle.damage_track(dtrack_norail);
eu07vehicle.step();
REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out));
CHECK(eu07vehicle->Derailed == dr::outcome::off_rails);
CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track);
CHECK(eu07vehicle->leaves_track());
}
SUBCASE("new: a vehicle pulled off by a coupling, upright, to the side it was pulled to") {
model_setting const physical{global_settings::derailment_model::physical};
vehicle pulled{definition::fiz("4e_v1/4e"), 40.0};
pulled->pull_off(-1, 5.0, "test");
CHECK(TestFlag(pulled->DamageFlag, dtrain_out));
CHECK(pulled->Derailed == dr::outcome::off_rails);
CHECK(pulled->DerailCause == dm::cause::pulled_off);
CHECK(pulled->DerailSide == -1);
CHECK(pulled->leaves_track());
}
}
TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle stays on the track, as before") {
test::track curve;
curve.radius = 300.0;
for (auto const model : {global_settings::derailment_model::monitor, global_settings::derailment_model::old}) {
auto const number{static_cast<int>(model)};
CAPTURE(number);
model_setting const setting{model};
vehicle fast{definition::fiz("4e_v1/4e"), 160.0};
for (int step = 0; step < 600; ++step) {
fast.step(curve);
}
REQUIRE(TestFlag(fast->DamageFlag, dtrain_out));
CHECK(fast->Derailed == dr::outcome::none);
CHECK_FALSE(fast->leaves_track());
CHECK_FALSE(fast->OffTrack.active());
// stopped dead by the legacy model
CHECK(fast->V == doctest::Approx(0.0).epsilon(0.01));
vehicle ending{definition::fiz("4e_v1/4e"), 40.0};
ending.damage_track(dtrack_norail);
ending.step();
REQUIRE(TestFlag(ending->DamageFlag, dtrain_out));
CHECK(ending->Derailed == dr::outcome::none);
CHECK_FALSE(ending->leaves_track());
// nor is a vehicle pulled off it
vehicle pulled{definition::fiz("4e_v1/4e"), 40.0};
pulled->pull_off(1, 5.0, "test");
CHECK_FALSE(TestFlag(pulled->DamageFlag, dtrain_out));
}
}
+426
View File
@@ -0,0 +1,426 @@
/*
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 "vehicle/derailmotion.h"
#include "McZapkie/derailment.h"
#include <algorithm>
#include <cmath>
#include <limits>
namespace derail_motion {
namespace {
glm::dvec3 const world_up{0.0, 1.0, 0.0};
// the vector level, of unit length; the fallback for one standing up
glm::dvec3 level(glm::dvec3 const &Vector, glm::dvec3 const &Fallback = {0.0, 0.0, 1.0}) {
glm::dvec3 const flat{Vector.x, 0.0, Vector.z};
auto const length{glm::length(flat)};
return length > 1e-9 ? flat / length : Fallback;
}
// to the left of a level heading, as TDynamicObject has it: up x front
glm::dvec3 left_of(glm::dvec3 const &Front) {
return glm::dvec3{Front.z, 0.0, -Front.x};
}
// the vector turned about the axis by the angle, right-handed
glm::dvec3 turned(glm::dvec3 const &Vector, glm::dvec3 const &Axis, double const Angle) {
auto const c{std::cos(Angle)};
auto const s{std::sin(Angle)};
return Vector * c + glm::cross(Axis, Vector) * s + Axis * (glm::dot(Axis, Vector) * (1.0 - c));
}
double sign_of(double const Value) {
if (Value > 0.0) {
return 1.0;
}
return Value < 0.0 ? -1.0 : 0.0;
}
// the height of the triangle over the point, if it is over it (in the plan)
std::optional<double> height_in(mesh_ground::triangle const &Triangle, double const X, double const Z) {
auto const &a{Triangle[0]};
auto const &b{Triangle[1]};
auto const &c{Triangle[2]};
auto const determinant{(b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z)};
if (std::abs(determinant) < 1e-12) {
// standing on its edge, a wall
return std::nullopt;
}
auto const u{((b.z - c.z) * (X - c.x) + (c.x - b.x) * (Z - c.z)) / determinant};
auto const v{((c.z - a.z) * (X - c.x) + (a.x - c.x) * (Z - c.z)) / determinant};
auto const w{1.0 - u - v};
constexpr double edge{-1e-9};
if (u < edge || v < edge || w < edge) {
return std::nullopt;
}
return u * a.y + v * b.y + w * c.y;
}
} // namespace
double sliding_friction(double const Tipping, bool const Guided) {
if (Guided) {
return guided_friction;
}
auto const share{std::clamp(std::abs(Tipping) / body::half_turn, 0.0, 1.0)};
return std::lerp(derailment::off_rails_friction, derailment::overturned_friction, share);
}
double departure_angle(cause const Cause, double const Speed, double const Acceleration) {
if (Cause == cause::end_of_track || Cause == cause::collision) {
return 0.0;
}
auto const sideways{std::sqrt(2.0 * std::abs(Acceleration) * climb_width)};
return std::min(most_departure, std::atan2(sideways, std::max(std::abs(Speed), 1.0)));
}
std::optional<double> stopping_distance(double const Speed, double const Friction, double const Grade) {
auto const angle{std::atan(Grade)};
auto const deceleration{gravity * (Friction * std::cos(angle) + std::sin(angle))};
if (deceleration <= 0.0) {
return std::nullopt;
}
return Speed * Speed / (2.0 * deceleration);
}
double pull_ratio(double const Force, double const Angle, double const Mass, int const Axles) {
auto const axles{std::max(Axles, 2)};
auto const load{Mass * gravity / (2.0 * axles)};
if (load <= 0.0) {
return 0.0;
}
auto const across{std::abs(Force * std::sin(Angle))};
return across / (0.5 * axles) / load;
}
// ---- the ground
std::optional<double> flat_ground::height(double, double, double) const {
return m_level;
}
mesh_ground::mesh_ground(std::vector<triangle> const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double const Cell) : m_min{Min}, m_max{glm::max(Max, Min + glm::dvec2{1.0})}, m_cell{std::max(Cell, 1.0)} {
auto const size{m_max - m_min};
// a million cells at most
m_cell = std::max(m_cell, std::sqrt(size.x * size.y / 1e6));
m_columns = static_cast<std::size_t>(std::ceil(size.x / m_cell));
m_rows = static_cast<std::size_t>(std::ceil(size.y / m_cell));
m_cells.resize(m_columns * m_rows);
auto const column = [this](double const X) { return static_cast<std::size_t>(std::clamp(std::floor((X - m_min.x) / m_cell), 0.0, static_cast<double>(m_columns - 1))); };
auto const row = [this](double const Z) { return static_cast<std::size_t>(std::clamp(std::floor((Z - m_min.y) / m_cell), 0.0, static_cast<double>(m_rows - 1))); };
for (auto const &triangle : Triangles) {
auto const low{glm::min(glm::min(triangle[0], triangle[1]), triangle[2])};
auto const high{glm::max(glm::max(triangle[0], triangle[1]), triangle[2])};
if (high.x < m_min.x || low.x > m_max.x || high.z < m_min.y || low.z > m_max.y) {
continue;
}
auto const index{m_triangles.size()};
m_triangles.push_back(triangle);
for (auto r = row(low.z); r <= row(high.z); ++r) {
for (auto c = column(low.x); c <= column(high.x); ++c) {
m_cells[r * m_columns + c].push_back(index);
}
}
}
}
bool mesh_ground::covers(double const X, double const Z) const {
return X >= m_min.x && X <= m_max.x && Z >= m_min.y && Z <= m_max.y;
}
std::optional<std::size_t> mesh_ground::cell_of(double const X, double const Z) const {
if (false == covers(X, Z) || m_cells.empty()) {
return std::nullopt;
}
auto const column{std::min(static_cast<std::size_t>((X - m_min.x) / m_cell), m_columns - 1)};
auto const row{std::min(static_cast<std::size_t>((Z - m_min.y) / m_cell), m_rows - 1)};
return row * m_columns + column;
}
std::optional<double> mesh_ground::height(double const X, double const Z, double const Ceiling) const {
auto const cell{cell_of(X, Z)};
if (false == cell.has_value()) {
return std::nullopt;
}
std::optional<double> highest;
for (auto const index : m_cells[*cell]) {
auto const found{height_in(m_triangles[index], X, Z)};
if (found.has_value() && *found <= Ceiling && (false == highest.has_value() || *found > *highest)) {
highest = found;
}
}
return highest;
}
double formation::height(double const X, double const Z) const {
auto const across{std::abs(glm::dot(glm::dvec3{X, 0.0, Z} - glm::dvec3{point.x, 0.0, point.z}, left_of(level(direction))))};
auto const top{point.y - depth};
if (across <= half_width) {
return top;
}
return top - (across - half_width) / std::max(slope, 0.1);
}
std::optional<double> site::height(double const X, double const Z, double const Ceiling) const {
auto const bed{m_bed.height(X, Z)};
std::optional<double> result;
if (m_terrain == nullptr) {
// no terrain: level with the top of the ballast
result = m_bed.point.y - m_bed.depth;
}
else {
result = m_terrain->height(X, Z, Ceiling);
}
if (bed <= Ceiling && (false == result.has_value() || bed > *result)) {
result = bed;
}
return result;
}
// ---- the vehicle
void body::begin(start const &Start, vehicle_shape const &Shape, ground const &Ground) {
*this = body{};
m_active = true;
m_reason = Start.reason;
m_shape = Shape;
m_pivot = 0.5 * std::max(Shape.contact_spacing, 0.5);
auto const centre{std::max(Shape.centre_of_gravity, 0.3)};
m_lever = centre + Shape.flexibility * std::max(0.0, centre - Shape.roll_centre);
m_tipangle = std::atan2(m_pivot, m_lever);
m_reach = std::hypot(m_pivot, m_lever);
// the body a box rolling about its middle, carried over to the wheels it tips about
m_gyration = m_reach * m_reach + (Shape.width * Shape.width + Shape.height * Shape.height) / 12.0;
m_position = Start.position;
m_origin = Start.position;
m_front = level(Start.front);
m_line = level(Start.line, m_front);
m_speed = Start.speed;
// out of the curve, the way it travels
auto const direction{Start.speed < 0.0 ? -1.0 : 1.0};
auto const turn{Start.outward * direction * departure_angle(Start.reason, Start.speed, Start.acceleration)};
m_front = level(turned(m_front, world_up, turn), m_front);
if (Start.reason == cause::overturned) {
m_guided = true;
m_outward = Start.outward != 0 ? Start.outward : 1;
m_guideacceleration = std::abs(Start.acceleration);
m_guidespeed = std::max(std::abs(Start.speed), 0.1);
}
auto const foot{find_footing(Ground)};
m_grade = foot.grade;
m_cross = foot.cross;
place();
}
void body::step(double const Dt, double const Distance, double const Speed, ground const &Ground) {
if (false == m_active || Dt <= 0.0) {
return;
}
auto const steps{std::max(1, static_cast<int>(std::ceil(Dt / substep - 1e-9)))};
auto const dt{Dt / steps};
auto const startspeed{m_speed};
for (int index = 1; index <= steps; ++index) {
auto const speed{std::lerp(startspeed, Speed, static_cast<double>(index) / steps)};
advance(dt, Distance / steps, speed, Ground);
}
m_speed = Speed;
place();
}
void body::advance(double const Dt, double const Distance, double const Speed, ground const &Ground) {
m_position += m_front * Distance + left_of_heading() * (m_lateral * Dt);
m_travelled += std::hypot(Distance, m_lateral * Dt);
auto const foot{find_footing(Ground)};
m_grade = foot.grade;
m_cross = foot.cross;
fall(Dt, foot.level, std::hypot(Distance, m_lateral * Dt));
slide(Dt, foot.cross);
tip(Dt, foot.cross, Speed);
if (m_guided) {
m_guidetime += Dt;
if (m_tipping >= m_tipangle || std::abs(Speed) < 0.5 || m_guidetime > guidance_time) {
m_guided = false;
}
}
}
body::footing body::find_footing(ground const &Ground) const {
auto const left{left_of_heading()};
// a step up under the middle, and as much more under a support away from it as a slope of 2 in 1 rises: what is
// higher is over the vehicle, not under it (a bridge, a roof), and the ground under the slope of a bank isn't the
// ground the support stands on
constexpr double steepest{2.0};
auto const sample = [&Ground, this](glm::dvec3 const &Point) {
auto const reach{std::hypot(Point.x - m_position.x, Point.z - m_position.z)};
return Ground.height(Point.x, Point.z, m_position.y + step_up + steepest * reach).value_or(m_position.y);
};
auto const ahead{m_front * (0.5 * std::max(m_shape.base, 1.0))};
// upright it stands on its wheels; tipping over, it comes to rest on the side of its body, which reaches out
// from the wheels it tips about as far as the body is high
auto const lean{std::sin(m_tipping)};
auto const middle{left * (m_side * lean * 0.5 * m_shape.height)};
auto const span{m_pivot + lean * std::max(0.0, 0.5 * m_shape.height - m_pivot)};
auto const aside{left * span};
auto const frontleft{sample(m_position + middle + ahead + aside)};
auto const frontright{sample(m_position + middle + ahead - aside)};
auto const rearleft{sample(m_position + middle - ahead + aside)};
auto const rearright{sample(m_position + middle - ahead - aside)};
footing result;
result.level = std::max(0.25 * (frontleft + frontright + rearleft + rearright), sample(m_position));
// a step under one support is no slope steeper than 2 in 1
result.grade = std::clamp((frontleft + frontright - rearleft - rearright) / (2.0 * std::max(m_shape.base, 1.0)), -steepest, steepest);
result.cross = std::clamp((frontleft + rearleft - frontright - rearright) / (4.0 * span), -steepest, steepest);
return result;
}
void body::fall(double const Dt, double const Level, double const Travel) {
// on the ground it follows it down a slope as steep as 1:1.5; off a steeper drop it falls
constexpr double follows{1.0 / 1.5};
if (m_grounded && m_position.y - Level <= std::max(0.02, follows * Travel)) {
m_position.y = Level;
return;
}
m_fallspeed -= gravity * Dt;
auto const height{m_position.y + m_fallspeed * Dt};
m_grounded = (height <= Level);
if (m_grounded) {
m_position.y = Level;
m_fallspeed = 0.0;
}
else {
m_position.y = height;
}
}
void body::slide(double const Dt, double const Cross) {
if (false == m_grounded) {
// in the air nothing holds it, nor pushes it
return;
}
auto const angle{std::atan(Cross)};
// down the slope, to the left positive; held by the friction of its weight on the slope
m_lateral -= gravity * std::sin(angle) * Dt;
auto const held{lateral_friction * gravity * std::cos(angle) * Dt};
if (std::abs(m_lateral) <= held) {
m_lateral = 0.0;
}
else {
m_lateral -= sign_of(m_lateral) * held;
}
}
double body::lateral_load(double const Cross, double const Speed) const {
auto const angle{std::atan(Cross)};
auto load{0.0};
if (m_grounded) {
if (m_lateral != 0.0) {
// sliding across, the friction under its wheels or its side trips it the way it slides
load = sign_of(m_lateral) * lateral_friction * gravity * std::cos(angle);
}
else {
// standing on the slope, the weight pulls it down the slope, the friction holds its feet
load = -gravity * std::sin(angle);
}
}
if (m_guided) {
auto const share{Speed / m_guidespeed};
load += m_outward * m_guideacceleration * share * share;
}
return load;
}
void body::tip(double const Dt, double const Cross, double const Speed) {
if (lying()) {
return;
}
auto const normal{gravity * std::cos(std::atan(Cross))};
auto const load{lateral_load(Cross, Speed)};
if (m_side == 0) {
// upright: it starts to tip once the load lifts the wheels of the other side
if (std::abs(load) * std::cos(m_tipangle) - normal * std::sin(m_tipangle) <= 0.0) {
return;
}
m_side = load > 0.0 ? 1 : -1;
}
auto const angle{m_tipping - m_tipangle};
auto const acceleration{m_reach / m_gyration * (m_side * load * std::cos(angle) + normal * std::sin(angle))};
m_tiprate += acceleration * Dt;
m_tipping += m_tiprate * Dt;
if (m_tipping <= 0.0) {
// back on its wheels
m_tipping = 0.0;
m_tiprate = 0.0;
m_side = 0;
}
else if (m_tipping >= half_turn) {
// on its side, where it stays
m_tipping = half_turn;
m_tiprate = 0.0;
}
}
glm::dvec3 body::left_of_heading() const {
return left_of(m_front);
}
double body::roll() const {
// the ground rising to the left leans it to the right
return tipping() - std::atan(m_cross);
}
double body::along() const {
return glm::dot(m_position - m_origin, m_line);
}
double body::across() const {
return glm::dot(m_position - m_origin, left_of(m_line));
}
bool body::at_rest() const {
return m_active && m_grounded && std::abs(m_speed) < 0.01 && m_lateral == 0.0 && m_tiprate == 0.0 && false == m_guided;
}
void body::place() {
// the plane of the ground under the supports
auto const front{glm::normalize(m_front + world_up * m_grade)};
auto const flatleft{glm::normalize(left_of_heading() + world_up * m_cross)};
auto const up{glm::normalize(glm::cross(front, flatleft))};
auto const left{glm::cross(up, front)};
// tipped about the wheels of its side: turned about the front, the up going over to that side
auto const angle{-m_side * m_tipping};
auto const pivot{m_position + left * (m_side * m_pivot)};
auto origin{pivot + turned(m_position - pivot, front, angle)};
auto const tippedleft{turned(left, front, angle)};
auto const tippedup{turned(up, front, angle)};
// the body doesn't go into the ground: the lowest of the edges of its box on it, from the rails to its roof
auto lowest{std::numeric_limits<double>::max()};
for (auto const across : {-0.5 * m_shape.width, 0.5 * m_shape.width}) {
for (auto const height : {0.0, m_shape.height}) {
lowest = std::min(lowest, glm::dot(origin + tippedleft * across + tippedup * height - m_position, up));
}
}
if (lowest < 0.0) {
origin -= up * lowest;
}
m_pose.position = origin;
m_pose.front = front;
m_pose.left = tippedleft;
m_pose.up = tippedup;
}
} // namespace derail_motion
+293
View File
@@ -0,0 +1,293 @@
/*
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 <array>
#include <cstddef>
#include <optional>
#include <vector>
#include <glm/glm.hpp>
// a rail vehicle off the rails (physics.derailment new, see McZapkie/derailment.h for when it derails): from then on
// it doesn't follow the track any more, it moves on the ground by itself until the friction stops it.
//
// along: the longitudinal motion stays with the physics of the vehicle (TMoverParameters), which brakes it with the
// friction() of this one, takes the grade() under it and passes the forces of the couplings on; each step gives
// the distance travelled along the heading of the vehicle
// the heading: the one the vehicle had when it derailed, turned out of the curve by the sideways speed it left the
// rail with: none off the end of the track, the speed of the flange climbing over the rail head (or of the wheels
// lifting over it) otherwise. it stays the heading from then on: the vehicle runs on straight, so in a curve it
// leaves the track to its outside, on a buckle towards the bulge
// sideways: the vehicle slides across its heading only where the ground slopes across it more than the friction
// holds, down an embankment say
// the height and the attitude: the ground under the supports of the vehicle (the ends of its wheelbase, the wheels
// of both sides) gives its height, its pitch and its roll; it doesn't sink into the ground, it falls off a step
// tipping over: about the wheels of one side, the body as a rigid one with the lean of its suspension, so it tips at
// the very lateral acceleration the wheel unloading of McZapkie/derailment.h reaches 1 at. what tips it: the
// overturning in the curve while its outer wheels still run on the rail (the curve keeps pushing it out as v^2/R,
// the excess over the limit the faster it tips), the slope of the ground across it, and the friction under it
// while it slides sideways. once over its tipping angle it falls on its side, at 90 degrees, and stays there
//
// the steps are cut to 0.01 s inside, so the result doesn't depend on the step of the simulation
namespace derail_motion {
inline constexpr double gravity{9.81}; // [m/s2]
// the longest step of the motion [s]
inline constexpr double substep{0.01};
// what put the vehicle off the rails, for the way it leaves the track
enum class cause {
off_rails, // the flange climbed the rail
overturned, // the vehicle fell over out of the curve
end_of_track, // it ran off the end of the track: straight on
pulled_off, // the coupling of a vehicle off the track pulled it off sideways
collision // overriding, or pushed off the track in a collision: straight on
};
// ---- the friction [-]
// of a vehicle tipping over on its outer wheels, which still roll on the outer rail
inline constexpr double guided_friction{0.1};
// of the wheels, or of the body on its side, sliding across the heading
inline constexpr double lateral_friction{0.5};
// the friction along the heading: upright on its wheels on the sleepers and the ballast, rising to the friction of a
// vehicle on its side (McZapkie/derailment.h) as it tips over
double sliding_friction(double Tipping, bool Guided);
// ---- the way the vehicle leaves the track
// how far the flange or the wheel goes sideways over the head of the rail before it drops off it [m]
inline constexpr double climb_width{0.1};
// the largest angle the vehicle turns off the track by [rad]
inline constexpr double most_departure{0.2};
// the angle [rad] the heading turns out of the curve by: the sideways speed sqrt(2 a w) the lateral acceleration a
// [m/s2] gives the wheels over the climb width w, against the speed [m/s]. none off the end of the track or in a
// collision
double departure_angle(cause Cause, double Speed, double Acceleration);
// the distance [m] a vehicle slides from the speed [m/s] with the friction, on the grade (rise per metre along the
// way); none when the grade doesn't let it stop
std::optional<double> stopping_distance(double Speed, double Friction, double Grade = 0.0);
// the Y/Q of the leading wheel of an end of a vehicle which the coupling pulls (or pushes) at the angle [rad] to its
// axis with the force [N]: the part across, taken by the axles of that end (half of them), against the static load of
// a wheel of the vehicle of the mass [kg]
double pull_ratio(double Force, double Angle, double Mass, int Axles);
// ---- the ground
// where the vehicle can find the ground
class ground {
public:
virtual ~ground() = default;
// the height of the ground at (X, Z): of the highest surface there at or under Ceiling; none where there is none
virtual std::optional<double> height(double X, double Z, double Ceiling) const = 0;
};
// level everywhere
class flat_ground final : public ground {
public:
explicit flat_ground(double Level) : m_level{Level} {}
std::optional<double> height(double X, double Z, double Ceiling) const override;
private:
double m_level;
};
// the triangles of the terrain of the scenery, kept in square cells for the lookup
class mesh_ground final : public ground {
public:
using triangle = std::array<glm::dvec3, 3>;
// the triangles which reach into the rectangle from Min to Max (x, z), in cells of the size [m]
mesh_ground(std::vector<triangle> const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double Cell = 8.0);
std::optional<double> height(double X, double Z, double Ceiling) const override;
// whether the point is inside the rectangle the triangles were taken for
bool covers(double X, double Z) const;
std::size_t size() const { return m_triangles.size(); }
glm::dvec2 const &minimum() const { return m_min; }
glm::dvec2 const &maximum() const { return m_max; }
private:
std::optional<std::size_t> cell_of(double X, double Z) const;
std::vector<triangle> m_triangles;
std::vector<std::vector<std::size_t>> m_cells; // the triangles reaching into each cell
glm::dvec2 m_min;
glm::dvec2 m_max;
double m_cell;
std::size_t m_columns{0};
std::size_t m_rows{0};
};
// the bed of the track at the place nearest to the vehicle: the top of the ballast under the rails, level out to the
// edge of the formation, then the slope of the embankment going down
struct formation {
glm::dvec3 point{0.0}; // on the axis of the track, at the height of the rails
glm::dvec3 direction{0.0, 0.0, 1.0}; // of the axis
double depth{0.2}; // of the top of the ballast under the rails [m]
double half_width{2.0}; // from the axis to the edge of the top [m]
double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment
double height(double X, double Z) const;
};
// the ground as the vehicle finds it: the terrain of the scenery where it has any, level with the top of the ballast
// where it has none (a scenery without terrain), and the bed of the track over it
class site final : public ground {
public:
explicit site(ground const *Terrain = nullptr, formation const &Bed = {}) : m_terrain{Terrain}, m_bed{Bed} {}
void terrain(ground const *Terrain) { m_terrain = Terrain; }
// the bed moves along the track with the vehicle
void bed(formation const &Bed) { m_bed = Bed; }
formation const &bed() const { return m_bed; }
std::optional<double> height(double X, double Z, double Ceiling) const override;
private:
ground const *m_terrain;
formation m_bed;
};
// ---- the vehicle
// what of the vehicle the motion takes
struct vehicle_shape {
double length{20.0}; // over the buffers [m]
double width{3.0}; // of the body [m]
double height{4.0}; // of the body above the rail [m]
double centre_of_gravity{1.5}; // its height above the rail [m]
double contact_spacing{1.5}; // of the wheels of a wheelset [m]
double base{10.0}; // between the bogie pivots or the outer axles, which it rests on lengthwise [m]
// the lean of the body on the suspension, as McZapkie/derailment.h takes it: flexibility and roll centre
double flexibility{0.4};
double roll_centre{0.5};
};
// how it left the rails
struct start {
glm::dvec3 position{0.0}; // of the vehicle, at the height of the rails
glm::dvec3 front{0.0, 0.0, 1.0}; // the way its front faces
glm::dvec3 line{0.0, 0.0, 1.0}; // the direction of the track there, to measure the offset across it by
double speed{0.0}; // along the front [m/s]
cause reason{cause::off_rails};
// the outer side of the curve of the line under it: 1 to the left of its front, -1 to the right, 0 straight
int outward{0};
double acceleration{0.0}; // the lateral acceleration of the body when it derailed, out of the curve [m/s2]
};
// where the body is and how it lies: the origin of its model, at the height of the rails between its wheels when
// upright, and its axes
struct pose {
glm::dvec3 position{0.0};
glm::dvec3 front{0.0, 0.0, 1.0};
glm::dvec3 left{1.0, 0.0, 0.0};
glm::dvec3 up{0.0, 1.0, 0.0};
};
class body {
public:
// the vehicle leaves the rails
void begin(start const &Start, vehicle_shape const &Shape, ground const &Ground);
// the step of Dt [s], in which the vehicle travelled Distance [m] along its heading (forwards along its front) and
// has the Speed [m/s] along it at its end
void step(double Dt, double Distance, double Speed, ground const &Ground);
// back on the rails, or never off them
void reset() { *this = body{}; }
bool active() const { return m_active; }
pose const &current() const { return m_pose; }
// the friction along the heading now, of its weight
double friction() const { return sliding_friction(m_tipping, m_guided); }
// the rise of the ground per metre along the heading, for the force of the gravity along it
double grade() const { return m_grade; }
// how far the body tipped over from its wheels [rad], to the left positive; 90 degrees: it lies on its side
double tipping() const { return m_side * m_tipping; }
// the roll of the body against the level [rad], to the left positive: the tipping and the slope across it
double roll() const;
bool lying() const { return m_tipping >= half_turn - 1e-9; }
// still on its outer wheels on the rail, tipping over out of the curve
bool guided() const { return m_guided; }
// the distance it went on the ground since it left the rails [m]
double travelled() const { return m_travelled; }
// from the place it left the rails at: along the line of the track there, and across it, to the left positive [m]
double along() const;
double across() const;
// the speed it slides with sideways, to the left of its front positive [m/s]
double sideways() const { return m_lateral; }
// at rest: not sliding, not tipping, on the ground
bool at_rest() const;
glm::dvec3 const &heading() const { return m_front; }
cause reason() const { return m_reason; }
// the vehicle the motion was begun with
vehicle_shape const &shape() const { return m_shape; }
static constexpr double half_turn{1.5707963267948966};
private:
// the ground under the supports of the vehicle
struct footing {
double level{0.0}; // under the middle, not under any support
double grade{0.0}; // rise per metre forwards
double cross{0.0}; // rise per metre to the left
};
void advance(double Dt, double Distance, double Speed, ground const &Ground);
footing find_footing(ground const &Ground) const;
// down to the ground at the Level, or onto it, having travelled Travel [m] over the ground in the step
void fall(double Dt, double Level, double Travel);
void slide(double Dt, double Cross);
void tip(double Dt, double Cross, double Speed);
// the lateral acceleration [m/s2] on the centre of gravity, to the left positive, in the plane of the ground
double lateral_load(double Cross, double Speed) const;
void place();
glm::dvec3 left_of_heading() const;
bool m_active{false};
cause m_reason{cause::off_rails};
vehicle_shape m_shape;
// the geometry of the tipping: half the spacing of the wheels, the height the lateral force leans the body at,
// the distance of the centre of gravity from the wheels it tips about, the angle it tips over past, and the
// square of the radius of gyration about them
double m_pivot{0.75};
double m_lever{1.8};
double m_reach{1.9};
double m_tipangle{0.4};
double m_gyration{5.0};
glm::dvec3 m_position{0.0}; // of the middle of the vehicle on the ground (at its base)
glm::dvec3 m_front{0.0, 0.0, 1.0}; // the heading, level
glm::dvec3 m_origin{0.0}; // where it left the rails
glm::dvec3 m_line{0.0, 0.0, 1.0}; // the direction of the track there, level
double m_fallspeed{0.0}; // [m/s], downwards negative
// on the ground, not falling. it leaves the rails above the top of the ballast, and drops onto it
bool m_grounded{false};
double m_lateral{0.0}; // [m/s], to the left positive
double m_grade{0.0};
double m_cross{0.0};
int m_side{0}; // the side it tips to: 1 left, -1 right, 0 upright
double m_tipping{0.0}; // [rad]
double m_tiprate{0.0}; // [rad/s]
// overturning in the curve: the lateral acceleration of the curve at the speed it derailed at, which goes with the
// square of the speed, the side out of the curve, and how long it has been tipping
bool m_guided{false};
double m_guideacceleration{0.0};
double m_guidespeed{0.0};
int m_outward{0};
double m_guidetime{0.0};
double m_speed{0.0};
double m_travelled{0.0};
pose m_pose;
};
// how long the curve can keep tipping over a vehicle on its outer wheels [s]
inline constexpr double guidance_time{5.0};
// how high a step up the vehicle can climb onto, for the ground under it [m]
inline constexpr double step_up{1.0};
} // namespace derail_motion