18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 06:35:21 +01:00

feat(physics): buffer stops at the free ends of the tracks

A free end of a rail track marked bufferstop1 / bufferstop2 <kind> in the
scenery is a buffer stop (physics/bufferstop.h): rigid, buffered, hydraulic
or friction. With physics.collisions new a vehicle running into it meets the
stages of the stop in series: the buffers of both, the absorber or the brake
elements of a sliding stop, then the frame, whose hit goes through
collision::hit() and whose ride-up goes through collision::override_of(),
the stop an immovable body. It is held, the frame deforms, it rides up
(Enfield 2021), demolishes the stop (Kirkby 2021) or overruns a sliding one.
The log tells each hit once, and the memory cells __simulation.bufferstop
and <track>:bufferstop and their events tell the scenery.

physics.bufferstops marked (the default) takes the marked ends only, auto
also the ends with a model of a stop within 3 m, off none. Every other free
end keeps the derailment off the end of the track, and so does every end
with physics.collisions old; monitor logs what the stop would have done.
This commit is contained in:
jerrrrycho
2026-12-02 12:33:36 +01:00
parent bc944b7977
commit 7578f2c3a0
19 changed files with 1535 additions and 0 deletions
+4
View File
@@ -218,6 +218,8 @@ set(SOURCES
"application/driverhints.cpp"
"vehicle/dynamic/animations.cpp"
"vehicle/dynamic/consist.cpp"
"vehicle/dynamic/bufferstop.cpp"
"world/bufferstops.cpp"
"vehicle/dynamic/couplers.cpp"
"vehicle/dynamic/destinations.cpp"
"vehicle/dynamic/lifecycle.cpp"
@@ -827,6 +829,8 @@ set(CORE_SOURCES
"physics/consistbraking.cpp"
"physics/derailment.cpp"
"physics/collision.cpp"
"physics/bufferstop.cpp"
"physics/components/bufferstops.cpp"
"vehicle/derailmotion.cpp"
"world/TrackCheck.cpp"
"world/SleeperPack.cpp"
+16
View File
@@ -126,6 +126,20 @@ existing data.
(Szczekociny on td.scn: 6 of 13, all 13 did); a train hitting at 50-60 km/h crushes deeper; a rear-end hit at
100 km/h on two EN57 crushes the two ends that meet and leaves the units coupled behind them.
New optional `.fiz` key `BuffCoupl: FcrushMax` (kN), the most the crushed end packs down to. Needs: nothing.
- **Buffer stops at the free ends of the tracks** (`physics.bufferstops`, feat/buffer-stops, with `physics.collisions
new`). A track end marked `bufferstop1 <kind>` or `bufferstop2 <kind>` in the scenery is a stop of that kind:
`rigid` (rails bent up or concrete with a beam, BN-79), `buffered`, `hydraulic` or `friction` (sliding on brake
elements over a run-out). A vehicle running into it is held by its buffers and the stop up to a few km/h; harder,
the frame of the stop deforms, and a rigid stop is ridden up from about 9-12 km/h (Enfield 2021) and demolished past
that (Kirkby 2021), the vehicle going on off the end; a sliding stop slides up to its run-out, then is overrun; a
hydraulic one takes 336 kJ over 0.6 m and recovers. The log tells each hit (`bufferstop: ...`); a scenery that
declares the memory cell `__simulation.bufferstop` or `<track>:bufferstop` gets the vehicle, the outcome, the track,
the speed and the code of the outcome in it, and its events of those names run. With `physics.bufferstops auto` a
free end with a model of a stop (`koziol*`, `*oporow*`, `prellbock*`, `bufferstop*`) standing within 3 m of it is a
stop too, unless the track says `bufferstopN none`. The default is `marked`: only the ends the scenery marks; `off`
turns the stops off. Any other free end keeps the derailment off the end of the track, and so does every end with
`physics.collisions old`; `monitor` keeps it too and logs what the stop would have done. Notices: none until a
scenery marks its ends or `auto` is set. Needs: the attribute in the sceneries (SVN), or `auto`.
- **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise.
- **A vehicle off the track (`physics.derailment new`) slides less far and no longer falls through the ground**
(GH#556, #560). The friction on the ground goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: an
@@ -171,4 +185,6 @@ All optional; without the key everything is as before. The data files are in the
| `.fiz` security system `AwareOffInShuntMode=Yes` | The SM42's vigilance device (CA) is off in the shunt mode. | SM42/SP42 files. | #275 |
| `.mmd` `animdoor` per door wing | Door wings of different kinds on one side. | Vehicles with mixed doors. | #397 |
| `.mmd` `i-compartmentlights`, `radioon_sw:` etc. | New lamps and radio fuse switches. | Cabs that have them. | #352, #280 |
| scenery `track`: `bufferstop1` / `bufferstop2 <kind>[;<a>[;<b>[;<setback>]]]` | A buffer stop at the free end 1 or 2 of the track, see Physics and scenery; `none` keeps the models of `physics.bufferstops auto` off the end. | The tracks of the stubs ending in a stop. | feat/buffer-stops |
| eu07.ini `physics.bufferstops auto\|marked\|off` | Whether the models of the stops at the free ends make them stops too (`auto`), only the marked ends are (`marked`, the default), or none (`off`). | Optional. | feat/buffer-stops |
| eu07.ini `sound.*` | The OpenAL Soft options, each defaulting to what the simulator did before. | Optional. | #404 |
+636
View File
@@ -0,0 +1,636 @@
/*
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 "physics/bufferstop.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <charconv>
#include <cmath>
namespace bufferstop {
namespace {
// the step is integrated in slices of this length at most, and in no more than so many of them, as collision::hit() does [s]
constexpr double slice{0.0005};
constexpr double slices_max{200.0};
// the transition between the loading and the unloading curve of the buffers, to their secant stiffness, as the
// buffers of a pair of vehicles have it (couplerphysics.cpp)
constexpr double transition_factor{3.0};
// a brake element of a sliding stop holds less the longer it slides: Rawie 10 EB, 40 kJ/m over 0-5 m, 36 over 5-8 m,
// 32 over 8-12 m, 28 past that
constexpr std::array<std::pair<double, double>, 4> element_force{{{5.0, 40.0e3}, {8.0, 36.0e3}, {12.0, 32.0e3}, {std::numeric_limits<double>::infinity(), 28.0e3}}};
// the frames past the stages: a rigid stop of rails or concrete gives at 1.5 MN, then at 1.0 MN as it bends (Kowalczyk:
// 225 kJ of the FEM case deform it by about 0.2 m), wrecked past 0.6 m (Kirkby); the concrete base of a hydraulic or a
// sliding stop is stronger than the end of a coach or a wagon (3 MN at its peak, 2 MN past it, collision::default_crush()),
// the end crushes first
collision::crush_curve rigid_frame() {
return {1.5e6, 1.0e6, 0.05, 1.0, 0.0, std::numeric_limits<double>::infinity(), 1.5};
}
collision::crush_curve base_frame() {
return {3.5e6, 2.5e6, 0.05, 1.0, 0.0, std::numeric_limits<double>::infinity(), 1.5};
}
std::string_view trimmed(std::string_view Text) {
while (false == Text.empty() && std::isspace(static_cast<unsigned char>(Text.front()))) {
Text.remove_prefix(1);
}
while (false == Text.empty() && std::isspace(static_cast<unsigned char>(Text.back()))) {
Text.remove_suffix(1);
}
return Text;
}
// a field of the attribute: empty, a number, or not one (nullopt within the optional)
std::optional<std::optional<double>> number(std::string_view Text) {
Text = trimmed(Text);
if (Text.empty()) {
return std::optional<double>{};
}
auto value{0.0};
auto const [end, error]{std::from_chars(Text.data(), Text.data() + Text.size(), value)};
if (error != std::errc{} || end != Text.data() + Text.size() || false == std::isfinite(value)) {
return std::nullopt;
}
return std::optional<double>{value};
}
std::vector<std::string_view> fields(std::string_view Text, char const Separator) {
std::vector<std::string_view> result;
while (true) {
auto const split{Text.find(Separator)};
result.emplace_back(Text.substr(0, split));
if (split == std::string_view::npos) {
return result;
}
Text.remove_prefix(split + 1);
}
}
std::string lowercase(std::string_view Text) {
std::string result{Text};
std::transform(result.begin(), result.end(), result.begin(), [](unsigned char const Character) { return static_cast<char>(std::tolower(Character)); });
return result;
}
// the force of the stage between the buffers and the frame: the absorber over its stroke, the brake elements over the
// run-out; none past them
double stage_force(definition const &Stop, state const &State) {
switch (Stop.type) {
case kind::hydraulic:
return State.absorber < Stop.absorber_stroke ? Stop.absorber_force : std::numeric_limits<double>::infinity();
case kind::friction:
return State.slid < Stop.runout ? friction_force(Stop, State.slid) : std::numeric_limits<double>::infinity();
default:
return std::numeric_limits<double>::infinity();
}
}
double series_stiffness(double const First, double const Second) {
if (false == std::isfinite(Second)) {
return First;
}
if (false == std::isfinite(First)) {
return Second;
}
return First * Second / (First + Second);
}
} // namespace
std::string_view kind_name(kind const Kind) {
switch (Kind) {
case kind::none:
return "none";
case kind::buffered:
return "buffered";
case kind::hydraulic:
return "hydraulic";
case kind::friction:
return "friction";
case kind::rigid:
default:
return "rigid";
}
}
std::optional<kind> kind_of(std::string_view const Name) {
for (auto const candidate : {kind::none, kind::rigid, kind::buffered, kind::hydraulic, kind::friction}) {
if (Name == kind_name(candidate)) {
return candidate;
}
}
return std::nullopt;
}
definition preset(kind const Kind) {
definition stop;
stop.type = Kind;
switch (Kind) {
case kind::none:
break;
case kind::rigid:
// the beam of a stop of BN-79 is 960 mm above the rail (Kowalczyk). its structure gives elastically: with 17.5 MN/m
// in series with the steel of the vehicle some 15 % of the energy of the FEM case springs back, as there
stop.frame = rigid_frame();
stop.stiffness = 17.5e6;
break;
case kind::buffered:
// two buffers of EN 15551 category A, 2 x 30 kJ over 105 mm
stop.height = 1.04;
stop.buffer_energy = 60.0e3;
stop.buffer_stroke = 0.105;
stop.frame = rigid_frame();
stop.stiffness = 17.5e6;
break;
case kind::hydraulic:
// Oleo: 336 kJ over 0.6 m, so a steady 560 kN
stop.height = 1.04;
stop.absorber_force = 336.0e3 / 0.6;
stop.absorber_stroke = 0.6;
stop.frame = base_frame();
stop.demolish = 0.4;
break;
case kind::friction:
// Rawie 10 EB: 6 elements, 8 m of braking distance; the body some 3 t. the track ends where the run-out does, its
// face stands that far before the rail end
stop.height = 1.04;
stop.elements = 6;
stop.runout = 8.0;
stop.setback = stop.runout;
stop.body_mass = 3000.0;
stop.frame = base_frame();
stop.demolish = 0.4;
break;
}
return stop;
}
std::optional<definition> read_attribute(std::string_view const Value) {
auto const parts{fields(trimmed(Value), ';')};
if (parts.size() > 4) {
return std::nullopt;
}
auto const type{kind_of(lowercase(trimmed(parts[0])))};
if (false == type.has_value()) {
return std::nullopt;
}
auto stop{preset(*type)};
if (*type == kind::none) {
return stop;
}
std::array<std::optional<double>, 3> values;
for (std::size_t index = 1; index < parts.size(); ++index) {
auto const field{number(parts[index])};
if (false == field.has_value()) {
return std::nullopt;
}
values[index - 1] = *field;
}
auto const &[first, second, setback]{values};
// the energy, the stroke, the elements and the run-out are more than nothing
if ((first && *first <= 0.0) || (second && *second <= 0.0)) {
return std::nullopt;
}
switch (*type) {
case kind::buffered:
if (first) {
stop.buffer_energy = *first * 1000.0;
}
break;
case kind::hydraulic: {
auto const energy{first.value_or(stop.absorber_force * stop.absorber_stroke / 1000.0) * 1000.0};
stop.absorber_stroke = second.value_or(stop.absorber_stroke);
stop.absorber_force = energy / stop.absorber_stroke;
break;
}
case kind::friction:
if (first) {
stop.elements = std::max(1, static_cast<int>(std::lround(*first)));
}
stop.runout = second.value_or(stop.runout);
stop.setback = stop.runout;
break;
default:
break;
}
if (setback) {
stop.setback = *setback;
if (*type == kind::friction) {
// the track ends where the run-out does: a face nearer the end leaves less of it
stop.runout = std::min(stop.runout, std::max(*setback, 0.0));
}
}
return stop;
}
coupler_physics::spring_curve buffers_of(definition const &Stop) {
if (Stop.buffer_energy <= 0.0 || Stop.buffer_stroke <= 0.0) {
return {1.0, 0.0, 0.0};
}
// linear, as collision::buffer_curve() of no progression: the energy is half the end force over the stroke
auto const endforce{2.0 * Stop.buffer_energy / Stop.buffer_stroke};
return {endforce / Stop.buffer_stroke, Stop.buffer_stroke, 0.0};
}
double friction_force(definition const &Stop, double const Slid) {
auto const slid{std::max(Slid, 0.0)};
for (auto const &[upto, force] : element_force) {
if (slid < upto) {
return Stop.elements * force;
}
}
return Stop.elements * element_force.back().second;
}
std::string_view outcome_name(outcome const Outcome) {
switch (Outcome) {
case outcome::held:
return "held";
case outcome::damaged:
return "damaged";
case outcome::rode_up:
return "rode_up";
case outcome::demolished:
return "demolished";
case outcome::overrun:
return "overrun";
case outcome::none:
default:
return "none";
}
}
outcome worse(outcome const First, outcome const Second) {
return static_cast<std::uint8_t>(First) >= static_cast<std::uint8_t>(Second) ? First : Second;
}
collision::hit_result frame_hit(definition const &Stop, state const &Stop_state, contact_input const &Input, double const Velocity, double const Springs, double const Dt, double const Budget) {
collision::hit_input input;
input.velocity = Velocity;
input.mass1 = Input.mass;
input.mass2 = immovable;
input.restitution = Stop.restitution;
input.stiffness = series_stiffness(Input.stiffness, Stop.stiffness);
input.springs = Springs;
input.dt = Dt;
input.start_velocity = Velocity;
input.budget = Budget;
return collision::hit(Input.vehicle_end, {Stop.frame, Stop_state.crush}, input);
}
contact_result after_override(definition const &Stop, state &Stop_state, double const Mass, double const Closing) {
contact_result result;
result.climbed = true;
result.touched = true;
Stop_state.climbed = true;
auto const velocity{std::max(Closing, 0.0)};
auto const brings{0.5 * Mass * velocity * velocity};
auto const frame{Stop.frame.energy(Stop_state.crush, Stop.demolish)};
auto const holds{frame + 0.5 * Mass * collision::gravity * ride_up_lift};
if (brings <= holds) {
// it comes to rest on the stop, which stands, damaged
result.residual = 0.0;
result.result = outcome::rode_up;
}
else {
// it wrecks the stop and goes on with the rest
result.residual = std::sqrt(std::max(0.0, velocity * velocity - 2.0 * holds / std::max(Mass, 1.0)));
result.work = frame;
Stop_state.crush = std::max(Stop_state.crush, Stop.demolish);
Stop_state.demolished = true;
result.result = outcome::demolished;
}
result.velocity = result.residual;
result.impulse = Mass * (velocity - result.residual);
return result;
}
contact_result contact(definition const &Stop, state &Stop_state, contact_input const &Input) {
contact_result result;
result.velocity = Input.closing;
if (Stop.type == kind::none || Stop_state.spent() || Input.mass <= 0.0 || Input.dt <= 0.0) {
result.travel = Input.closing * std::max(Input.dt, 0.0);
return result;
}
auto &now{Stop_state};
auto const stopbuffers{buffers_of(Stop)};
auto const travel{std::max(Input.buffers.travel, 0.0) + stopbuffers.travel};
auto const top{std::max(Input.buffers.travel > 0.0 ? Input.buffers.end_force() : 0.0, stopbuffers.end_force())};
auto const transition{transition_factor * std::max(top, 1.0) / std::max(travel, 1e-3)};
// springing back the buffers give the square of the restitution of the force they took loading; with the transition
// between the curves a vehicle bounces off them at about 0.64 of its speed, 41 % of the energy back (EN 15551 has
// the buffers take in at least half of it)
auto const unloading{Stop.restitution * Stop.restitution};
auto const slices{std::clamp(std::ceil(Input.dt / slice), 1.0, slices_max)};
auto const length{Input.dt / slices};
// the override of the end onto the stop: the stop never interlocks with an anticlimber, nor does the anticlimber of
// the end hold a beam off its own height by more than the vertical offset of the design collision of EN 15227 (the
// Class 710 of Enfield, built to it, rode up the stop)
auto const engaged{Input.anticlimber && std::abs(Input.vehicle_height - Stop.height) < collision::override_height - 1e-9};
auto const climbs = [&](double const VehicleCrush) {
collision::override_input climbing;
climbing.crush1 = VehicleCrush;
climbing.crush2 = now.crush;
climbing.mass1 = Input.mass;
climbing.mass2 = immovable;
climbing.height1 = Input.vehicle_height;
climbing.height2 = Stop.height;
climbing.anticlimber1 = engaged;
climbing.zone1 = Input.zone;
climbing.zone2 = Stop.demolish;
return collision::override_of(climbing).first;
};
auto velocity{Input.closing};
auto penetration{Input.penetration};
auto vehiclecrush{Input.vehicle_end.crush};
auto time{0.0};
auto final{outcome::none};
while (Input.dt - time > 1e-12) {
auto const step{std::min(length, Input.dt - time)};
auto deflection{penetration - (now.absorber + now.slid + now.crush + vehiclecrush)};
if (deflection <= 0.0 && now.absorber > 0.0) {
// the absorber springs back after the vehicle, pressing on nothing
now.absorber = std::max(0.0, now.absorber + deflection);
deflection = 0.0;
}
if (deflection <= 0.0) {
// apart: the buffers unloaded, the body of a sliding stop at rest
now.elastic.reset();
now.absorbed = 0.0;
now.sliding = false;
penetration += velocity * step;
result.travel += velocity * step;
time += step;
continue;
}
result.touched = true;
result.duration += step;
auto const loading{velocity > 0.0};
auto const split{coupler_physics::series(Input.buffers, stopbuffers, deflection)};
auto force{now.elastic.update(deflection, split.force, unloading * split.force, transition)};
auto const stage{stage_force(Stop, now)};
auto const stopforce{Stop.frame.force(now.crush)};
auto const endforce{Input.vehicle_end.curve.force(vehiclecrush)};
auto const frameforce{std::min(stopforce, endforce)};
auto const yield{std::min(stage, frameforce)};
auto mass{Input.mass};
auto crushed{false};
auto yielded{false};
if (loading && force > yield) {
// the weaker stage gives at its force, the buffers stay pressed as far as that force has them
yielded = true;
auto const held{std::min(Input.buffers.deflection(yield) + stopbuffers.deflection(yield), travel)};
auto const excess{std::max(deflection - held, 0.0)};
if (stage <= frameforce) {
if (Stop.type == kind::hydraulic) {
now.absorber = std::min(now.absorber + excess, Stop.absorber_stroke);
}
else {
if (false == now.sliding) {
// the body of the stop takes its share of the momentum as it starts off
velocity *= Input.mass / (Input.mass + Stop.body_mass);
now.sliding = true;
}
now.slid = std::min(now.slid + excess, Stop.runout);
mass += Stop.body_mass;
if (now.slid >= Stop.runout - 1e-9) {
// slid off the end of its run-out: it goes on with the vehicle, holding nothing
now.overrun = true;
final = outcome::overrun;
}
}
}
else {
// the frame of the stop or the end of the vehicle crushes, the weaker one, both alike when they're alike
if (std::abs(stopforce - endforce) <= 1e-9 * yield) {
now.crush += 0.5 * excess;
vehiclecrush += 0.5 * excess;
}
else if (stopforce < endforce) {
now.crush += excess;
}
else {
vehiclecrush += excess;
}
result.work += yield * excess;
crushed = true;
}
force = yield;
now.elastic.force = yield;
now.elastic.deflection = held;
}
else if (loading && deflection >= travel - 1e-9) {
// the buffers solid, the hit goes onto the steel and the frames: the crush takes only what the hit brings past
// what the buffers of EN 15551 of the end take in
auto const budget{std::min(Input.budget, 0.5 * Input.mass * velocity * velocity - std::max(0.0, Input.vehicle_capacity - now.absorbed))};
auto input{Input};
input.vehicle_end.crush = vehiclecrush;
auto const hit{frame_hit(Stop, now, input, velocity, force, Input.dt - time, budget)};
if (hit.crushing) {
vehiclecrush += hit.crush1;
now.crush += hit.crush2;
result.work += hit.work;
result.force = std::max(result.force, hit.force);
result.travel += hit.crush1 + hit.crush2;
result.duration = std::min(Input.dt, result.duration + hit.duration);
velocity = hit.velocity;
time = Input.dt;
if (climbs(vehiclecrush)) {
auto const climbed{after_override(Stop, now, Input.mass, velocity)};
result.climbed = true;
result.work += climbed.work;
velocity = climbed.velocity;
final = climbed.result;
}
else if (now.crush >= Stop.demolish) {
now.demolished = true;
final = outcome::demolished;
}
break;
}
// the steel takes it, the vehicle bounces off
velocity = -Stop.restitution * velocity;
}
result.force = std::max(result.force, force);
if (false == yielded) {
if (loading && velocity > 0.0) {
now.absorbed += force * velocity * step;
}
else {
now.absorbed = std::min(now.absorbed, 0.5 * force * deflection);
}
}
velocity -= force * step / mass;
penetration += velocity * step;
result.travel += velocity * step;
time += step;
if (crushed) {
if (climbs(vehiclecrush)) {
auto const climbed{after_override(Stop, now, Input.mass, velocity)};
result.climbed = true;
result.work += climbed.work;
velocity = climbed.velocity;
final = climbed.result;
break;
}
if (now.crush >= Stop.demolish) {
now.demolished = true;
final = outcome::demolished;
break;
}
}
if (now.overrun) {
break;
}
}
result.velocity = velocity;
result.residual = now.spent() || result.climbed ? std::max(velocity, 0.0) : 0.0;
result.impulse = Input.mass * (Input.closing - velocity);
result.vehicle_crush = vehiclecrush - Input.vehicle_end.crush;
now.peak_force = std::max(now.peak_force, result.force);
if (final != outcome::none) {
result.result = final;
}
else if (result.touched) {
result.result = now.crush >= collision::crush_mark ? outcome::damaged : outcome::held;
}
return result;
}
std::string cell_text(notice const &Notice) {
return Notice.vehicle + " " + std::string{outcome_name(Notice.result)} + " " + (Notice.track.empty() ? std::string{"none"} : Notice.track);
}
std::string cell_name(std::string_view const Track) {
return std::string{Track} + ":bufferstop";
}
std::vector<model_rule> default_rules() {
return read_rules("!*kozlak* // wiatrak_kozlak: a windmill\n"
"koziol_lublin buffered 0.0 // the buffers of a vehicle on its beam\n"
"koziol_chylonia buffered 0.0\n"
"koziol* rigid 0.0\n"
"*oporow* rigid 0.0\n"
"prellbock* rigid 0.0\n"
"bufferstop* rigid 0.0\n");
}
std::vector<model_rule> read_rules(std::string_view Text) {
std::vector<model_rule> rules;
for (auto line : fields(Text, '\n')) {
if (auto const comment{line.find("//")}; comment != std::string_view::npos) {
line = line.substr(0, comment);
}
std::vector<std::string_view> words;
for (auto const word : fields(trimmed(line), ' ')) {
if (false == trimmed(word).empty()) {
words.emplace_back(trimmed(word));
}
}
if (words.empty()) {
continue;
}
model_rule rule;
if (words[0].front() == '!') {
rule.excluded = true;
rule.pattern = lowercase(words[0].substr(1));
rules.emplace_back(rule);
continue;
}
auto const type{words.size() > 1 ? kind_of(lowercase(words[1])) : std::optional<kind>{kind::rigid}};
auto const face{words.size() > 2 ? number(words[2]) : std::optional<std::optional<double>>{std::optional<double>{0.0}}};
if (false == type.has_value() || *type == kind::none || false == face.has_value()) {
continue;
}
rule.pattern = lowercase(words[0]);
rule.type = *type;
rule.face = face->value_or(0.0);
rules.emplace_back(rule);
}
return rules;
}
bool wildcard(std::string_view const Pattern, std::string_view const Text) {
// the usual greedy match with backtracking to the last star
std::size_t pattern{0};
std::size_t text{0};
auto star{std::string_view::npos};
std::size_t resume{0};
while (text < Text.size()) {
if (pattern < Pattern.size() && Pattern[pattern] == '*') {
star = pattern++;
resume = text;
}
else if (pattern < Pattern.size() && Pattern[pattern] == Text[text]) {
++pattern;
++text;
}
else if (star != std::string_view::npos) {
pattern = star + 1;
text = ++resume;
}
else {
return false;
}
}
while (pattern < Pattern.size() && Pattern[pattern] == '*') {
++pattern;
}
return pattern == Pattern.size();
}
std::optional<model_rule> match(std::string_view const ModelFile, std::vector<model_rule> const &Rules) {
// the name of the file alone, without its folders and its extension
auto name{ModelFile};
if (auto const folder{name.find_last_of("/\\")}; folder != std::string_view::npos) {
name.remove_prefix(folder + 1);
}
if (auto const extension{name.rfind('.')}; extension != std::string_view::npos) {
name = name.substr(0, extension);
}
auto const file{lowercase(name)};
if (file.empty()) {
return std::nullopt;
}
for (auto const &rule : Rules) {
if (rule.excluded && wildcard(rule.pattern, file)) {
return std::nullopt;
}
}
for (auto const &rule : Rules) {
if (false == rule.excluded && wildcard(rule.pattern, file)) {
return rule;
}
}
return std::nullopt;
}
placement place(double const EndX, double const EndZ, double const OutwardX, double const OutwardZ, double const ModelX, double const ModelZ) {
auto const dx{ModelX - EndX};
auto const dz{ModelZ - EndZ};
return {std::hypot(dx, dz), dx * OutwardX + dz * OutwardZ};
}
bool at_end(placement const &Placement) {
return Placement.distance <= model_reach && std::abs(Placement.along) <= model_reach;
}
double model_setback(placement const &Placement, model_rule const &Rule) {
// the face lies the offset of the rule from the origin towards the track
return std::clamp(Rule.face - Placement.along, -model_setback_limit, model_setback_limit);
}
} // namespace bufferstop
+224
View File
@@ -0,0 +1,224 @@
/*
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 <cstdint>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "physics/collision.h"
#include "physics/couplerphysics.h"
// buffer stops (kozioł oporowy, Prellbock) at the free ends of rail tracks (physics.bufferstops in eu07.ini), as plain
// functions of the stop and the vehicle meeting it. a track end is a stop by the attribute bufferstop1 / bufferstop2 of
// its track, or with physics.bufferstops auto by a model of a stop placed at it; any other free end keeps the legacy
// derailment off the end of the track.
//
// a stop is three stages in series, met in this order, each optional:
// - elastic: the spring buffers of the stop (a buffered stop), in series with the buffers of the vehicle;
// - dissipative: a hydraulic absorber (a steady force over its stroke, recovering when unloaded) or the brake elements
// of a sliding stop (a steady force over the run-out, staying displaced);
// - the frame: a crush curve as the ends of the vehicles have (collision.h), demolished past a depth; the hit on it goes
// through collision::hit() and the ride-up through collision::override_of(), the stop an immovable body.
// sources:
// - Ie-1 (PLK, 2025) par. 10 ust. 7: a track ending in a buffer stop shows Z 1 "Stoj" on the stop or ahead of it;
// Ir-1 par. 38 ust. 9-10: a train is let onto such a track only exceptionally, at 20 km/h at most;
// - BN-79/9310-06 "Kozly oporowe" (1979): fixed, sliding, destroyed and vehicle-destroying stops; PLK ST-T1-A8 (2021):
// the stop takes W >= k * 1/2 m v^2, v 10 or 15 km/h, k 1.2 to 2.0 (both after Kowalczyk D., "Urzadzenia
// zakonczenia torow kolejowych", Problemy Kolejnictwa 202, 2024);
// - Kowalczyk, FEM of a rail stop of BN-79 (49E1, its beam 960 mm above the rail): 50 t at 3 m/s deform it by about
// 0.18 m, some 85 % of the energy going into the deformation;
// - RAIB 13/2022, Enfield Town 2021: a unit of some 140 t at 12 km/h rode up a fixed stop, its leading wheels 800 mm
// above the rails; RAIB 07/2022, Kirkby 2021: 47 km/h demolished the stop;
// - Rawie, friction stop 10 EB, the calculation of 21.11.2024: 40 kN for each brake element over the first 5 m of the
// slide, 36 / 32 / 28 kN past 5 / 8 / 12 m (Ril 800.0113A02, safety factor 1.5);
// - Oleo, the fixed hydraulic stop: 336 kJ over a recoverable stroke of 600 mm.
namespace bufferstop {
enum class kind : std::uint8_t {
none, // no stop: the end opts out of the automatic rule
rigid, // rails bent up or concrete with a beam (BN-79), most of the Polish stops
buffered, // rigid, with the spring buffers of EN 15551 on its beam
hydraulic, // a hydraulic absorber over a recoverable stroke
friction // sliding on brake elements clamped to the rails over a run-out ("samohamowny")
};
// the name of the kind in the attribute and the log, e.g. "rigid"
std::string_view kind_name(kind Kind);
std::optional<kind> kind_of(std::string_view Name);
// what a stop is
struct definition {
kind type{kind::rigid};
double setback{0.0}; // how far its face stands before the rail end, negative past it [m]
double height{0.96}; // of its beam or buffers above the rail [m]
double buffer_energy{0.0}; // the energy its spring buffers take in over their stroke, both [J]; 0 none
double buffer_stroke{0.0}; // [m]
double absorber_force{0.0}; // hydraulic [N]
double absorber_stroke{0.0}; // [m]
int elements{0}; // friction: the brake elements
double runout{0.0}; // friction: how far it may slide [m]
double body_mass{0.0}; // friction: the body that slides with the vehicle [kg]
collision::crush_curve frame; // past the stages above
double demolish{0.6}; // the crush of the frame past which it's wrecked [m]
double stiffness{std::numeric_limits<double>::infinity()}; // of its structure in series with the steel of the vehicle [N/m]
double restitution{0.4}; // of the rebound of the vehicle off it
};
// the stop of the kind with the numbers of the sources above
definition preset(kind Kind);
// the value of the attribute bufferstop1 / bufferstop2 of a track: <kind>[;<a>[;<b>[;<setback>]]], with a and b
// buffered: the energy of its buffers [kJ]; hydraulic: the energy [kJ] and the stroke [m]; friction: the elements and
// the run-out [m]. what's left out (or empty) comes from the preset, the setback of a friction stop is its run-out. none
// for a value that isn't one: an unknown kind, a value that isn't a number, a negative one where it can't be
std::optional<definition> read_attribute(std::string_view Value);
// the spring buffers of the stop, both side by side; a travel of 0 for none
coupler_physics::spring_curve buffers_of(definition const &Stop);
// the force the brake elements of a sliding stop hold it with, having slid the distance [m]: each element 40 kN, falling
// to 36 / 32 / 28 kN past 5 / 8 / 12 m [N]
double friction_force(definition const &Stop, double Slid);
// what the stop went through, kept with the track end: until the scenery loads again
struct state {
double absorber{0.0}; // the stroke of the absorber in use now [m], it recovers unloaded
double slid{0.0}; // [m]
double crush{0.0}; // of the frame [m]
bool demolished{false};
bool overrun{false};
bool climbed{false}; // a vehicle rode up onto it
double peak_force{0.0}; // the most it took [N], for the log
// the contact under way: the energy the buffers took in pressed, and their friction
double absorbed{0.0};
coupler_physics::hysteresis elastic;
bool sliding{false}; // the body of a sliding stop moves with the vehicle
// the stop gives nothing any more: past it the end is a free one
bool spent() const { return demolished || overrun; }
};
// how a hit came out. the codes are public: the memory cell __simulation.bufferstop holds them in its value 2
enum class outcome : std::uint8_t {
none = 0,
held = 1, // it stopped the vehicle, nothing crushed worth telling
damaged = 2, // its frame deformed past collision::crush_mark
rode_up = 3, // the vehicle climbed onto it and came to rest there
demolished = 4, // wrecked: the vehicle went on past it
overrun = 5 // a sliding stop slid to the end of its run-out: the vehicle went on past it
};
// the name of the outcome in the memory cell, e.g. "rode_up"
std::string_view outcome_name(outcome Outcome);
// the worse of the two, for a hit over many steps
outcome worse(outcome First, outcome Second);
// one end of one vehicle against the stop, in one step
struct contact_input {
double closing{0.0}; // the velocity of the vehicle towards the stop [m/s]
double penetration{0.0}; // its buffer face past the original face of the stop [m]; not more than 0: apart
double mass{0.0}; // of the vehicle [kg]; the train behind it acts on it through the couplers, as in crush_hit()
collision::end_state vehicle_end; // its crush curve and the crush it has
coupler_physics::spring_curve buffers; // the buffers of the end
double vehicle_capacity{0.0}; // collision::buffer_capacity() of the end; 0 for a central coupler
double vehicle_height{1.04}; // collision::buffer_height() of the end [m]
bool anticlimber{false}; // of the end
double zone{0.0}; // the crush zone of the end (its densify) for override_of() [m]
double stiffness{1.0e8}; // of the steel of the end [N/m]
double dt{0.01}; // [s]
// the energy the crush of the frame may take at most [J]; the buffers of EN 15551 of the end take in their capacity
// of the hit first either way
double budget{std::numeric_limits<double>::infinity()};
};
struct contact_result {
bool touched{false}; // the vehicle met the stop in the step
double impulse{0.0}; // pushing the vehicle back [N s]
double velocity{0.0}; // its velocity towards the stop after the step [m/s]
double travel{0.0}; // how far it moved towards the stop over the step [m]
double force{0.0}; // peak force [N]
double duration{0.0}; // how long it pressed on the stop over the step [s]
double vehicle_crush{0.0}; // added to the end of the vehicle [m]
double work{0.0}; // taken by the crush of the frames [J]
bool climbed{false}; // the vehicle rode up onto the stop
double residual{0.0}; // the velocity it keeps after riding up or through the stop [m/s]
outcome result{outcome::none};
};
// the step of the vehicle against the stop: the stages in series, integrated over the step in short slices as
// collision::hit() is, so the result doesn't depend on the step. the state of the stop changes with it
contact_result contact(definition const &Stop, state &Stop_state, contact_input const &Input);
// the vehicle rode up onto the stop: the energy it brings, against what the frame still takes before it's wrecked and
// the lift of its end over the stop (the 800 mm of Enfield). less: it comes to rest on the stop; more: the stop is
// demolished, and the vehicle goes on with what's left
contact_result after_override(definition const &Stop, state &Stop_state, double Mass, double Closing);
// the lift of the end of a vehicle riding up a stop: the leading wheels of Enfield came to rest 800 mm above the rails [m]
inline constexpr double ride_up_lift{0.8};
// the hit on the frame of the stop past its other stages, the buffers of the pair solid: collision::hit() of the end of
// the vehicle against the frame, the stop immovable. all that the stop takes of collision.h goes through here
collision::hit_result frame_hit(definition const &Stop, state const &Stop_state, contact_input const &Input, double Velocity, double Springs, double Dt, double Budget);
// the stop of no mass to move: as crush_hit() has a wall [kg]
inline constexpr double immovable{1e12};
// ---- what the scenery is told
// a vehicle hit a stop: the memory cells __simulation.bufferstop and <track>:bufferstop, and their events
struct notice {
std::string vehicle;
std::string track;
outcome result{outcome::none};
double velocity{0.0}; // [km/h] as it hit
};
// "<vehicle> <outcome> <track>"
std::string cell_text(notice const &Notice);
// "<track>:bufferstop"
std::string cell_name(std::string_view Track);
// ---- the automatic rule: a model of a stop at a free track end (physics.bufferstops auto)
// a pattern of the file name of a model (without the folders and the extension, lower case; * matches anything), what
// kind of stop it is, and where the face of the stop lies from the origin of the model towards the track [m]. an
// excluded pattern is never a stop, whatever comes after it
struct model_rule {
std::string pattern;
kind type{kind::rigid};
double face{0.0};
bool excluded{false};
};
// the models of the stops of the bundled data
std::vector<model_rule> default_rules();
// rules of a text, one to a line: <pattern> <kind> <face>, or !<pattern> for one excluded; // starts a comment
std::vector<model_rule> read_rules(std::string_view Text);
bool wildcard(std::string_view Pattern, std::string_view Text);
// the rule the model file is a stop by, none for a model that isn't one
std::optional<model_rule> match(std::string_view ModelFile, std::vector<model_rule> const &Rules);
// a model counts for a free end within this distance of it, across and along [m]
inline constexpr double model_reach{3.0};
// the setback a model gives is kept within this [m]
inline constexpr double model_setback_limit{1.0};
// where a model stands at a free track end, on the ground (x, z)
struct placement {
double distance{0.0}; // from the end [m]
double along{0.0}; // past the end along the track, negative inside it [m]
};
placement place(double EndX, double EndZ, double OutwardX, double OutwardZ, double ModelX, double ModelZ);
// whether a model there stands at the end
bool at_end(placement const &Placement);
// the setback of the stop a model gives there
double model_setback(placement const &Placement, model_rule const &Rule);
// ---- the stop at a track end
struct installation {
definition stop;
state now;
std::string track; // the name of the track
int end{1}; // 0 at its point 1, 1 at its point 2
std::string source; // what made it a stop: the attribute or the model
};
} // namespace bufferstop
+2
View File
@@ -311,6 +311,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap
for (auto const b : VehicleEnds)
if (Couplers[b].CheckCollision)
CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!!
buffer_stop_contact(dt);
check_pushed_off(dt, std::abs(dL));
} // liczone dL, predkosc i przyspieszenie
@@ -389,6 +390,7 @@ double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Sh
for (auto const b : VehicleEnds)
if (Couplers[b].CheckCollision)
CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!!
buffer_stop_contact(dt);
check_pushed_off(dt, std::abs(dL));
} // liczone dL, predkosc i przyspieszenie
+197
View File
@@ -0,0 +1,197 @@
/*
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/.
*/
// the ends of a vehicle against the buffer stops at the free ends of the tracks (physics.bufferstops), see
// physics/bufferstop.h
#include "stdafx.h"
#include "physics/vehicle.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include <algorithm>
#include <format>
#include <string>
namespace
{
// the vehicle went on, off the stop, by more than this: its next touch is another hit [m]
constexpr double apart_margin{0.1};
// physics.collisions monitor: the hit is followed for this long at most, in steps of this length [s]
constexpr double monitor_time{20.0};
constexpr double monitor_step{0.01};
std::string_view outcome_words(bufferstop::outcome const Outcome)
{
switch (Outcome)
{
case bufferstop::outcome::rode_up: return "rode up";
case bufferstop::outcome::none: return "held";
default: return bufferstop::outcome_name(Outcome);
}
}
// what the log tells of the stop after the hit
std::string stop_report(bufferstop::installation const &Stop, double const VehicleCrush)
{
return std::format("stop deformed {:.2f} m, peak {:.0f} kN, slid {:.2f} m, absorber {:.2f} m, end crushed {:.2f} m", Stop.now.crush, Stop.now.peak_force / 1000.0, Stop.now.slid, Stop.now.absorber,
VehicleCrush);
}
} // namespace
void physics::Vehicle::buffer_stop_contact(double const dt)
{
if (Global.buffer_stops == global_settings::bufferstop_mode::off || Global.collisions == global_settings::collision_model::old || false == TestFlag(CategoryFlag, 1))
{
return;
}
for (auto const end : VehicleEnds)
{
auto &contact{TrackEnds[end]};
if (contact.stop == nullptr || DamageFlag.HasAll(VehicleDamage::derailed))
{
continue;
}
auto &installation{*contact.stop};
// the gap now: the one found at the start of the frame, and the move of the vehicle since, as for the gap to a
// neighbour (coupler_gap_change())
auto const gap{contact.gap + (end == VehicleEnd::front ? -moveLength : moveLength)};
if (gap > apart_margin)
{
// off the stop: the next touch is another hit
contact.touching = false;
contact.reported = false;
contact.worst = bufferstop::outcome::none;
contact.vehicle_crush = 0.0;
}
if (gap >= 0.0 || installation.now.spent())
{
// apart, the stop as it stands: the absorber extended again, the buffers unloaded
if (false == installation.now.spent())
{
installation.now.absorber = 0.0;
installation.now.elastic.reset();
installation.now.absorbed = 0.0;
installation.now.sliding = false;
}
continue;
}
auto const direction{end == VehicleEnd::front ? 1.0 : -1.0};
auto const closing{direction * travelSpeed};
auto const &coupler{Couplers[end]};
auto const kind{collision_kind()};
auto const curve{crush_curve_at(end)};
bufferstop::contact_input input;
input.closing = closing;
input.penetration = -gap;
input.mass = totalMass;
input.vehicle_end = {curve, coupler.crush};
input.buffers = coupler.physics.buffers;
// an automatic coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs do
auto const central{coupler.type() == TCouplerType::Automatic || coupler.has_adapter()};
input.vehicle_capacity = central ? 0.0 : collision::buffer_capacity(coupler.collision, kind);
input.vehicle_height = buffer_height_at(end);
input.anticlimber = collision::anticlimber_of(coupler.collision, kind);
input.zone = curve.densify;
input.stiffness = std::max(coupler.physics.link_stiffness, 1.0);
input.dt = dt;
auto const describe = [&]() { return std::format("{} hit the buffer stop of {} ({})", Name, installation.track, bufferstop::kind_name(installation.stop.type)); };
if (Global.collisions == global_settings::collision_model::monitor)
{
// the legacy behaviour goes on, the vehicle runs off the end; the log tells what the whole hit would be
if (contact.reported || closing <= 0.0)
{
continue;
}
contact.reported = true;
auto state{installation.now};
auto would{bufferstop::outcome::none};
auto vehiclecrush{0.0};
input.dt = monitor_step;
for (auto time = 0.0; time < monitor_time; time += monitor_step)
{
auto const step{bufferstop::contact(installation.stop, state, input)};
would = bufferstop::worse(would, step.result);
vehiclecrush += step.vehicle_crush;
input.closing = step.velocity;
input.penetration += step.travel;
input.vehicle_end.crush += step.vehicle_crush;
if (state.spent() || step.climbed || (step.touched && step.velocity <= 0.0))
{
break;
}
}
auto copy{installation};
copy.now = state;
WriteLog(std::format("bufferstop monitor: {} at {:.0f} km/h: would {}, {}", describe(), closing * 3.6, outcome_words(would), stop_report(copy, vehiclecrush)));
continue;
}
auto const result{bufferstop::contact(installation.stop, installation.now, input)};
if (false == result.touched)
{
continue;
}
if (false == contact.touching)
{
// a new hit
contact.touching = true;
contact.reported = false;
contact.speed = closing * 3.6;
contact.worst = bufferstop::outcome::none;
contact.vehicle_crush = 0.0;
}
contact.worst = bufferstop::worse(contact.worst, result.result);
// the hit changes the velocity alone, as a collision of a pair does (CollisionDetect())
travelSpeed = direction * result.velocity;
if (result.vehicle_crush > 0.0)
{
// the end of the vehicle crushed for good, the body shorter by it off the track; crushed past the draw gear,
// its coupler is gone
auto &thiscoupler{Couplers[end]};
auto const before{thiscoupler.crush};
thiscoupler.crush += result.vehicle_crush;
contact.vehicle_crush += result.vehicle_crush;
if (before < collision::crush_mark && thiscoupler.crush >= collision::crush_mark)
{
ErrorLog(std::format("Bad driving: {} at {:.0f} km/h, the {} end of {} crushed by {:.2f} m", describe(), contact.speed, end == VehicleEnd::front ? "front" : "rear", Name, thiscoupler.crush));
}
OffTrack.crushed(Couplers[VehicleEnd::front].crush, Couplers[VehicleEnd::rear].crush);
if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken && thiscoupler.CouplingFlag == Coupling::none)
{
damage_coupler(end);
}
}
if (result.climbed)
{
// it rode up onto the stop: off the rails, with what the stop left it of its speed
derail_in_collision(COLLISION_OVERRIDE, std::format("{} at {:.0f} km/h and rode up onto it, its buffers at {:.0f} mm, the beam at {:.0f} mm; {}", describe(), contact.speed,
input.vehicle_height * 1000.0, installation.stop.height * 1000.0, stop_report(installation, contact.vehicle_crush)));
travelSpeed = direction * result.residual;
}
// the hit is over once the vehicle stopped or bounced off, or went on past the stop: the log and the scenery are
// told of it once
if (false == contact.reported && (result.velocity <= 0.0 || result.climbed || installation.now.spent()))
{
contact.reported = true;
auto const text{std::format("bufferstop: {} at {:.0f} km/h: {}, {}", describe(), contact.speed, outcome_words(contact.worst), stop_report(installation, contact.vehicle_crush))};
if (contact.worst == bufferstop::outcome::held)
{
WriteLog(text);
}
else
{
ErrorLog(text);
}
contact.pending = bufferstop::notice{Name, installation.track, contact.worst, contact.speed};
}
}
}
+23
View File
@@ -12,12 +12,14 @@ http://mozilla.org/MPL/2.0/.
// Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji
#include <array>
#include <map>
#include <memory>
#include <optional>
#include <unordered_map>
#include "physics/brakes.h"
#include "physics/couplerphysics.h"
#include "physics/derailment.h"
#include "physics/collision.h"
#include "physics/bufferstop.h"
#include "scripting/ladderlogic.h"
#include "vehicle/derailmotion.h"
#include "vehicle/odometerreading.h"
@@ -582,6 +584,22 @@ struct TCoupling
}
};
// physics.bufferstops: the buffer stop ahead of an end of the vehicle at a free end of its track, with nothing in
// between, found at the start of the frame (TDynamicObject::update_track_ends()); see physics/bufferstop.h
struct track_end_contact
{
std::shared_ptr<bufferstop::installation> stop; // owned by the end of the track, shared by every vehicle meeting it
double gap{10000.0}; // from the buffer face of the vehicle to the face of the stop along the track, at the start of the frame [m]
// the hit under way: its speed [km/h] at the first touch, the worst it came to, the crush of the end in it, and
// whether the log and the scenery were told of it (physics.collisions monitor: what it would be)
bool touching{false};
double speed{0.0};
bufferstop::outcome worst{bufferstop::outcome::none};
double vehicle_crush{0.0};
bool reported{false};
// for the scenery, told on the main thread at the start of the next frame
std::optional<bufferstop::notice> pending;
};
struct speed_control
{
@@ -861,6 +879,7 @@ class Vehicle
bool const &CouplerPhysics() const { return couplerPhysics; }
void SetCouplerPhysics(bool const Value) { couplerPhysics = Value; }
ByEnd<neighbour_data> Neighbours; // potential collision sources
ByEnd<track_end_contact> TrackEnds; // the buffer stops ahead of the ends, past the neighbours there
// something out of the ordinary happened (the line breaker knocked out, a derailment), for the sounds to follow up
bool EventFlag() const { return eventFlag; }
void RaiseEventFlag() { eventFlag = true; }
@@ -1224,6 +1243,10 @@ class Vehicle
// the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the
// Distance [m]: the flange climbs while the wheels roll on
void check_pushed_off(double dt, double Distance);
// physics.bufferstops with physics.collisions new: the ends of the vehicle meet the buffer stops ahead of them
// (TrackEnds), see physics/bufferstop.h. the velocity takes the hit; a ride-up derails the vehicle onto the stop.
// physics.collisions monitor: the log tells what the hit would be, once for a hit, nothing changes
void buffer_stop_contact(double dt);
// the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of
// derailment.h have it
void derail_in_collision(DerailReason Reason, std::string const &Why);
+21
View File
@@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulationenvironment.h"
#include "simulation/simulationtest.h"
#include "simulation/blackboxrecorder.h"
#include "physics/bufferstop.h"
#include "utilities/Globals.h"
#include "world/Event.h"
@@ -153,6 +154,26 @@ state_manager::report_derailment( TDynamicObject const &Vehicle, derailment::not
test().vehicle_derailed( Vehicle, Notice );
}
void
state_manager::report_buffer_stop( TDynamicObject const &Vehicle, bufferstop::notice const &Notice ) {
auto const text { bufferstop::cell_text( Notice ) };
auto const tell { [ & ]( std::string const &Name ) {
if( auto *cell { Memory.find( Name ) } ) {
cell->UpdateValues(
text,
Notice.velocity,
static_cast<double>( static_cast<int>( Notice.result ) ),
basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2 );
}
if( auto *launched { Events.FindEvent( Name ) } ) {
Events.AddToQuery( launched, &Vehicle );
}
} };
tell( std::string( bufferstop_name ) );
tell( bufferstop::cell_name( Notice.track ) );
}
// legacy method, calculates changes in simulation state over specified time
void
state_manager::update( double const Deltatime, int Iterationcount ) {
+12
View File
@@ -19,6 +19,10 @@ http://mozilla.org/MPL/2.0/.
#include "scripting/lua.h"
#endif
namespace bufferstop {
struct notice;
}
namespace simulation {
class state_manager {
@@ -82,6 +86,14 @@ public:
report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice );
// name of the memory cell and of the event of a derailment of any vehicle
static constexpr std::string_view derailment_name { "__simulation.derailment" };
// the vehicle hit a buffer stop (physics/bufferstop.h): the scenery's memory cells __simulation.bufferstop and
// <track>:bufferstop get the notice (bufferstop::cell_text(), value 1 the speed [km/h], value 2 the code of the
// outcome) at once, then its events of those names run, the vehicle their activator. as for a derailment, the
// scenery declares those it wants, nothing is made otherwise
void
report_buffer_stop( TDynamicObject const &Vehicle, bufferstop::notice const &Notice );
// name of the memory cell and of the event of a hit on any buffer stop
static constexpr std::string_view bufferstop_name { "__simulation.bufferstop" };
private:
// members
+2
View File
@@ -479,6 +479,8 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc
if( Global.track_check ) {
simulation::Paths.CheckTracks();
}
// the buffer stops at the free ends the joining left
simulation::Paths.InitBufferStops();
// the roads tie up their own lanes where they gain or lose some, the junctions tie the lanes of the roads together,
// what's left loose after that gets closed by the roads
simulation::Roads.InitLanes();
+11
View File
@@ -1102,6 +1102,16 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
return true;
}
if (token == "physics.bufferstops")
{
// marked: the track ends the scenery marks as buffer stops, auto: those and the ends with a model of a stop,
// off: none (physics/bufferstop.h)
std::string mode;
ParseOne(Parser, mode, 1);
buffer_stops = bufferstop_mode_of(mode);
return true;
}
if (token == "controlcoupling.enginecheck")
{
ParseOne(Parser, control_coupling_engine_check, 1);
@@ -2602,6 +2612,7 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "physics.derailment.trustlimits", derailment_trust_limits );
export_as_text( Output, "physics.trackcheck", track_check );
export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } );
export_as_text( Output, "physics.bufferstops", std::string{ name_of( buffer_stops ) } );
export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 );
export_as_text( Output, "scalespeculars", ScaleSpecularValues );
export_as_text( Output, "gfxrenderer", GfxRenderer );
+21
View File
@@ -394,6 +394,13 @@ struct global_settings {
// (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any
enum class collision_model { old, physical, monitor };
collision_model collisions = collision_model::physical;
// the buffer stops at the free ends of rail tracks (physics.bufferstops in eu07.ini, physics/bufferstop.h), with
// physics.collisions new: marked, the ends the scenery marks with the attribute bufferstop1 / bufferstop2 of the
// track; auto, those and the ends with a model of a stop placed at them; off, none. any other end keeps the
// derailment off the end of the track. marked is the default until the table of the models of the stops is
// checked against the models
enum class bufferstop_mode { off, marked, automatic };
bufferstop_mode buffer_stops = bufferstop_mode::marked;
// physics.trackcheck: the geometry of the rail tracks the criteria of derailment find suspicious, to the log once the
// scenery loaded (trackcheck:, see world/TrackCheck.h)
bool track_check = false;
@@ -867,6 +874,20 @@ inline std::string_view name_of( global_settings::collision_model const Model )
default: { return "new"; }
}
}
// the modes of physics.bufferstops by their names in eu07.ini: auto, off (or no), marked (the default, also for a name it
// doesn't know)
inline global_settings::bufferstop_mode bufferstop_mode_of( std::string_view const Name ) {
if( Name == "auto" ) { return global_settings::bufferstop_mode::automatic; }
if( Name == "off" || Name == "no" ) { return global_settings::bufferstop_mode::off; }
return global_settings::bufferstop_mode::marked;
}
inline std::string_view name_of( global_settings::bufferstop_mode const Mode ) {
switch( Mode ) {
case global_settings::bufferstop_mode::automatic: { return "auto"; }
case global_settings::bufferstop_mode::off: { return "off"; }
default: { return "marked"; }
}
}
// the models of physics.derailment by their names in eu07.ini: new, old, off or no, monitor (the default, also for a
// name it doesn't know)
inline global_settings::derailment_model derailment_model_of(std::string_view const Name) {
+3
View File
@@ -1035,6 +1035,9 @@ public:
TDynamicObject * Neighbour(int &dir);
// updates potential collision sources
void update_neighbours();
// physics.bufferstops: finds the buffer stops ahead of the ends of the vehicle, past the neighbours there, and tells
// the scenery of a hit of the frame before (vehicle/dynamic/bufferstop.cpp)
void update_track_ends();
// physics.derailment new: the vehicle and the other one, one of them off the track, are in line, close enough
// across to run into each other
bool in_line_with( TDynamicObject const &Other ) const;
+120
View File
@@ -0,0 +1,120 @@
/*
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/.
*/
// the buffer stops ahead of the ends of the vehicle (physics.bufferstops, physics/bufferstop.h)
#include "stdafx.h"
#include "vehicle/DynObj.h"
#include "physics/vehicle.h"
#include "physics/bufferstop.h"
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "world/Track.h"
#include "world/bufferstops.h"
#include <algorithm>
#include <cmath>
#include <memory>
namespace {
struct found_stop {
TTrack const *track{nullptr};
int end{0};
std::shared_ptr<bufferstop::installation> stop;
};
} // namespace
void TDynamicObject::update_track_ends() {
for (auto const end : VehicleEnds) {
auto &contact{physics->TrackEnds[end]};
// the scenery is told of the hit of the frame before, on the main thread
if (contact.pending) {
simulation::State.report_buffer_stop(*this, *contact.pending);
contact.pending.reset();
}
}
auto const active{simulation::Paths.buffer_stops() > 0 && Global.buffer_stops != global_settings::bufferstop_mode::off &&
Global.collisions != global_settings::collision_model::old && TestFlag(physics->CategoryFlag, 1) &&
false == physics->DamageFlag.HasAll(VehicleDamage::derailed) && RaTrackGet() != nullptr};
for (auto const end : VehicleEnds) {
auto &contact{physics->TrackEnds[end]};
auto const previous{contact.stop};
contact.stop = nullptr;
contact.gap = 10000.0;
auto const &coupler{physics->Couplers[end]};
if (false == active || coupler.Connected != nullptr) {
// coupled, the vehicle there stands between this end and any stop
continue;
}
// the route of the end along the tracks from the active axle, as find_vehicle() takes it, up to the free end with a
// stop. the range of the scan of the neighbours
auto const range{std::max(10.0, std::abs(physics->V())) + 40.0};
auto direction{end == VehicleEnd::front ? 1 : -1};
auto const *track{RaTrackGet()};
if (RaDirectionGet() < 0) {
direction = -direction;
}
auto distance{direction > 0 ? track->Length() - RaTranslationGet() : RaTranslationGet()};
found_stop found;
while (track != nullptr) {
auto const trackend{direction > 0 ? 1 : 0};
if (auto const &stop{track->bufferstop(trackend)}; stop != nullptr) {
found = {track, trackend, stop};
break;
}
if (distance > range) {
break;
}
TTrack const *next{nullptr};
if (direction > 0) {
if (track->iNextDirection) {
direction = -direction;
}
next = track->CurrentNext();
}
else {
if (false == track->iPrevDirection) {
direction = -direction;
}
next = track->CurrentPrev();
}
if (next == nullptr || TestFlag(next->iCategoryFlag, 0x80)) {
// a free end without a stop, or the piece past it made for a vehicle that ran off it
break;
}
track = next;
distance += track->Length();
}
if (found.stop == nullptr || found.stop->now.spent()) {
// none, or a wreck: the end is a free one
continue;
}
// the gap from the buffer face of the end to the face of the stop, along the track at the end
auto const outward{bufferstops::outward(*found.track, found.end)};
auto const face{bufferstops::face(*found.track, found.end, found.stop->stop.setback)};
auto const gap{glm::dot(face - vCoulpler[end], outward) - coupler.adapter_length};
auto const &neighbour{physics->Neighbours[end]};
if (neighbour.vehicle != nullptr && neighbour.distance < gap) {
// a vehicle in between is the obstacle
continue;
}
if (previous != found.stop) {
// another stop: no hit under way with it
contact.touching = false;
contact.reported = false;
contact.worst = bufferstop::outcome::none;
contact.vehicle_crush = 0.0;
}
contact.stop = found.stop;
contact.gap = gap;
}
}
+1
View File
@@ -256,6 +256,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) {
}
vehicle->physics->ComputeConstans();
vehicle->update_neighbours();
vehicle->update_track_ends();
}
update_coupler_physics();
Timer::subsystem.vehicles_prepare.stop();
+10
View File
@@ -789,6 +789,11 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin)
m_cwr = track_buckle::read_cwr( values );
}
}
else if( str == "bufferstop1" || str == "bufferstop2" ) {
// bufferstop<n> <kind>[;<a>[;<b>[;<setback>]]]: a buffer stop at the end n of the track, see physics/bufferstop.h.
// checked once the tracks are joined (path_table::InitBufferStops()); the semicolons stay in the token
m_bufferstopattributes[ str.back() - '1' ] = parser->getToken<std::string>( false, "\n\r\t " );
}
else if( str == "friction" ) {
// memory cell holding friction value modifiers
m_friction.first = parser->getToken<std::string>();
@@ -2953,6 +2958,11 @@ TTrack::export_as_text_( std::ostream &Output ) const {
if( eType == tt_Normal && iCategoryFlag == 1 ) {
Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr );
}
for( std::size_t end = 0; end < m_bufferstopattributes.size(); ++end ) {
if( false == m_bufferstopattributes[ end ].empty() ) {
Output << "bufferstop" << end + 1 << ' ' << m_bufferstopattributes[ end ] << ' ';
}
}
if( false == m_friction.first.empty() ) {
Output << "friction " << m_friction.first << ' ';
}
+25
View File
@@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/.
#include <vector>
#include <deque>
#include <array>
#include <memory>
#include <glm/glm.hpp>
#include <glm/mat4x4.hpp>
@@ -31,6 +32,9 @@ http://mozilla.org/MPL/2.0/.
namespace scene {
class basic_cell;
}
namespace bufferstop {
struct installation;
}
enum TTrackType {
tt_Unknown,
@@ -292,6 +296,9 @@ public:
track_uneven::attribute m_uneven; // plain tracks and switches
track_buckle::declared m_buckledeclared; // the buckle entered in the scenery; plain rail tracks
track_buckle::cwr m_cwr; // the welded rail, for the buckling by the temperature
// the values of the attributes bufferstop1 and bufferstop2 as the scenery gives them (physics/bufferstop.h), kept to be
// written back; empty for none
std::array<std::string, 2> m_bufferstopattributes;
private:
double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia)
public:
@@ -431,6 +438,12 @@ public:
return m_buckle; }
bool is_buckled() const {
return track_buckle::active( m_buckle ); }
// the buffer stop at the end of the track (0 at its point 1, 1 at its point 2), nullptr for none (physics.bufferstops,
// see path_table::InitBufferStops())
std::shared_ptr<bufferstop::installation> const &bufferstop( int const End ) const {
return m_bufferstops[ End & 1 ]; }
void bufferstop( int const End, std::shared_ptr<bufferstop::installation> Stop ) {
m_bufferstops[ End & 1 ] = std::move( Stop ); }
// buckles the track during the game as the values say, or with none straightens it, and makes its geometry again. Cause goes to the log
bool buckle_now( track_buckle::declared const &Values, std::string const &Cause );
// the buckling of the tracks by the temperature of the rails, physics.trackbuckling auto; once a minute
@@ -502,6 +515,7 @@ private:
};
switch_stray m_switchstray;
track_buckle::shape m_buckle;
std::array<std::shared_ptr<bufferstop::installation>, 2> m_bufferstops;
// the buckling by the temperature: the passes of the trains over the track, and the pass which will buckle it as its head leaves
std::uint32_t m_buckle_passes { 0 };
bool m_buckle_armed { false };
@@ -569,6 +583,14 @@ public:
// physics.trackcheck: logs the geometry of the rail tracks the checks of world/TrackCheck.h find suspicious
void
CheckTracks() const;
// physics.bufferstops: makes the buffer stops at the free ends of the rail tracks, of the attributes bufferstop1 and
// bufferstop2 of the tracks, and with auto of the models of the stops placed at the ends (world/bufferstops.cpp)
void
InitBufferStops();
// how many there are: none, the vehicles don't look for them
std::size_t
buffer_stops() const {
return m_bufferstopcount; }
// legacy method, sends list of occupied paths over network
void
TrackBusyList() const;
@@ -578,6 +600,9 @@ public:
// legacy method, sends state of specified path section over network
void
IsolatedBusy( std::string const &Name ) const;
private:
std::size_t m_bufferstopcount { 0 };
};
//---------------------------------------------------------------------------
+181
View File
@@ -0,0 +1,181 @@
/*
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/.
*/
// the buffer stops at the free ends of the rail tracks (physics.bufferstops, physics/bufferstop.h): those the scenery
// marks on its tracks, and with auto those its models of the stops give
#include "stdafx.h"
#include "world/bufferstops.h"
#include <algorithm>
#include <cmath>
#include <format>
#include <memory>
#include <optional>
#include <vector>
#include "world/Track.h"
#include "physics/bufferstop.h"
#include "model/AnimModel.h"
#include "model/Model3d.h"
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/utilities.h"
namespace bufferstops {
glm::dvec3 end_point(TTrack const &Track, int const End) {
auto const &segment{Track.CurrentSegment()};
return End == 0 ? segment->FastGetPoint_0() : segment->FastGetPoint_1();
}
glm::dvec3 outward(TTrack const &Track, int const End) {
// from a point a metre inside the track, or half of it for a shorter one, to the end
auto const length{Track.Length()};
auto const back{std::min(1.0, 0.5 * length)};
glm::dvec3 inner;
glm::vec3 rotation;
Track.CurrentSegment()->RaPositionGet(End == 0 ? back : length - back, inner, rotation);
auto direction{end_point(Track, End) - inner};
direction.y = 0.0;
auto const size{glm::length(direction)};
return size > 1e-6 ? direction / size : glm::dvec3{0.0, 0.0, 1.0};
}
glm::dvec3 face(TTrack const &Track, int const End, double const Setback) {
return end_point(Track, End) - Setback * outward(Track, End);
}
} // namespace bufferstops
namespace {
// a stop stands only at the free end of a plain rail track: not on a switch or a road, nor at the piece the vehicles
// running off an end make past it (auto_null)
bool takes_stop(TTrack const &Track) {
return Track.eType == tt_Normal && TestFlag(Track.iCategoryFlag, 1) && false == TestFlag(Track.iCategoryFlag, 0x80);
}
bool is_free(TTrack const &Track, int const End) {
return (End == 0 ? Track.CurrentPrev() : Track.CurrentNext()) == nullptr;
}
// a model must stand about level with the end: not on a bridge over it, nor under it [m]
constexpr double model_height_reach{3.0};
} // namespace
void path_table::InitBufferStops() {
m_bufferstopcount = 0;
if (Global.buffer_stops == global_settings::bufferstop_mode::off) {
return;
}
auto const install = [this](TTrack &Track, int const End, bufferstop::definition const &Stop, std::string const &Source) {
auto stop{std::make_shared<bufferstop::installation>()};
stop->stop = Stop;
stop->track = Track.name();
stop->end = End;
stop->source = Source;
Track.bufferstop(End, std::move(stop));
++m_bufferstopcount;
WriteLog(std::format("bufferstop: {} end {}: {}, by {}, its face {:.2f} m before the end", Track.name(), End + 1, bufferstop::kind_name(Stop.type), Source, Stop.setback));
};
// the free ends without the attribute, for the models
struct free_end {
TTrack *track{nullptr};
int end{0};
glm::dvec3 point;
glm::dvec3 outward;
};
std::vector<free_end> ends;
auto const automatic{Global.buffer_stops == global_settings::bufferstop_mode::automatic};
for (auto *track : m_items) {
if (track == nullptr) {
continue;
}
for (int end = 0; end < 2; ++end) {
auto const &attribute{track->m_bufferstopattributes[end]};
if (attribute.empty()) {
if (automatic && takes_stop(*track) && is_free(*track, end)) {
ends.push_back({track, end, bufferstops::end_point(*track, end), bufferstops::outward(*track, end)});
}
continue;
}
auto const stop{bufferstop::read_attribute(attribute)};
if (false == stop.has_value()) {
ErrorLog(std::format("Bad track: bufferstop{} \"{}\" of track \"{}\" isn't a buffer stop, ignored", end + 1, attribute, track->name()));
continue;
}
if (stop->type == bufferstop::kind::none) {
// opted out of the models
continue;
}
if (false == takes_stop(*track) || false == is_free(*track, end)) {
ErrorLog(std::format("Bad track: bufferstop{} of track \"{}\" at a joined end or not on a plain rail track, ignored", end + 1, track->name()));
continue;
}
install(*track, end, *stop, "the attribute");
}
}
if (ends.empty()) {
return;
}
// the models of the stops: each counts for the nearest free end it stands at, the nearest model for an end
auto const rules{bufferstop::default_rules()};
struct pick {
bufferstop::model_rule rule;
bufferstop::placement placement;
std::string model;
};
std::vector<std::optional<pick>> picks(ends.size());
for (auto const *instance : simulation::Instances.sequence()) {
if (instance == nullptr || instance->Model() == nullptr) {
continue;
}
auto const &file{instance->Model()->NameGet()};
auto const rule{bufferstop::match(file, rules)};
if (false == rule.has_value()) {
continue;
}
auto const &location{instance->location()};
std::optional<std::size_t> nearest;
bufferstop::placement placement;
for (std::size_t index = 0; index < ends.size(); ++index) {
auto const &end{ends[index]};
if (std::abs(location.y - end.point.y) > model_height_reach) {
continue;
}
auto const here{bufferstop::place(end.point.x, end.point.z, end.outward.x, end.outward.z, location.x, location.z)};
if (bufferstop::at_end(here) && (false == nearest.has_value() || here.distance < placement.distance)) {
nearest = index;
placement = here;
}
}
if (false == nearest.has_value()) {
continue;
}
auto &chosen{picks[*nearest]};
if (false == chosen.has_value() || placement.distance < chosen->placement.distance) {
chosen = pick{*rule, placement, file};
}
}
for (std::size_t index = 0; index < ends.size(); ++index) {
if (false == picks[index].has_value()) {
continue;
}
auto const &chosen{*picks[index]};
auto stop{bufferstop::preset(chosen.rule.type)};
stop.setback = bufferstop::model_setback(chosen.placement, chosen.rule);
install(*ends[index].track, ends[index].end, stop, std::format("model {} at {:.2f} m", chosen.model, chosen.placement.distance));
}
}
+26
View File
@@ -0,0 +1,26 @@
/*
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 <glm/glm.hpp>
class TTrack;
// where the buffer stops at the ends of the tracks stand (physics/bufferstop.h, path_table::InitBufferStops())
namespace bufferstops {
// the end of the track: 0 its point 1, 1 its point 2
glm::dvec3 end_point(TTrack const &Track, int End);
// the direction out of the track at the end, level
glm::dvec3 outward(TTrack const &Track, int End);
// the face of a stop standing the setback [m] before the end
glm::dvec3 face(TTrack const &Track, int End, double Setback);
} // namespace bufferstops