diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..98e703cc0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -113,6 +113,7 @@ set(SOURCES "world/RailCarve.cpp" "world/RailLayer.cpp" "world/TrackUneven.cpp" +"world/TrackBuckle.cpp" "world/Road.cpp" "world/Sweep.cpp" "world/RoadPoint.cpp" diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index 548a794d8..f88c91a18 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -3400,6 +3400,9 @@ void write_ending(std::ostream &Text, TTrack const &Style, bool const Switch) if ((Style.iCategoryFlag & 15) == 1 && false == Style.m_profile1.first.empty()) Text << "railprofile " << Style.m_profile1.first << ' '; Text << track_uneven::write_attribute(Style.m_uneven, Switch); + // the welded rail goes on in the piece; a buckle stays where it was + if (false == Switch && (Style.iCategoryFlag & 15) == 1) + Text << track_buckle::write_cwr(Style.m_cwr); // a piece of the track made from another one stays in its track circuit and under the same overhead line for (auto const *isolated : Style.Isolated) Text << "isolated " << isolated->asName << ' '; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..a25e4ccc7 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -130,6 +130,8 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Junctions.update( totaltime ); simulation::Roadpoints.update( totaltime ); simulation::Vehicles.update( Deltatime, Iterationcount ); + // the tracks the heat buckles, by itself or under the trains just moved + TTrack::update_buckling( totaltime ); } void diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp new file mode 100644 index 000000000..df26c74ab --- /dev/null +++ b/tests/unit/test_track_buckle.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackBuckle.h" + +#include + +// the buckling of welded track in the heat, world/TrackBuckle.h: the shape the track takes, the force and the temperature of the rails, +// the limits it buckles at and the draws, repeated with the same seed + +namespace { + +double constexpr pi_squared{9.869604401089358}; + +int count_buckled(double const Rise, track_buckle::limits const &Limits, std::uint32_t const Seed, int const Passes) +{ + auto count{0}; + for (int pass = 1; pass <= Passes; ++pass) + { + auto const draw{track_buckle::draw(track_buckle::name_hash("tor_1234"), Seed, track_buckle::pass, static_cast(pass))}; + if (track_buckle::decide(Rise, Limits, true, draw) == track_buckle::verdict::under_train) + ++count; + } + return count; +} + +} // namespace + +TEST_CASE("the force in a rail held from growing longer is E*A*alpha*dT") +{ + // PLK ST-T1-A8 designs for 35 K, 665 kN in a 60E1 rail, with its own alpha of about 1.18e-5 + auto const force{track_buckle::thermal_force(track_buckle::area_60e1, 35.0)}; + CHECK(force == doctest::Approx(650e3).epsilon(0.03)); + CHECK(force == doctest::Approx(665e3).epsilon(0.03)); + // Kish, Samavedam: about 2.5 kips a rail for each degree F in a 136 lb rail (13.35 sq in), 20.0 kN/K + CHECK(track_buckle::thermal_force(13.35 * 6.4516e-4, 1.0) == doctest::Approx(20.0e3).epsilon(0.05)); + // lighter rails press less + CHECK(track_buckle::thermal_force(track_buckle::area_49e1, 35.0) < force); + CHECK(track_buckle::rail_area("49E1_rail") == track_buckle::area_49e1); + CHECK(track_buckle::rail_area("S42") == track_buckle::area_s42); + CHECK(track_buckle::rail_area("") == track_buckle::area_60e1); +} + +TEST_CASE("a rail is as warm as the air at night or under clouds, 17 K warmer in full sun") +{ + CHECK(track_buckle::rail_temperature(30.0, -10.0, 0.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 0.0) == doctest::Approx(47.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 1.0) == doctest::Approx(30.0)); + // rain cools as much as clouds + CHECK(track_buckle::rail_temperature(30.0, 90.0, 2.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 30.0, 0.0) == doctest::Approx(38.5)); + CHECK(track_buckle::rail_temperature(30.0, 60.0, 0.5) == doctest::Approx(30.0 + 17.0 * std::sin(60.0 * 3.141592653589793 / 180.0) * 0.5)); +} + +TEST_CASE("the limits of the grades meet the heat the tracks of PLK deform in") +{ + track_buckle::cwr track; + auto const average{track_buckle::limits_of(track, 0.0, 0.0)}; + // at the neutral 26 C under a train from rails at 58 C, by itself from 71 C: PLK, deformations with the rails above 70 C + CHECK(track.neutral + average.low == doctest::Approx(58.0)); + CHECK(track.neutral + average.high == doctest::Approx(71.0)); + // Kish, Samavedam: the chance of a buckle of a straight track grows fast from rails at 63 C with the neutral at 27 C, 36 K + CHECK(36.0 > average.low); + CHECK(36.0 < average.high); + // the design of PLK, 35 K, is short of where a good track buckles under a train + track.grade = track_buckle::grade::good; + CHECK(track_buckle::limits_of(track, 0.0, 0.0).low > 35.0); + // worked lately: weak whatever the grade + track.worked = true; + auto const worked{track_buckle::limits_of(track, 0.0, 0.0)}; + CHECK(worked.low == doctest::Approx(22.0)); + CHECK(worked.high == doctest::Approx(32.0)); + // curves and an uneven line lower them + track = {}; + CHECK(track_buckle::limits_of(track, 500.0, 0.0).low == doctest::Approx(29.0)); + CHECK(track_buckle::limits_of(track, -250.0, 0.0).low == doctest::Approx(26.0)); + CHECK(track_buckle::limits_of(track, 2000.0, 0.0).low == doctest::Approx(32.0)); + CHECK(track_buckle::limits_of(track, 0.0, 20.0).high == doctest::Approx(42.0)); + // FRA, the dynamic test: a 7.5 degree curve (233 m) with a 19 mm misalignment buckled under the train at 34 K + auto const fra{track_buckle::limits_of(track, 233.0, 19.0)}; + CHECK(34.0 > fra.low); + CHECK(34.0 < fra.high); +} + +TEST_CASE("below the lower limit a track never buckles, at the upper one it buckles by itself") +{ + track_buckle::limits const limits{32.0, 45.0}; + for (auto const draw : {0.0, 0.3, 0.999}) + { + CHECK(track_buckle::decide(31.9, limits, true, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(31.9, limits, false, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(45.0, limits, false, draw) == track_buckle::verdict::by_itself); + // in between only under a train + CHECK(track_buckle::decide(44.0, limits, false, draw) == track_buckle::verdict::none); + } + CHECK(track_buckle::chance(32.0, limits) == doctest::Approx(0.0)); + CHECK(track_buckle::chance(38.5, limits) == doctest::Approx(0.5)); + CHECK(track_buckle::chance(50.0, limits) == doctest::Approx(1.0)); + // a train going slowly and not braking doesn't stir it up + CHECK_FALSE(track_buckle::stirs(30.0, false)); + CHECK(track_buckle::stirs(30.0, true)); + CHECK(track_buckle::stirs(60.0, false)); + CHECK_FALSE(track_buckle::stirs(3.0, true)); +} + +TEST_CASE("the share of the passes that buckle a track grows with the heat, and repeats with the seed") +{ + track_buckle::limits const limits{32.0, 45.0}; + auto const passes{4000}; + auto const quarter{count_buckled(32.0 + 0.25 * 13.0, limits, 7, passes)}; + auto const most{count_buckled(32.0 + 0.75 * 13.0, limits, 7, passes)}; + CHECK(quarter == doctest::Approx(0.25 * passes).epsilon(0.1)); + CHECK(most == doctest::Approx(0.75 * passes).epsilon(0.05)); + CHECK(count_buckled(31.0, limits, 7, passes) == 0); + // the same seed and track, the same passes + CHECK(count_buckled(38.0, limits, 7, passes) == count_buckled(38.0, limits, 7, passes)); + auto const key{track_buckle::name_hash("tor_1234")}; + CHECK(track_buckle::draw(key, 7, track_buckle::pass, 3) == track_buckle::draw(key, 7, track_buckle::pass, 3)); + // another seed, other draws + auto differ{0}; + for (std::uint64_t pass = 1; pass <= 100; ++pass) + if (track_buckle::draw(key, 7, track_buckle::pass, pass) != track_buckle::draw(key, 8, track_buckle::pass, pass)) + ++differ; + CHECK(differ == 100); + // and another track + CHECK(track_buckle::draw(track_buckle::name_hash("tor_1235"), 7, track_buckle::pass, 3) != track_buckle::draw(key, 7, track_buckle::pass, 3)); + // the draws spread over 0 to 1 + auto low{0}; + for (std::uint64_t pass = 1; pass <= 1000; ++pass) + { + auto const draw{track_buckle::draw(key, 7, track_buckle::pass, pass)}; + CHECK(draw >= 0.0); + CHECK(draw < 1.0); + if (draw < 0.5) + ++low; + } + CHECK(low == doctest::Approx(500).epsilon(0.1)); +} + +TEST_CASE("the heat buckles a track at one place in about 10 km, and wherever the bed was worked on") +{ + auto sites{0}; + auto const tracks{20000}; + for (int track = 0; track < tracks; ++track) + if (track_buckle::weak_spot(track_buckle::name_hash("t" + std::to_string(track)), 3, 500.0, false)) + ++sites; + // 500 m each, 10 000 km together: about 1000 + CHECK(sites == doctest::Approx(1000).epsilon(0.1)); + CHECK(track_buckle::weak_spot(track_buckle::name_hash("t1"), 3, 1.0, true)); +} + +TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way and ends smoothly") +{ + track_buckle::shape const shape{0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(shape, 60.0) == doctest::Approx(0.4)); + CHECK(track_buckle::slope(shape, 60.0) == doctest::Approx(0.0)); + // the main lobe crosses the line one length apart + CHECK(track_buckle::offset(shape, 60.0 - 7.0) == doctest::Approx(0.0)); + CHECK(track_buckle::offset(shape, 60.0 + 7.0) == doctest::Approx(0.0)); + // the side lobes the other way, a quarter as far out + CHECK(track_buckle::offset(shape, 60.0 + 14.0) == doctest::Approx(-0.1)); + CHECK(track_buckle::offset(shape, 60.0 - 14.0) == doctest::Approx(-0.1)); + // into the straight track at the ends with no displacement, slope or curvature + CHECK(track_buckle::reach(shape) == doctest::Approx(21.0)); + for (auto const at : {-21.0 + 1e-6, 21.0 - 1e-6}) + { + CAPTURE(at); + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::slope(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::bend(shape, 60.0 + at) == doctest::Approx(0.0)); + } + // nothing beyond + CHECK(track_buckle::offset(shape, 60.0 + 21.5) == 0.0); + CHECK(track_buckle::bend(shape, 60.0 - 30.0) == 0.0); + // symmetric + for (auto const at : {1.0, 4.0, 7.5, 12.0, 16.0, 20.0}) + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(track_buckle::offset(shape, 60.0 - at))); + // the largest curvature 11/9 pi^2 a / L^2 in the middle, bending back towards the line + auto const peak{track_buckle::peak_bend(0.4, 14.0)}; + CHECK(peak == doctest::Approx(11.0 / 9.0 * pi_squared * 0.4 / (14.0 * 14.0))); + CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); + // none larger anywhere, and the curvature with no jumps + auto previous{track_buckle::bend(shape, 35.0)}; + for (auto at = 35.0; at <= 85.0; at += 0.01) + { + auto const bend{track_buckle::bend(shape, at)}; + CHECK(std::abs(bend) <= peak * 1.0001); + CHECK(std::abs(bend - previous) < 0.01 * peak); + previous = bend; + } + // the curvature as the displacement has it + auto const step{0.01}; + for (auto const at : {42.0, 50.5, 55.0, 61.0, 66.0, 73.0, 79.0}) + { + CAPTURE(at); + auto const slope{(track_buckle::offset(shape, at + step) - track_buckle::offset(shape, at - step)) / (2.0 * step)}; + auto const bend{(track_buckle::offset(shape, at + step) - 2.0 * track_buckle::offset(shape, at) + track_buckle::offset(shape, at - step)) / (step * step)}; + CHECK(track_buckle::slope(shape, at) == doctest::Approx(slope).epsilon(1e-4)); + CHECK(track_buckle::bend(shape, at) == doctest::Approx(bend).epsilon(1e-3)); + } + // to the left + track_buckle::shape const left{-0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(left, 60.0) == doctest::Approx(-0.4)); + CHECK(track_buckle::bend(left, 60.0) == doctest::Approx(peak)); + // none + CHECK(track_buckle::offset(track_buckle::shape{}, 60.0) == 0.0); + CHECK_FALSE(track_buckle::active(track_buckle::shape{})); +} + +TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase, a body that of its pivots") +{ + track_buckle::shape const shape{0.3, 20.0, 50.0}; + auto const peak{track_buckle::peak_bend(0.3, 20.0)}; + CHECK(track_buckle::mean_bend(shape, 50.0, 0.0) == doctest::Approx(track_buckle::bend(shape, 50.0))); + // a bogie 2.5 m long, almost the whole of it + CHECK(std::abs(track_buckle::mean_bend(shape, 50.0, 2.5)) > 0.95 * peak); + // the mean of the curvature over the stretch, anywhere + for (auto const at : {32.0, 42.0, 50.0, 57.5, 64.0}) + { + CAPTURE(at); + auto sum{0.0}; + auto const parts{2500}; + for (int part = 0; part < parts; ++part) + sum += track_buckle::bend(shape, at - 1.25 + (part + 0.5) * 2.5 / parts); + CHECK(track_buckle::mean_bend(shape, at, 2.5) == doctest::Approx(sum / parts).epsilon(1e-3)); + } + // a body on the pivots 0 apart is a bogie + CHECK(track_buckle::body_bend(shape, 47.0, 0.0, 2.5) == doctest::Approx(track_buckle::mean_bend(shape, 47.0, 2.5))); + // a coach with its pivots 17 m apart over the main lobe: its pivots are on the flanks, which bend the other way + auto const across{track_buckle::body_bend(shape, 50.0, 17.0, 2.5)}; + CHECK(std::abs(across) < 0.5 * peak); + // the most the body feels, at any place, is less than a bogie does + auto most{0.0}; + for (auto at = 20.0; at <= 80.0; at += 0.05) + most = std::max(most, std::abs(track_buckle::body_bend(shape, at, 17.0, 2.5))); + CHECK(most < 0.95 * peak); + CHECK(most > 0.3 * peak); +} + +TEST_CASE("the equivalent radius of a buckle") +{ + // the default ones as sharp as the raised cosine lobes of the research note: 0.4 m by 18 m on a straight 41 m, 0.2 by 14 in a curve 50 m + CHECK(1.0 / track_buckle::peak_bend(track_buckle::straight_amplitude, track_buckle::straight_length) == doctest::Approx(41.0).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(track_buckle::curve_amplitude, track_buckle::curve_length) == doctest::Approx(49.6).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(0.3, 20.0) == doctest::Approx(110.5).epsilon(0.01)); +} + +TEST_CASE("the entries buckle and cwr are read and written back") +{ + auto const buckle{track_buckle::read_buckle("400;18;60")}; + CHECK(buckle.amplitude == 400.f); + CHECK(buckle.length == 18.f); + CHECK(buckle.centre == 60.f); + CHECK(buckle.side == 0); + CHECK(track_buckle::write_buckle(buckle) == "buckle 400;18;60 "); + auto const left{track_buckle::read_buckle("250;;;-1")}; + CHECK(left.amplitude == 250.f); + CHECK(left.length < 0.f); + CHECK(left.centre < 0.f); + CHECK(left.side == -1); + CHECK(track_buckle::write_buckle(left) == "buckle 250;;;-1 "); + CHECK(track_buckle::read_buckle(track_buckle::write_buckle(left).substr(7)).side == -1); + // kept within bounds + auto const wild{track_buckle::read_buckle("5000;100;-5;3")}; + CHECK(wild.amplitude == 1000.f); + CHECK(wild.length == 60.f); + CHECK(wild.centre < 0.f); + CHECK(wild.side == 1); + CHECK(track_buckle::read_buckle("300;1").length == 4.f); + // none + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("0;18;60"))); + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("x"))); + CHECK(track_buckle::write_buckle(track_buckle::declared{}).empty()); + + auto const cwr{track_buckle::read_cwr("20;2;1")}; + CHECK(cwr.neutral == 20.f); + CHECK(cwr.grade == track_buckle::grade::weak); + CHECK(cwr.worked); + CHECK(track_buckle::write_cwr(cwr) == "cwr 20;2;1 "); + auto const partial{track_buckle::read_cwr("22")}; + CHECK(partial.neutral == 22.f); + CHECK(partial.grade == track_buckle::grade::average); + CHECK_FALSE(partial.worked); + CHECK(track_buckle::write_cwr(partial) == "cwr 22;1 "); + auto const bounded{track_buckle::read_cwr("99;7")}; + CHECK(bounded.neutral == 60.f); + CHECK(bounded.grade == 2); + // the default isn't written + CHECK(track_buckle::write_cwr(track_buckle::read_cwr("26;1;0")).empty()); +} + +TEST_CASE("a buckle is laid into its track away from the ends, out of a curve") +{ + auto const values{track_buckle::read_buckle("400;18;60")}; + auto const straight{track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.2)}; + CHECK(straight.centre == 60.0); + CHECK(straight.length == 18.0); + // the side drawn on a straight + CHECK(straight.amplitude == doctest::Approx(-0.4)); + CHECK(track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.7).amplitude == doctest::Approx(0.4)); + // out of a curve, whatever the draw + CHECK(track_buckle::resolve(values, 200.0, 1, 400.0, 0.5, 0.2).amplitude == doctest::Approx(0.4)); + CHECK(track_buckle::resolve(values, 200.0, -1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the side given wins + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;60;-1"), 200.0, 1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the centre kept away from the ends by the reach, 1.5 lengths, and a margin + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;5"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;195"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(171.0)); + // drawn where not given + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 0.0, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 1.0, 0.2).centre == doctest::Approx(171.0)); + // the length by the shape of the track: a curve goes out less far and shorter + CHECK(track_buckle::resolve(track_buckle::read_buckle("200"), 200.0, 1, 400.0, 0.5, 0.2).length == track_buckle::curve_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 0, 0.0, 0.5, 0.2).length == track_buckle::straight_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 1, 3000.0, 0.5, 0.2).length == track_buckle::straight_length); + // too short a track + CHECK_FALSE(track_buckle::active(track_buckle::resolve(values, 57.9, 0, 0.0, 0.5, 0.2))); + CHECK(track_buckle::active(track_buckle::resolve(values, 58.0, 0, 0.0, 0.5, 0.2))); + // the natural ones + CHECK(track_buckle::natural(true).amplitude == 200.f); + CHECK(track_buckle::natural(false).length == 14.f); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..37dd30eed 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -872,6 +872,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackbuckling") + { + // off, scenery: the buckles of the scenery and its events, auto: also by the temperature of the rails + std::string mode; + ParseOne(Parser, mode, 1); + if (mode == "off" || mode == "no") + track_buckling = track_buckling_mode::off; + else if (mode == "auto") + track_buckling = track_buckling_mode::automatic; + else + track_buckling = track_buckling_mode::scenery; + return true; + } + if (token == "couplerphysics") { // yes: the player's train and the trains it closes in on, all: every train @@ -1783,6 +1797,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.offset", ScenarioTimeOffset ); export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); + export_as_text( Output, "physics.trackbuckling", std::string{ + track_buckling == track_buckling_mode::off ? "off" : + track_buckling == track_buckling_mode::automatic ? "auto" : + "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; diff --git a/utilities/Globals.h b/utilities/Globals.h index 19dabab53..e82beddd4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -284,6 +284,10 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + // the buckling of welded track in the heat (physics.trackbuckling in eu07.ini, see world/TrackBuckle.h): off, none; scenery, the + // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places + enum class track_buckling_mode { off, scenery, automatic }; + track_buckling_mode track_buckling = track_buckling_mode::scenery; // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every diff --git a/world/Event.cpp b/world/Event.cpp index 80697cfa2..2452b7881 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -2054,6 +2054,69 @@ track_event::export_as_text_( std::ostream &Output ) const { +// prepares event for use +void +buckle_event::init() { + + init_targets( simulation::Paths, "track" ); +} + +// event type string +std::string +buckle_event::type() const { + + return "trackbuckle"; +} + +// deserialize() subclass details +void +buckle_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { + + Input.getTokens(); + Input >> m_buckle.amplitude; + m_buckle.amplitude = std::clamp( m_buckle.amplitude, 0.f, static_cast( 1000.0 * track_buckle::most_amplitude ) ); + Input.getTokens(); + // the length, the centre and the side, each optional + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.length; + if( m_buckle.length > 0.f ) { + m_buckle.length = std::clamp( m_buckle.length, static_cast( track_buckle::least_length ), static_cast( track_buckle::most_length ) ); + } + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.centre; + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + auto side { 0.f }; + Input >> side; + m_buckle.side = ( side > 0.f ? 1 : side < 0.f ? -1 : 0 ); + Input.getTokens(); + } +} + +// run() subclass details +void +buckle_event::run_() { + + WriteLog( "Type: TrackBuckle - [" + to_string( m_buckle.amplitude, 0 ) + " mm]" ); + for( auto &target : m_targets ) { + auto *targettrack = static_cast( std::get( target ) ); + if( targettrack == nullptr ) { continue; } + targettrack->buckle_now( m_buckle, "event " + m_name ); + } +} + +// export_as_text() subclass details +void +buckle_event::export_as_text_( std::ostream &Output ) const { + + Output << m_buckle.amplitude << ' ' << m_buckle.length << ' ' << m_buckle.centre << ' ' << m_buckle.side << ' '; +} + + + // prepares event for use void voltage_event::init() { @@ -2310,6 +2373,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { else if( type == "multiple" ) { event = new multi_event(); } else if( type == "switch" ) { event = new switch_event(); } else if( type == "trackvel" ) { event = new track_event(); } + else if( type == "trackbuckle" ) { event = new buckle_event(); } else if( type == "sound" ) { event = new sound_event(); } else if( type == "texture" ) { event = new texture_event(); } else if( type == "animation" ) { event = new animation_event(); } diff --git a/world/Event.h b/world/Event.h index f1d75689b..090d165d6 100644 --- a/world/Event.h +++ b/world/Event.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scene.h" #include "utilities/Names.h" #include "world/EvLaunch.h" +#include "world/TrackBuckle.h" #include "utilities/Logs.h" #include "input/command.h" #include "utilities/comparison.h" @@ -527,6 +528,31 @@ private: +// trackbuckle [ [ []]]: the target tracks buckle in the heat as the entry +// "buckle" of a track says (see world/TrackBuckle.h), amplitude 0 straightens them +class buckle_event : public basic_event { + +public: +// methods + // prepares event for use + void init() override; + +private: +// methods + // event type string + std::string type() const override; + // deserialize() subclass details + void deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) override; + // run() subclass details + void run_() override; + // export_as_text() subclass details + void export_as_text_( std::ostream &Output ) const override; +// members + track_buckle::declared m_buckle; +}; + + + class voltage_event : public basic_event { public: diff --git a/world/Segment.cpp b/world/Segment.cpp index d1c5f2c89..5e0f47116 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -141,6 +141,10 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N // dense enough for the waves; a switch keeps its division, the blades depend on it fStep = std::min( fStep, 2.0 ); } + if( m_setting.buckled ) { + // and for the lobes of a buckle, 9 m and more + fStep = std::min( fStep, 1.0 ); + } // NOTE: optionally replace this part with the commented version, after solving geometry issues with double switches if( pOwner->eType == tt_Switch && fStep * (3.0 * Global.SplineFidelity) > fLength ) { @@ -431,14 +435,33 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const }; */ -glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { - auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; - result.y -= pOwner->joint_dip( Distance ); +glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const { + glm::dvec3 result { 0.0 }; + if( m_setting.uneven ) { + auto const field { track_uneven::field( Point ) }; + result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result.y -= pOwner->joint_dip( Distance ); + } + if( m_setting.buckled && m_pieces.empty() ) { + result += Across * track_buckle::offset( pOwner->buckle(), Distance ); + } return result; } +double TSegment::buckle_bend( double const Distance, double const Base ) const { + if( false == m_setting.buckled || false == m_pieces.empty() ) { + return 0.0; + } + return track_buckle::mean_bend( pOwner->buckle(), Distance, Base ); +} + +glm::dvec3 TSegment::across_at( double const Distance ) const { + glm::dvec3 point; + glm::dvec3 across; + plan_frame( Distance, point, across ); + return across; +} + glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( false == m_setting.uneven ) { return glm::dvec3 { 0.0 }; @@ -453,12 +476,13 @@ glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) { point += direction * ( ( At - on ) / glm::length( direction ) ); } - return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); }; + // the buckle left out: its curvature is taken on its own, see buckle_bend() + return stray( point, pOwner->uneven_at( At, m_setting.path ), At, glm::dvec3 { 0.0 } ); }; return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach ); } void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const { - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } // the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays @@ -468,9 +492,9 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi if( share <= 0.0 ) { return; } - auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); - Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; + Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const { @@ -500,17 +524,18 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: rotation.y = static_cast(fStoop); // pochylenie toru prostego rotation.z = static_cast(fDirection); // kierunek toru w planie } - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } - // direction and slope stay as designed: the physics takes the curve radius and the grade from them + // direction and slope stay as designed: the physics takes the curve radius and the grade from them, and the curvature of a buckle + // on its own (buckle_bend()) auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; - auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; rotation.x += static_cast( track_uneven::stray_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); - position += track_uneven::across_only( stray( position, amount, fDistance ), across ); + position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { diff --git a/world/Segment.h b/world/Segment.h index 3255de362..58d5785f3 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -96,6 +96,7 @@ class TSegment struct setting { std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint bool uneven { false }; // see TrackUneven.h + bool buckled { false }; // see TrackBuckle.h int path { 0 }; // which path of a switch // where the path meets the next one: the middle of their ends and their common vector across std::array>, 2> joints; @@ -132,8 +133,9 @@ class TSegment // moves a lofted vertex with the unevenness of the track void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const; - // displacement of a point by the unevenness, at a distance along the path - glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const; + // displacement of a point by the unevenness, at a distance along the path, and by the buckle of the track across it, along Across + // (none along a zero vector) + glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const; public: bool bCurve = false; @@ -188,6 +190,10 @@ public: set_uneven( bool const Uneven, int const Path = 0 ) { m_setting.uneven = Uneven; m_setting.path = Path; } + // call before Init too + void + set_buckled( bool const Buckled ) { + m_setting.buckled = Buckled; } // a point of the path and the unit vector across it in the plan, towards the right rail profile; zero for a path never made void plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const; @@ -201,6 +207,13 @@ public: // second derivative of the displacement along the path; times speed squared: acceleration of an axle glm::dvec3 uneven_bend( double const Distance ) const; + // the curvature the buckle of the track adds to the path at the distance, 1/m, positive bending towards its right; averaged over Base + // around it, as a bogie or a body takes it + double + buckle_bend( double const Distance, double const Base = 0.0 ) const; + // the unit vector across the path at the distance, towards its right + glm::dvec3 + across_at( double const Distance ) const; glm::dvec3 FastGetPoint(double const t) const; inline glm::dvec3 diff --git a/world/Track.cpp b/world/Track.cpp index 947a5836c..27bf7c9dc 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -756,6 +756,20 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) m_uneven = track_uneven::read_attribute( values, eType == tt_Switch ); } } + else if( str == "buckle" ) { + // buckle ;;[;]: the track buckled by the heat, see TrackBuckle.h + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_buckledeclared = track_buckle::read_buckle( values ); + } + } + else if( str == "cwr" ) { + // cwr ;[;]: the welded rail, for the buckling by the temperature + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_cwr = track_buckle::read_cwr( values ); + } + } else if( str == "friction" ) { // memory cell holding friction value modifiers m_friction.first = parser->getToken(); @@ -818,8 +832,15 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) // from the scenery is put back after it auto const velocity { fVelocity }; init_segments( true ); + // the buckle goes along the path made + if( Global.track_buckling != global_settings::track_buckling_mode::off && track_buckle::given( m_buckledeclared ) ) { + m_buckle = resolve_buckle( m_buckledeclared, 0 ); + if( false == is_buckled() ) { + ErrorLog( "Bad track: \"" + m_name + "\" too short for its buckle" ); + } + } // made with no unevenness, which is read with the attributes and goes onto them by making them again - if( is_uneven() ) { + if( is_uneven() || is_buckled() ) { init_segments( false ); } if( SwitchExtension ) { @@ -875,6 +896,7 @@ void TTrack::init_segments( bool const Initial ) { } else if( Segment ) { Segment->set_uneven( is_uneven() ); + Segment->set_buckled( is_buckled() ); } switch (eType) { @@ -1266,6 +1288,10 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) } } } + if( Dynamics.empty() ) { + // a train comes onto the track, which can buckle under it in the heat + buckle_pass_enter( *Dynamic ); + } Dynamics.emplace_back( Dynamic ); Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy if( Dynamic->iOverheadMask ) { @@ -1313,6 +1339,10 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } + if( result ) { + // the head of a train leaving the track the pass was drawn to buckle + buckle_pass_leave(); + } if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { @@ -2868,6 +2898,9 @@ TTrack::export_as_text_( std::ostream &Output ) const { Output << "railprofile " << m_profile1.first << ' '; } Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch ); + if( eType == tt_Normal && iCategoryFlag == 1 ) { + Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr ); + } if( false == m_friction.first.empty() ) { Output << "friction " << m_friction.first << ' '; } diff --git a/world/Track.h b/world/Track.h index 033bee610..3fefde977 100644 --- a/world/Track.h +++ b/world/Track.h @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Segment.h" #include "world/RailLayout.h" #include "world/TrackSleepers.h" +#include "world/TrackBuckle.h" #include "world/TrackUneven.h" #include "model/material.h" #include "scene/scenenode.h" @@ -278,6 +279,8 @@ public: int iAction = 0; // czy modyfikowany eventami (specjalna obsługa przy skanowaniu) float fOverhead = -1.0; // można normalnie pobierać prąd (0 dla jazdy bezprądowej po danym odcinku, >0-z opuszczonym i ograniczeniem prędkości) 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 private: double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia) public: @@ -412,6 +415,17 @@ public: track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ); // how much of the displacement a point of the profile at the depth takes double uneven_bed_share( double const Depth ) const; + // the buckle the track has now (see TrackBuckle.h): none with physics.trackbuckling off + track_buckle::shape const &buckle() const { + return m_buckle; } + bool is_buckled() const { + return track_buckle::active( m_buckle ); } + // 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 + static void update_buckling( double const Deltatime ); + // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight + double plan_radius( double const Distance, int &Outward ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm @@ -473,6 +487,21 @@ private: int stamp { -1 }; }; switch_stray m_switchstray; + track_buckle::shape m_buckle; + // 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 }; + // the buckle of the values on this track, its place and side drawn with the seed where not given + track_buckle::shape resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const; + // the draws for this track: by its name, by where it is for one with none + std::uint64_t buckle_key() const; + // whether the temperature can buckle the track, and the rise of the rails above its neutral temperature it does it at + bool buckles_by_heat() const; + track_buckle::limits buckle_limits() const; + // a train coming onto the track and its head leaving it, for the buckling under a train + void buckle_pass_enter( TDynamicObject const &Dynamic ); + void buckle_pass_leave(); + void buckle_under_train(); switch_stray const &switch_uneven(); void settle_switch_stray(); void settle_switch_ends(); diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp new file mode 100644 index 000000000..b49dd5753 --- /dev/null +++ b/world/TrackBuckle.cpp @@ -0,0 +1,233 @@ +/* +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 "world/Track.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "scene/scene.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "vehicle/DynObj.h" + +#include + +namespace { + +// how often the temperature is checked, s of the simulation +double constexpr check_interval { 60.0 }; +// the tracks the temperature can buckle, found at the first check +std::vector heat_sites; +bool heat_sites_found { false }; +double heat_clock { 0.0 }; +// the tracks to buckle under a train, done with the next update rather than amid the moves of the vehicles +std::vector heat_due; + +double rail_temperature_now() { + + return track_buckle::rail_temperature( Global.AirTemperature, simulation::Environment.sun().getAngle(), Global.Overcast ); +} + +} // namespace + +double TTrack::plan_radius( double const Distance, int &Outward ) const { + + Outward = 0; + if( Segment == nullptr || eType != tt_Normal ) { + return 0.0; + } + auto const length { Segment->GetLength() }; + auto const reach { std::min( 5.0, 0.25 * length ) }; + auto const at { std::clamp( Distance, reach, length - reach ) }; + glm::dvec3 behind, middle, ahead, across; + Segment->plan_frame( at - reach, behind, across ); + Segment->plan_frame( at + reach, ahead, across ); + Segment->plan_frame( at, middle, across ); + auto bend { ( behind + ahead - 2.0 * middle ) / ( reach * reach ) }; + bend.y = 0.0; + auto const curvature { glm::length( bend ) }; + // straighter than the curves the tracks are laid with + if( curvature < 1.0 / 20000.0 ) { + return 0.0; + } + // away from the centre, which the bend points to + Outward = ( glm::dot( bend, across ) > 0.0 ? -1 : 1 ); + return 1.0 / curvature; +} + +std::uint64_t TTrack::buckle_key() const { + + if( false == m_name.empty() && m_name != "none" ) { + return track_buckle::name_hash( m_name ); + } + auto const point { location() }; + return track_buckle::name_hash( std::format( "{:.1f};{:.1f};{:.1f}", point.x, point.y, point.z ) ); +} + +track_buckle::shape TTrack::resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const { + + if( Segment == nullptr || eType != tt_Normal || iCategoryFlag != 1 ) { + return {}; + } + auto const length { Segment->GetLength() }; + auto const key { buckle_key() }; + auto const place { track_buckle::draw( key, Seed, track_buckle::place ) }; + // the side out of the curve where the buckle is + auto const centre { Values.centre >= 0.f ? static_cast( Values.centre ) : 0.5 * length }; + auto outward { 0 }; + auto const radius { plan_radius( centre, outward ) }; + return track_buckle::resolve( Values, length, outward, radius, place, track_buckle::draw( key, Seed, track_buckle::way ) ); +} + +bool TTrack::buckle_now( track_buckle::declared const &Values, std::string const &Cause ) { + + if( Global.track_buckling == global_settings::track_buckling_mode::off ) { + return false; + } + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr ) { + ErrorLog( "Bad track: \"" + m_name + "\" can't buckle, it isn't a plain rail track" ); + return false; + } + auto const shape { resolve_buckle( Values, 0 ) }; + if( track_buckle::given( Values ) && false == track_buckle::active( shape ) ) { + ErrorLog( std::format( "Bad track: \"{}\" too short for a buckle {:.0f} m long", m_name, 2.0 * track_buckle::reach_share * ( Values.length > 0.f ? Values.length : track_buckle::straight_length ) ) ); + return false; + } + m_buckle = shape; + m_buckle_armed = false; + // made again with the buckle, which the rails, the sleepers and the axles on the track follow + init_segments( false ); + auto const rebuild = []( TTrack &Track ) { + auto §ion { simulation::Region->section( Track.location() ) }; + Track.rebuild_geometry( section.m_geometrycreated ? section.m_geometrybank : gfx::geometrybank_handle {} ); }; + rebuild( *this ); + for( auto *crossing : m_crossings ) { + if( crossing != nullptr && crossing != this ) { + rebuild( *crossing ); + } + } + if( is_buckled() ) { + WriteLog( std::format( + "Track \"{}\" buckled ({}): {:.0f} mm to the {} at {:.1f} m, main lobe {:.1f} m, curvature up to 1/{:.0f} m", + m_name, Cause, std::abs( 1000.0 * m_buckle.amplitude ), m_buckle.amplitude > 0.0 ? "right" : "left", m_buckle.centre, m_buckle.length, + 1.0 / track_buckle::peak_bend( m_buckle.amplitude, m_buckle.length ) ) ); + } + else { + WriteLog( "Track \"" + m_name + "\" straightened (" + Cause + ")" ); + } + return true; +} + +bool TTrack::buckles_by_heat() const { + + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr || is_buckled() || false == m_crossings.empty() ) { + return false; + } + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + // continuous welded rail is laid down to a radius of 190 m (PLK ST-T1-A8) + if( radius > 0.0 && radius < 190.0 ) { + return false; + } + auto const natural { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + if( Segment->GetLength() < 2.0 * ( track_buckle::reach_share * natural.length + track_buckle::end_margin ) ) { + return false; + } + return track_buckle::weak_spot( buckle_key(), Global.random_seed, Segment->GetLength(), m_cwr.worked ); +} + +track_buckle::limits TTrack::buckle_limits() const { + + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + return track_buckle::limits_of( m_cwr, radius, uneven_declared().side ); +} + +void TTrack::update_buckling( double const Deltatime ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic ) { + return; + } + if( false == heat_sites_found ) { + heat_sites_found = true; + for( auto *track : simulation::Paths.sequence() ) { + if( track != nullptr && track->buckles_by_heat() ) { + heat_sites.push_back( track ); + } + } + WriteLog( std::format( "Track buckling: {} places the heat can buckle", heat_sites.size() ) ); + // the first check right away, a scenario can start in the heat + heat_clock = check_interval; + } + for( auto *track : heat_due ) { + track->buckle_under_train(); + } + heat_due.clear(); + heat_clock += Deltatime; + if( heat_clock < check_interval ) { + return; + } + heat_clock = 0.0; + auto const rail { rail_temperature_now() }; + for( auto *track : heat_sites ) { + if( track->is_buckled() ) { + continue; + } + auto const rise { rail - track->m_cwr.neutral }; + if( track_buckle::decide( rise, track->buckle_limits(), false, 1.0 ) == track_buckle::verdict::by_itself ) { + auto outward { 0 }; + auto const radius { track->plan_radius( 0.5 * track->Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, track->Segment->GetLength(), outward, radius, + track_buckle::draw( track->buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + track->buckle_now( values, std::format( "rails at {:.0f} C, {:.0f} K above neutral, {:.0f} kN in each", rail, rise, + 0.001 * track_buckle::thermal_force( track_buckle::rail_area( track->m_profile1.first ), rise ) ) ); + } + } +} + +void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic || is_buckled() || false == heat_sites_found ) { + return; + } + if( std::ranges::find( heat_sites, this ) == heat_sites.end() ) { + return; + } + ++m_buckle_passes; + auto const *mover { Dynamic.MoverParameters }; + auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + auto const rise { rail_temperature_now() - m_cwr.neutral }; + auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; + m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); +} + +void TTrack::buckle_pass_leave() { + + if( false == m_buckle_armed ) { + return; + } + m_buckle_armed = false; + heat_due.push_back( this ); +} + +void TTrack::buckle_under_train() { + + if( is_buckled() ) { + return; + } + // under the rest of the train, which lifts the track between its bogies + auto const rail { rail_temperature_now() }; + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, Segment->GetLength(), outward, radius, + track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + buckle_now( values, std::format( "under a train, rails at {:.0f} C, {:.0f} K above neutral", rail, rail - m_cwr.neutral ) ); +} diff --git a/world/TrackBuckle.h b/world/TrackBuckle.h new file mode 100644 index 000000000..25825ed99 --- /dev/null +++ b/world/TrackBuckle.h @@ -0,0 +1,440 @@ +/* +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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Lateral buckling of continuous welded rail: in the heat the rails, held from growing longer, press on the track along it with +// E*A*alpha*dT, and where the bed holds it too weakly sideways the track jumps out to the side. The track of the scenery takes it as +// a displacement across it (TSegment::stray()), drawn and followed by the axles as the unevenness of TrackUneven.h is. +// Sources: Kish, Samavedam, "Risk analysis based CWR track buckling safety evaluations" (Volpe, about 2001); FRA, "Dynamic buckling +// test analyses of a high degree CWR track"; PKP PLK ST-T1-A8 (2021); the answers of the ministry to interpellations 3875 (2026) and +// 2575 (2025). The thresholds and the shape are fitted to the numbers there, see test_track_buckle.cpp. +namespace track_buckle { + +// the shape: a main lobe and a side lobe of the other way on each side of it, as the buckled shapes of Kerr and Kish have it. A +// cosine of a period twice the main lobe under a window cos^2 over three lobes: the side lobes come to a quarter of the main one, and +// the curvature runs on smoothly all along, into the straight track at the ends too, as a bent rail has it +// straight track jumps out far at once, a curve goes out step by step and less far, to the outside of the curve (Kish, Samavedam) +inline constexpr double straight_amplitude { 0.4 }; // m +inline constexpr double straight_length { 14.0 }; // m, main lobe +inline constexpr double curve_amplitude { 0.2 }; // m +inline constexpr double curve_length { 11.0 }; // m +inline constexpr double curve_radius { 1500.0 }; // m, below which a track counts as a curve for the shape +inline constexpr double end_margin { 2.0 }; // m between the buckle and the ends of the track +inline constexpr double most_amplitude { 1.0 }; // m +inline constexpr double least_length { 4.0 }; // m +inline constexpr double most_length { 60.0 }; // m +// how far the side lobes reach from the centre, in lengths of the main lobe +inline constexpr double reach_share { 1.5 }; + +struct shape { + double amplitude { 0.0 }; // of the main lobe, m: positive to the right of the path looking from its start to its end, negative to the left + double length { 0.0 }; // of the main lobe between the points it crosses the line, m; each side lobe is as long + double centre { 0.0 }; // of the main lobe, distance from the start of the path, m +}; + +inline bool active( shape const &Shape ) { + + return Shape.amplitude != 0.0 && Shape.length > 0.0; +} + +// the wave and the window at a distance from the centre, with their derivatives +struct parts { + double wave, wave1, wave2; + double window, window1, window2; +}; + +inline parts parts_at( shape const &Shape, double const Distance ) { + + auto const from { Distance - Shape.centre }; + auto const k { glm::pi() / Shape.length }; + // cos^2(b x) = ( 1 + cos( 2 b x ) ) / 2 reaching 0 at the ends of the side lobes + auto const b { glm::pi() / ( 2.0 * reach_share * Shape.length ) }; + return { + std::cos( k * from ), -k * std::sin( k * from ), -k * k * std::cos( k * from ), + 0.5 * ( 1.0 + std::cos( 2.0 * b * from ) ), -b * std::sin( 2.0 * b * from ), -2.0 * b * b * std::cos( 2.0 * b * from ) }; +} + +inline bool within( shape const &Shape, double const Distance ) { + + return active( Shape ) && std::abs( Distance - Shape.centre ) < reach_share * Shape.length; +} + +// displacement across the path at a distance along it, m +inline double offset( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * p.wave * p.window; +} + +// its first derivative along the path +inline double slope( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave1 * p.window + p.wave * p.window1 ); +} + +// and the second: the curvature the buckle adds to the path, 1/m, positive bending to the right +inline double bend( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave2 * p.window + 2.0 * p.wave1 * p.window1 + p.wave * p.window2 ); +} + +// the mean curvature over a stretch around a distance, as a bogie over its wheelbase feels it: the difference of the slopes at its ends +// over its length +inline double mean_bend( shape const &Shape, double const Distance, double const Base ) { + + if( Base <= 0.0 ) { + return bend( Shape, Distance ); + } + return ( slope( Shape, Distance + 0.5 * Base ) - slope( Shape, Distance - 0.5 * Base ) ) / Base; +} + +// and as a body on two bogies: it goes sideways by the mean of its pivots, so its lateral acceleration is v^2 times the mean of the +// curvatures at the pivots, each over the wheelbase of the bogie (without bogies: the pivots are the axles, with no base) +inline double body_bend( shape const &Shape, double const Distance, double const Pivots, double const Base ) { + + return 0.5 * ( mean_bend( Shape, Distance - 0.5 * Pivots, Base ) + mean_bend( Shape, Distance + 0.5 * Pivots, Base ) ); +} + +// how far from the centre the buckle reaches on each side +inline double reach( shape const &Shape ) { + + return active( Shape ) ? reach_share * Shape.length : 0.0; +} + +// the largest curvature of the buckle, 1/m, in the middle of the main lobe: pi^2 a / L^2 of the wave and 2/9 of it from the window +inline double peak_bend( double const Amplitude, double const Length ) { + + return ( 1.0 + 2.0 / ( 4.0 * reach_share * reach_share ) ) * glm::pi() * glm::pi() * std::abs( Amplitude ) / ( Length * Length ); +} + +// the heat + +inline constexpr double steel_modulus { 210e9 }; // Pa +inline constexpr double steel_expansion { 1.15e-5 }; // 1/K +inline constexpr double sun_heating { 17.0 }; // K a rail in full sun is warmer than the air: 30 F (Kish, Samavedam) +inline constexpr float neutral_default { 26.f }; // C, the rail stress-free temperature PLK lays its tracks at since 2025 +inline constexpr double area_60e1 { 76.70e-4 }; // m2 +inline constexpr double area_49e1 { 62.92e-4 }; +inline constexpr double area_s42 { 54.2e-4 }; + +// the rail section by the name of the rail profile, 60E1 if it tells nothing +inline double rail_area( std::string_view const Profile ) { + + auto const has = [ Profile ]( std::string_view const Part ) { + return std::search( Profile.begin(), Profile.end(), Part.begin(), Part.end(), []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ) != Profile.end(); }; + if( has( "49" ) ) { + return area_49e1; + } + if( has( "s42" ) ) { + return area_s42; + } + return area_60e1; +} + +// the force along a rail held from growing longer, N, pressing for Rise above the neutral temperature +inline double thermal_force( double const Area, double const Rise ) { + + return steel_modulus * Area * steel_expansion * Rise; +} + +// the temperature of a rail, C, from the air, the height of the sun over the horizon in degrees and the clouds (0 clear, 1 overcast; +// above 1 it rains, which cools as much) +inline double rail_temperature( double const Air, double const Sun, double const Overcast ) { + + auto const sun { std::max( 0.0, std::sin( glm::radians( Sun ) ) ) }; + return Air + sun_heating * sun * ( 1.0 - std::clamp( Overcast, 0.0, 1.0 ) ); +} + +// the state of the track, from the scenery +namespace grade { +inline constexpr int good { 0 }; // concrete sleepers, full ballast shoulder, consolidated +inline constexpr int average { 1 }; +inline constexpr int weak { 2 }; // timber sleepers, ballast missing, or the bed disturbed by tamping or sleeper renewal not yet consolidated +} + +struct cwr { + float neutral { neutral_default }; // C + int grade { grade::average }; + bool worked { false }; // works on the bed lately: weak whatever the grade +}; + +// the rise above the neutral temperature at which the track buckles: from low on under a passing train, which lifts it between the +// bogies and takes away part of its hold sideways, at high and above by itself +struct limits { + double low { 0.0 }; // K + double high { 0.0 }; +}; + +inline constexpr std::array grade_limits { { { 40.0, 55.0 }, { 32.0, 45.0 }, { 22.0, 32.0 } } }; + +// for the grade of the track, lowered in a curve, which presses outwards, and by an uneven line, which gives it a start +inline limits limits_of( cwr const &Track, double const Radius, double const Side ) { + + auto const kind { Track.worked ? grade::weak : std::clamp( Track.grade, grade::good, grade::weak ) }; + auto result { grade_limits[ kind ] }; + auto less { 0.0 }; + auto const radius { std::abs( Radius ) }; + if( radius > 0.0 && radius < 300.0 ) { + less += 6.0; + } + else if( radius > 0.0 && radius < 600.0 ) { + less += 3.0; + } + if( Side > 15.0 ) { + less += 3.0; + } + result.low -= less; + result.high -= less; + return result; +} + +// the share of the passes of a train which buckle the track at the rise: none below low, all at high +inline double chance( double const Rise, limits const &Limits ) { + + if( Limits.high <= Limits.low ) { + return Rise >= Limits.high ? 1.0 : 0.0; + } + return std::clamp( ( Rise - Limits.low ) / ( Limits.high - Limits.low ), 0.0, 1.0 ); +} + +enum class verdict { + none, + under_train, + by_itself +}; + +// with Train the track has a train going over it hard enough, Draw is the draw of the pass, 0 to 1 +inline verdict decide( double const Rise, limits const &Limits, bool const Train, double const Draw ) { + + if( Rise >= Limits.high ) { + return verdict::by_itself; + } + if( Train && Rise >= Limits.low && Draw < chance( Rise, Limits ) ) { + return verdict::under_train; + } + return verdict::none; +} + +// a train stirs the track up when it goes fast or brakes on it +inline constexpr double stirring_speed { 40.0 }; // km/h +inline bool stirs( double const Speed, bool const Braking ) { + + return Speed > stirring_speed || ( Braking && Speed > 5.0 ); +} + +// draws, the same for the same track and seed + +// FNV-1a, which std::hash isn't on every compiler +inline std::uint64_t name_hash( std::string_view const Name ) { + + std::uint64_t hash { 14695981039346656037ULL }; + for( auto const character : Name ) { + hash ^= static_cast( character ); + hash *= 1099511628211ULL; + } + return hash; +} + +// the splitmix64 finalizer, so close numbers give far apart draws +inline std::uint64_t scramble( std::uint64_t Value ) { + + Value += 0x9e3779b97f4a7c15ULL; + Value = ( Value ^ ( Value >> 30 ) ) * 0xbf58476d1ce4e5b9ULL; + Value = ( Value ^ ( Value >> 27 ) ) * 0x94d049bb133111ebULL; + return Value ^ ( Value >> 31 ); +} + +// what a draw is for, so the draws for one track don't go together +enum purpose : std::uint64_t { + pass = 1, + site = 2, + place = 3, + way = 4 +}; + +// a fraction 0 to 1 +inline double draw( std::uint64_t const Name, std::uint32_t const Seed, std::uint64_t const Purpose, std::uint64_t const Number = 0 ) { + + auto const value { scramble( scramble( scramble( Name ^ Purpose ) + Seed ) + Number ) }; + // the 53 high bits + return static_cast( value >> 11 ) / 9007199254740992.0; +} + +// where the track buckles by the temperature on its own: one place in so many metres of track, and the tracks worked on lately. +// Elsewhere the bed holds far beyond the limits of the grade (Sweden: 200 buckles in the hot summer of 2018 on 14 000 km) +inline constexpr double site_spacing { 10000.0 }; // m + +inline bool weak_spot( std::uint64_t const Name, std::uint32_t const Seed, double const Length, bool const Worked ) { + + return Worked || draw( Name, Seed, site ) < Length / site_spacing; +} + +// the entries in the scenery + +// buckle ;;[;] +struct declared { + float amplitude { 0.f }; // mm + float length { -1.f }; // m, negative: by the shape of the track + float centre { -1.f }; // m, negative: drawn + int side { 0 }; +}; + +inline bool given( declared const &Values ) { + + return Values.amplitude > 0.f; +} + +// the numbers of an entry like "400;18;60", NaN where left out +template +std::array read_numbers( std::string_view const Text ) { + + std::array result; + result.fill( std::numeric_limits::quiet_NaN() ); + auto rest { Text }; + for( auto &field : result ) { + auto const end { std::min( rest.find( ';' ), rest.size() ) }; + if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} && std::isfinite( value ) ) { + field = value; + } + if( end == rest.size() ) { + break; + } + rest.remove_prefix( end + 1 ); + } + return result; +} + +inline declared read_buckle( std::string_view const Text ) { + + auto const fields { read_numbers<4>( Text ) }; + declared result; + if( std::isfinite( fields[ 0 ] ) ) { + result.amplitude = std::clamp( fields[ 0 ], 0.f, static_cast( most_amplitude * 1000.0 ) ); + } + if( std::isfinite( fields[ 1 ] ) && fields[ 1 ] > 0.f ) { + result.length = std::clamp( fields[ 1 ], static_cast( least_length ), static_cast( most_length ) ); + } + if( std::isfinite( fields[ 2 ] ) && fields[ 2 ] >= 0.f ) { + result.centre = fields[ 2 ]; + } + if( std::isfinite( fields[ 3 ] ) ) { + result.side = ( fields[ 3 ] > 0.f ? 1 : fields[ 3 ] < 0.f ? -1 : 0 ); + } + return result; +} + +inline std::string write_buckle( declared const &Values ) { + + if( false == given( Values ) ) { + return {}; + } + std::ostringstream text; + text << "buckle " << Values.amplitude << ';'; + if( Values.length > 0.f ) { + text << Values.length; + } + text << ';'; + if( Values.centre >= 0.f ) { + text << Values.centre; + } + if( Values.side != 0 ) { + text << ';' << Values.side; + } + text << ' '; + return text.str(); +} + +// cwr ;[;] +inline cwr read_cwr( std::string_view const Text ) { + + auto const fields { read_numbers<3>( Text ) }; + cwr result; + if( std::isfinite( fields[ 0 ] ) ) { + result.neutral = std::clamp( fields[ 0 ], -20.f, 60.f ); + } + if( std::isfinite( fields[ 1 ] ) ) { + result.grade = std::clamp( static_cast( std::lround( fields[ 1 ] ) ), 0, 2 ); + } + if( std::isfinite( fields[ 2 ] ) ) { + result.worked = fields[ 2 ] > 0.f; + } + return result; +} + +inline std::string write_cwr( cwr const &Values ) { + + if( Values.neutral == neutral_default && Values.grade == grade::average && false == Values.worked ) { + return {}; + } + std::ostringstream text; + text << "cwr " << Values.neutral << ';' << Values.grade; + if( Values.worked ) { + text << ";1"; + } + text << ' '; + return text.str(); +} + +// the buckle of the values on a track of the length, which curves to the side Outward (-1 left, 1 right, 0 straight), with radius +// Radius (0 straight); None for one which doesn't fit into the track. Place and Way are draws for the centre and the side not given +inline shape resolve( declared const &Values, double const Length, int const Outward, double const Radius, double const Place, double const Way ) { + + if( false == given( Values ) ) { + return {}; + } + auto const curve { Outward != 0 && Radius > 0.0 && Radius < curve_radius }; + shape result; + result.length = Values.length > 0.f ? static_cast( Values.length ) : ( curve ? curve_length : straight_length ); + auto const first { reach_share * result.length + end_margin }; + auto const last { Length - reach_share * result.length - end_margin }; + if( last < first ) { + return {}; + } + result.centre = Values.centre >= 0.f ? std::clamp( static_cast( Values.centre ), first, last ) : first + ( last - first ) * Place; + auto const side { Values.side != 0 ? Values.side : Outward != 0 ? Outward : ( Way < 0.5 ? -1 : 1 ) }; + result.amplitude = side * 0.001 * Values.amplitude; + return result; +} + +// the buckle the temperature makes on a track: as large as a curve or a straight one makes +inline declared natural( bool const Curve ) { + + declared result; + result.amplitude = static_cast( 1000.0 * ( Curve ? curve_amplitude : straight_amplitude ) ); + result.length = static_cast( Curve ? curve_length : straight_length ); + return result; +} + +} // namespace track_buckle