diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d5847cbc1..a5ff758a5 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2594,6 +2594,12 @@ class TMoverParameters // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the // forces of the vehicles coupled to it acting on it) derailment::outcome Derailed{derailment::outcome::none}; + // what derailed the vehicle, by any model, and its speed then [km/h], for what the scenery and the test mode are + // told (TDynamicObject::new_derailment()); none on the rails, and other when only the flag of the damage was set + derailment::reason DerailedBy{derailment::reason::none}; + double DerailVelocity{0.0}; + // the vehicle derails now, by the Reason, at the speed it has + void note_derailment(derailment::reason Reason); // physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h): // what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a // buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1 diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 7ee85203a..a48b05366 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1626,6 +1626,7 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin DerailAcceleration = 0.0; DerailSide = 0; CollisionDerail = Reason; + note_derailment(Reason == COLLISION_OVERRIDE ? derailment::reason::overriding : derailment::reason::pushed_off); EventFlag = true; MainSwitch(false, range_t::local); if (Vel < 5.0) @@ -2100,6 +2101,10 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve } Derailed = Verdict.result; DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // a buckle under it is what derailed it, whichever way it went + note_derailment(Track.buckle_curvature != 0.0 ? derailment::reason::buckle : + Verdict.result == derailment::outcome::overturned ? derailment::reason::overturned : + derailment::reason::flange_climb); // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; DerailSide = 0; @@ -2119,6 +2124,8 @@ void TMoverParameters::rerail() { ClearFlag(DamageFlag, dtrain_out); Derailed = derailment::outcome::none; + DerailedBy = derailment::reason::none; + DerailVelocity = 0.0; // and back on the track; what derailed it before has no say in how it leaves the track the next time OffTrack.reset(); DerailCause = derail_motion::cause::off_rails; @@ -2161,6 +2168,13 @@ void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) { + note_derailment(Reason == END_OF_TRACK ? derailment::reason::end_of_track : + Reason == TOO_HIGH_SPEED ? derailment::reason::overspeed : + Reason == GAUGE_MISMATCH ? derailment::reason::track_gauge : + Reason == WRONG_TRACK_TYPE ? derailment::reason::track_type : + Reason == COLLISION ? derailment::reason::collision : + Reason == TRAILED_SWITCH ? derailment::reason::trailed_switch : + derailment::reason::other); EventFlag = true; MainSwitch(false, range_t::local); @@ -2208,6 +2222,12 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +void TMoverParameters::note_derailment(derailment::reason const Reason) +{ + DerailedBy = Reason; + DerailVelocity = std::abs(V) * 3.6; +} + bool TMoverParameters::leaves_track() const { return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && @@ -2225,6 +2245,7 @@ void TMoverParameters::pull_off(int const Side, double const Acceleration, std:: DerailCause = derail_motion::cause::pulled_off; DerailAcceleration = Acceleration; DerailSide = Side; + note_derailment(derailment::reason::pulled_off); EventFlag = true; MainSwitch(false, range_t::local); tear_brake_hoses(*this); diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index e9cfa452e..5f7e346a8 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -282,4 +282,33 @@ std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_s Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); } +std::string_view reason_name(reason const Reason) { + switch (Reason) { + case reason::none: return "none"; + case reason::flange_climb: return "flange_climb"; + case reason::overturned: return "overturned"; + case reason::end_of_track: return "end_of_track"; + case reason::pulled_off: return "pulled_off"; + case reason::collision: return "collision"; + case reason::buckle: return "buckle"; + case reason::overriding: return "overriding"; + case reason::pushed_off: return "pushed_off"; + case reason::overspeed: return "overspeed"; + case reason::track_gauge: return "track_gauge"; + case reason::track_type: return "track_type"; + case reason::trailed_switch: return "trailed_switch"; + case reason::other: return "other"; + } + return "other"; +} + +std::string cell_text(notice const &Notice) { + return std::format("{} {} {}", Notice.vehicle, reason_name(Notice.why), Notice.track.empty() ? std::string_view{"none"} : std::string_view{Notice.track}); +} + +std::string describe(notice const &Notice) { + return std::format("{} derailed ({}) {} at {:.0f} km/h", Notice.vehicle, reason_name(Notice.why), + Notice.track.empty() ? std::string{"on a track without a name"} : "on track " + Notice.track, std::abs(Notice.velocity)); +} + } // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 50a3d84cb..720b7ea88 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include #include @@ -226,4 +227,41 @@ std::optional climbing_speed(vehicle_state const &Vehicle, track_state c // track damage ..., cross level ... mm)" std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, std::string_view TrackName); +// ---- what the scenery and the test mode are told + +// what put a vehicle off the rails, by any model of the derailment (physics.derailment new, monitor or old) and of the +// collisions. the codes are public: the memory cell __simulation.derailment holds them in its value 2, and the black +// box in its derailment records (blackbox_doc.md); 1 to 5 are the causes of the motion off the track +enum class reason : std::uint8_t { + none = 0, + flange_climb = 1, // the flange climbed the rail (new) + overturned = 2, // it overturned in a curve (new) + end_of_track = 3, // it ran off the end of the track + pulled_off = 4, // the coupling of a vehicle off the track pulled it off (new) + collision = 5, // the legacy derailment in a collision + buckle = 6, // it left the rails on a buckled track (new) + overriding = 7, // it climbed onto the vehicle it hit (physics.collisions new) + pushed_off = 8, // the force pressing its ends pushed it off the track (physics.collisions new) + overspeed = 9, // the legacy draw: too fast in a curve (old, monitor) + track_gauge = 10, // the gauge of the track doesn't fit the vehicle + track_type = 11, // a track of another kind than the vehicle + trailed_switch = 12, // it trailed through a switch with a movable nose set the other way + other = 13 // something else derailed it: a SetDamage command of a scenery +}; +// the name of the cause in the log and the memory cell, e.g. "end_of_track" +std::string_view reason_name(reason Reason); + +// a vehicle derailed: what the scenery (the memory cell and the events of __simulation.derailment) and the test mode +// are told, once each time it leaves the rails +struct notice { + std::string vehicle; // name of the vehicle + reason why{reason::other}; + std::string track; // name of the track it derailed on, empty for a track without one + double velocity{0.0}; // [km/h] as it derailed +}; +// the text of the memory cell __simulation.derailment: " ", "none" for a track without a name +std::string cell_text(notice const &Notice); +// for the log and the verdict of a test: " derailed () on track at km/h" +std::string describe(notice const &Notice); + } // namespace derailment diff --git a/blackbox_doc.md b/blackbox_doc.md index ce2108484..c89823ee0 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -552,15 +552,18 @@ undone in shunting (between the cars of a unit). ### 0x38 derailment -A vehicle off the track, with `physics.derailment new` in `eu07.ini`: it doesn't follow the track any more -and moves on the ground by itself until it stops. Written when it leaves the track, and when it comes to -rest off it, looked at every second. A vehicle put back on the rails and derailed again is written again. +A vehicle derails, with any `physics.derailment` in `eu07.ini`: written as it happens (phase 2), with what +derailed it and the track (one that derailed before the recording started, in the first frame, at the first look). With `physics.derailment new` the vehicle then leaves the track, doesn't follow it +any more and moves on the ground by itself until it stops: written when it leaves the track (phase 0), and +when it comes to rest off it (phase 1), looked at every second. A vehicle put back on the rails and derailed +again is written again. In phase 2 the fields of the motion on the ground are those of the vehicle on the +track: no offset, no roll, nothing travelled. | type | field | |---------|--------------------------------------------------------------------------------| | `f64` | t | | `u32` | number of the vehicle | -| `u8` | 0 it left the track, 1 it came to rest off it | +| `u8` | 0 it left the track, 1 it came to rest off it, 2 it derailed | | `u8` | what derailed it: 1 the flange climbed the rail, 2 it overturned in a curve, 3 the end of the track, 4 a coupling of a vehicle off the track pulled it off, 5 a collision | | `dvec3` | position of the vehicle | | `f32` | heading [rad] of its front, from +z towards +x | @@ -569,6 +572,13 @@ rest off it, looked at every second. A vehicle put back on the rails and deraile | `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | | `f32` | distance [m] it went on the ground since it left the rails | | `u8` | 1 lying on its side, 0 upright | +| `u8` | what derailed it, finer: the code of the cause of the memory cell `__simulation.derailment` (tests/scenarios/README.md): 1 the flange climbed, 2 overturned, 3 the end of the track, 4 pulled off, 5 a collision (the legacy model), 6 a buckle, 7 overriding, 8 pushed off, 9 too fast in a curve (the legacy draw), 10 the gauge, 11 a track of another kind, 12 a trailed switch, 13 something else. In phases 0 and 1 too | +| `str` | name of the track it derailed on, empty for a track without a name | + +The last two came later: a reader of an older file finds the record shorter. The finer cause is 0 when the +simulator didn't know it yet. The cause before them stays one of 1-5, the closest one: a buckle 1 or 2, the +way the vehicle went; overriding and pushing off 5; a trailed switch, the legacy draw in a curve, the gauge, +the kind of track and something else 1. ### 0x3F end diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md index 069bb6e90..9877fb50e 100644 --- a/docs/behaviour-changes.md +++ b/docs/behaviour-changes.md @@ -42,6 +42,13 @@ existing data. - **Test mode** (#266, `--test`; see `tests/scenarios/README.md`): takes no input from outside, does not read the player's own eu07.ini, writes only its verdict to the standard output, and has exit codes of its own (kept clear of 1 and 3). +- **A derailment is logged in one line of its own** (derailment event PR): `derailment: derailed () on + track at km/h`, once each time a vehicle leaves the rails, with any `physics.derailment`, next to the + `Bad driving` lines that were there before. The black box writes it too, as a derailment record (0x38) with phase 2, + and every derailment record gets the finer cause and the track name at its end (see `blackbox_doc.md`). Notices: log + checks that count lines with "derailed"; readers of the black box that took every 0x38 record for one off the track. + The settings dump at the start of log.txt has `test.fail_on_derailment` (default `no`); with `yes` a derailment of + a tested train ends a test run with the new exit code 15. Needs: nothing. ## AI @@ -114,6 +121,10 @@ existing data. - **New putvalues commands** for sceneries: `Crew: ` puts an AI driver in a vehicle or takes it off (#422); `SignalAreaEnd` (#305, above); the parameter `H` after the coupling of a vehicle prepares it for hauling dead in a train, the "pullee mode" (#419). +- **A scenery can react to a derailment** (derailment event PR, optional): when it declares the memory cell + `__simulation.derailment`, the simulator writes the vehicle, the cause, the track, the speed and the code of the + cause into it on each derailment, then runs the event `__simulation.derailment` and the event `:derailed` + when the scenery has them. Nothing is made or run for a scenery without them. See `tests/scenarios/README.md`. ## Data keys that need new data diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e4161ce61..307b9001a 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "input/command.h" +#include "McZapkie/derailment.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" @@ -575,14 +576,66 @@ std::uint8_t cause_of(derail_motion::cause const Cause) { } } +// the cause of the motion off the track closest to what derailed the vehicle: a buckle as the vehicle went +std::uint8_t cause_of(derailment::reason const Reason, derailment::outcome const Outcome) { + switch (Reason) { + case derailment::reason::overturned: + return blackbox::derailment_causes::overturned; + case derailment::reason::buckle: + return Outcome == derailment::outcome::overturned ? blackbox::derailment_causes::overturned : blackbox::derailment_causes::flange_climbed; + case derailment::reason::end_of_track: + return blackbox::derailment_causes::end_of_track; + case derailment::reason::pulled_off: + return blackbox::derailment_causes::pulled_off; + case derailment::reason::collision: + case derailment::reason::overriding: + case derailment::reason::pushed_off: + return blackbox::derailment_causes::collision; + default: + return blackbox::derailment_causes::flange_climbed; + } +} + } // namespace +void blackbox_recorder::derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice) { + std::scoped_lock lock{m_mutex}; + // before the recording starts (a vehicle derailing in the first frame) the first look writes it + if (m_writer == nullptr || Vehicle == nullptr) + return; + write_derailed(Vehicle, Notice); +} + +void blackbox_recorder::write_derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice) { + auto &entry{m_vehicles[Vehicle]}; + if (entry.derailed) + return; + entry.derailed = true; + blackbox::derailment_state state; + state.time = m_time; + state.vehicle = vehicle_id(Vehicle); + state.phase = blackbox::derailment_phases::derailed; + state.cause = cause_of(Notice.why, Vehicle->MoverParameters->Derailed); + state.position = Vehicle->GetPosition(); + state.heading = static_cast(std::atan2(Vehicle->VectorFront().x, Vehicle->VectorFront().z)); + // as it derailed, along its front as it moves now + state.speed_kmh = static_cast(std::copysign(Notice.velocity, Vehicle->MoverParameters->V)); + state.reason = static_cast(Notice.why); + state.track = text_of(Notice.track); + m_writer->derailment(state); +} + void blackbox_recorder::look_at_derailments() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) continue; auto const &motion{vehicle->MoverParameters->OffTrack}; auto const id{vehicle_id(vehicle)}; + // the derailment itself first, if it came before the recording did; forgotten once back on the rails + if (auto const *notice{vehicle->derailment_notice()}) + write_derailed(vehicle, *notice); + else + m_vehicles[vehicle].derailed = false; auto &entry{m_vehicles[vehicle]}; if (false == motion.active()) { entry.derailment = 0; @@ -602,6 +655,10 @@ void blackbox_recorder::look_at_derailments() { state.roll = static_cast(motion.roll()); state.travelled = static_cast(motion.travelled()); state.lying = motion.lying(); + if (auto const *notice{vehicle->derailment_notice()}) { + state.reason = static_cast(notice->why); + state.track = text_of(notice->track); + } // seen first at rest, it left the track before for (auto written = entry.derailment + 1; written <= phase; ++written) { state.phase = (written == 1 ? blackbox::derailment_phases::left_track : blackbox::derailment_phases::at_rest); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index cdc61da61..568f1671d 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -24,6 +24,9 @@ http://mozilla.org/MPL/2.0/. #include class TDynamicObject; +namespace derailment { +struct notice; +} class TTrack; class TMemCell; class basic_event; @@ -49,6 +52,8 @@ public: // Event: the one telling the aspect of the signal void signal_passed(TDynamicObject const *Vehicle, basic_event const &Event, double Speed1, double Speed2, double Trainspeed, double Overrun, std::uint8_t Flags); void vehicle_removed(TDynamicObject const *Vehicle); + // the vehicle derailed, by any model: the derailment record as it happens + void derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice); // a train at a station of its timetable; the time and the vehicle are filled in here void station(TDynamicObject const *Vehicle, blackbox::station_event Station); // a train told to sound the horn (W6), at Position @@ -71,6 +76,8 @@ private: bool couplers_known{false}; // off the track: 0 not, 1 written as leaving it, 2 written as at rest int derailment{0}; + // its derailment written (phase 2), while it's off the rails + bool derailed{false}; }; struct switch_entry { TTrack *track{nullptr}; @@ -103,6 +110,8 @@ private: void look_at_couplers(); // the vehicles leaving the track and coming to rest off it (physics.derailment new) void look_at_derailments(); + // the derailment record of the vehicle as it derailed (phase 2), once + void write_derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice); void write_camera(); // the timetable of the train the user is in, written again when it is another one; none isn't written void look_at_timetable(TDynamicObject const &Vehicle, std::uint32_t Id); diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 2eb0a3c89..770a3553a 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -127,6 +127,28 @@ state_manager::init_scripting_interface() { simulation::test().init_result_cell(); } +void +state_manager::report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice ) { + + WriteLog( "derailment: " + derailment::describe( Notice ) ); + auto const name { std::string( derailment_name ) }; + if( auto *cell { Memory.find( name ) } ) { + cell->UpdateValues( + derailment::cell_text( Notice ), + Notice.velocity, + static_cast( static_cast( Notice.why ) ), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2 ); + } + if( auto *event { Events.FindEvent( name ) } ) { + Events.AddToQuery( event, &Vehicle ); + } + if( auto *event { Events.FindEvent( Vehicle.name() + ":derailed" ) } ) { + Events.AddToQuery( event, &Vehicle ); + } + Blackbox.derailed( &Vehicle, Notice ); + test().vehicle_derailed( Vehicle, Notice ); +} + // legacy method, calculates changes in simulation state over specified time void state_manager::update( double const Deltatime, int Iterationcount ) { diff --git a/simulation/simulation.h b/simulation/simulation.h index 02bef0ffd..9bf9cd057 100644 --- a/simulation/simulation.h +++ b/simulation/simulation.h @@ -72,6 +72,15 @@ public: // stores class data in specified file, in legacy (text) format void export_as_text( std::string const &Scenariofile ) const; + // the vehicle derailed: the log, the black box, the test mode, and the scenery which asked for it. the scenery's + // memory cell __simulation.derailment gets the notice (derailment::cell_text(), value 1 the speed [km/h], value 2 + // the code of the cause), then its events __simulation.derailment and :derailed run, the vehicle their + // activator. a scenery declares those it wants: nothing is made at the start, where a node made would take a + // draw of the random numbers and change every run + void + 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" }; private: // members diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index f6e2a4a39..276596bbc 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtest.h" #include "application/application.h" +#include "McZapkie/derailment.h" #include "scene/scene.h" #include "simulation/simulation.h" #include "utilities/Globals.h" @@ -49,6 +50,16 @@ double elapsed_wall_time() namespace simulation { +namespace { + +// the limits of the settings, as they are now: the scenery may change them +test_limits current_limits() +{ + return test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass, Global.test.fail_on_derailment }; +} + +} // namespace + test_manager &test() { static test_manager instance; @@ -141,11 +152,12 @@ void test_manager::start() tested += " " + name; } auto const walllimit { m_walllimit.load() }; - WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}", tested, Global.test.timeout, + WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}{}", tested, Global.test.timeout, walllimit > 0.0 ? std::format("{:.0f} s", walllimit) : std::string("none"), Global.test.standstill, Global.test.pass_on_standstill ? ", standstill passes" : "", Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed", - Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop")); + Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop", + Global.test.fail_on_derailment ? ", a derailment fails" : "")); } void test_manager::update(double const Deltatime) @@ -160,7 +172,7 @@ void test_manager::update(double const Deltatime) frame.reason = cell->Text(); } - auto const limits { test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass } }; + auto const limits { current_limits() }; std::optional verdict; auto passrequested { false }; { @@ -192,6 +204,38 @@ bool test_manager::tested_trains_at_rest() const }); } +bool test_manager::tested(TDynamicObject const &Vehicle) const +{ + if (Global.test.vehicles.empty()) + return true; + return std::ranges::any_of(Global.test.vehicles, [&Vehicle](std::string const &Name) { + auto *vehicle { simulation::Vehicles.find(Name) }; + return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, [&Vehicle](TDynamicObject const *Other) { return Other == &Vehicle; }) != nullptr; + }); +} + +void test_manager::vehicle_derailed(TDynamicObject const &Vehicle, derailment::notice const &Notice) +{ + if (false == Global.test.enabled || false == m_started || m_finished) + return; + auto const istested { tested(Vehicle) }; + auto const description { derailment::describe(Notice) }; + std::optional verdict; + double time { 0.0 }; + { + std::scoped_lock lock { m_lock }; + verdict = evaluate_derailment(m_progress, istested, description, current_limits()); + time = m_progress.time; + } + if (verdict.has_value()) + { + finish(verdict->result, verdict->reason); + return; + } + if (istested) + WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_on_derailment", description, time)); +} + void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal) { auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) }; @@ -222,7 +266,8 @@ bool test_manager::conclude(test_result const Result, std::string_view const Rea m_result = Result; m_finished = true; - auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, Reason) }; + auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, + verdict_reason(test_verdict { Result, std::string(Reason) }, m_progress)) }; if (Result == test_result::pass) WriteLog(line); else diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h index 784cd39e8..cf03d1287 100644 --- a/simulation/simulationtest.h +++ b/simulation/simulationtest.h @@ -11,6 +11,11 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtestrules.h" +class TDynamicObject; +namespace derailment { +struct notice; +} + #include #include #include @@ -36,6 +41,8 @@ public: void update(double Deltatime); // reported by a driver whose train went past a signal showing stop void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal); + // the vehicle derailed: a vehicle of the tested trains ends the test with test.fail_on_derailment + void vehicle_derailed(TDynamicObject const &Vehicle, derailment::notice const &Notice); // ends the test with given result and closes the application; the first call wins void finish(test_result Result, std::string_view Reason); // ends the test with given result, without closing the application: for the ways out that close it anyway @@ -54,6 +61,8 @@ private: void check_wall_clock(double Elapsed); // every vehicle of the tested trains stands: the consists of test.vehicle, or every vehicle without it bool tested_trains_at_rest() const; + // the vehicle is one of the tested trains: in a consist of test.vehicle as it is now, any vehicle without it + bool tested(TDynamicObject const &Vehicle) const; // the watchdog may end the test from its own thread mutable std::mutex m_lock; diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp index fcedaed7d..6635d0808 100644 --- a/simulation/simulationtestrules.cpp +++ b/simulation/simulationtestrules.cpp @@ -58,6 +58,7 @@ std::string_view to_string(test_result const Result) case timeout: return "timeout"; case standstill: return "standstill"; case error: return "error"; + case derailment: return "derailment"; } return "unknown"; } @@ -159,4 +160,23 @@ std::optional evaluate_frame(test_progress &Progress, test_frame c return std::nullopt; } +std::optional evaluate_derailment(test_progress &Progress, bool const Tested, std::string_view const Description, test_limits const &Limits) +{ + if (false == Tested) + return std::nullopt; + if (Limits.fail_on_derailment) + return test_verdict{test_result::derailment, std::string(Description)}; + if (Progress.derailments++ == 0) + Progress.firstderailment = Description; + return std::nullopt; +} + +std::string verdict_reason(test_verdict const &Verdict, test_progress const &Progress) +{ + if (Verdict.result == test_result::derailment || Progress.derailments <= 0) + return Verdict.reason; + return std::format("{} [derailed: {}{}]", Verdict.reason, Progress.firstderailment, + Progress.derailments > 1 ? std::format(", and {} more", Progress.derailments - 1) : std::string()); +} + } // namespace simulation diff --git a/simulation/simulationtestrules.h b/simulation/simulationtestrules.h index 684b90cde..469eae29e 100644 --- a/simulation/simulationtestrules.h +++ b/simulation/simulationtestrules.h @@ -29,6 +29,7 @@ enum class test_result : int { timeout = 12, // test.timeout seconds of simulation time, or test.wall_timeout seconds of real time went by standstill = 13, // the tested trains stood still for test.standstill seconds without a result error = 14, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw + derailment = 15, // a vehicle of the tested trains derailed, with test.fail_on_derailment }; std::string_view to_string(test_result Result); @@ -72,6 +73,7 @@ struct test_limits { double standstill{300.0}; // [s] of the tested trains standing without a result; 0 = never bool pass_on_standstill{false}; bool no_movement_before_pass{true}; + bool fail_on_derailment{false}; }; // what a frame of the simulation brought @@ -87,6 +89,8 @@ struct test_progress { double time{0.0}; // simulation time since the start [s] double resttime{0.0}; // how long the tested trains have been standing [s] bool passrequested{false}; // __test.result was set to 1, the pass waits for the tested trains to stop + int derailments{0}; // of the vehicles of the tested trains, the test going on + std::string firstderailment; // the first of them, as derailment::describe() tells it }; // how long the tested trains have to stand before a requested pass is granted [s] @@ -95,4 +99,13 @@ inline constexpr double pass_settle_time{1.0}; // checks the end conditions after a frame and moves the progress on. returns the verdict once the test is over std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits); +// a vehicle derailed, as Description tells it (" derailed () on track at km/h"). one of +// the tested trains (Tested) ends the test with test.fail_on_derailment; without it the test goes on, and the +// derailment is kept for the verdict. another train doesn't count +std::optional evaluate_derailment(test_progress &Progress, bool Tested, std::string_view Description, test_limits const &Limits); + +// the reason the verdict line gives: that of the verdict, and when the test went on after a tested train derailed +// " [derailed: ]" (", and N more" inside the brackets for more of them) at its end +std::string verdict_reason(test_verdict const &Verdict, test_progress const &Progress); + } // namespace simulation diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 529fefea6..757757659 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -77,6 +77,7 @@ The test ends with the first of these: | 12 | timeout | `test.timeout` seconds of simulation time went by (default 3600), or `test.wall_timeout` seconds of real time since the start (see below) | | 13 | standstill | the tested trains stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits | | 14 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw | +| 15 | derailment | a vehicle of the tested trains derailed, with `test.fail_on_derailment yes` (default `no`); ends at once. The reason tells the vehicle, the cause, the track and the speed: `autotest_x derailed (buckle) on track tdo_n222 at 46 km/h` | A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819). The codes of the test mode keep clear of the ones a process gets when it goes wrong on its own: 1 @@ -93,6 +94,7 @@ test.standstill 120 test.pass_on_standstill no test.fail_if_stop_overran yes test.no_movement_before_pass yes +test.fail_on_derailment no test.vehicle ep07-424 endconfig ``` @@ -105,6 +107,7 @@ endconfig | `test.pass_on_standstill` | no | the standstill end passes the test instead | | `test.fail_if_stop_overran` | yes | a signal passed at danger ends the test; with `no` it's only logged | | `test.no_movement_before_pass` | yes | a pass waits until the tested trains stand still; with `no` it ends the test at once | +| `test.fail_on_derailment` | no | a derailment of a vehicle of the tested trains ends the test with `derailment` (15). With `no` it's only logged (`test: ... derailed ..., allowed by test.fail_on_derailment`), and the verdict of the run, whatever it is, ends with ` [derailed: ]` (and how many more). Off by default: the cases that derail on purpose check what the derailed vehicles did afterwards | | `test.vehicle` | none | a vehicle of a train under test, by its name in the scenery (once for each train under test). The tested trains are the consists of these vehicles as they are at the moment (a train the tested one couples to joins it), and only they count for the pass and the standstill: other trains, AI traffic, may run on. A name the scenery doesn't have ends the test with `error`. Not given, every vehicle of the scenery counts. A signal passed at danger counts for every train either way | `--test-timeout` and `--test-wall-timeout` on the command line win over `test.timeout` and @@ -118,6 +121,47 @@ fast as real time is never cut short by it. With `test.timeout 0` there is no wa `test.wall_timeout` is given; `test.wall_timeout 0` turns it off. A test that has ended but whose simulator doesn't close is ended by the watchdog too, with its own result. +### A derailment, for the scenery + +Every derailment, whatever the model (`physics.derailment new`: overturning, the flange climbing the rail, a buckle, +a coupling pulling a vehicle off, the end of the track, a collision; `old` and `monitor`: the legacy draw in a curve, +the end of the track, the gauge, a collision, a trailed switch with a movable nose), goes to the log as +`derailment: derailed () on track at km/h`, once for each time a vehicle leaves the +rails, and to the black box (record 0x38, phase 2, see `blackbox_doc.md`). A scenery that wants to react declares what +it needs, nothing is made for it otherwise: + +``` +node -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell +event __simulation.derailment multiple 0 none stop_the_line endevent +event ep07-424:derailed UpdateValues 0 __test.result derailed 0 * endevent +``` + +- the memory cell `__simulation.derailment` gets, before the events run: the text ` ` + (`none` for a track without a name), value 1 the speed [km/h] as it derailed (in a collision: after the hit), value 2 the code of the cause. + A `memcompare` can test the vehicle by the start of the text (`ep07-424*`) and the cause by value 2; +- the event `__simulation.derailment` runs for a derailment of any vehicle, `:derailed` for that vehicle + (like `:busy`); the vehicle is their activator (`whois`). Two vehicles derailing in the same frame run + the first one once, the cell holds the second. + +| code | cause | | +| --- | --- | --- | +| 1 | `flange_climb` | the flange climbed the rail (`new`) | +| 2 | `overturned` | it overturned in a curve (`new`) | +| 3 | `end_of_track` | it ran off the end of the track | +| 4 | `pulled_off` | the coupling of a vehicle off the track pulled it off (`new`) | +| 5 | `collision` | the legacy derailment in a collision | +| 6 | `buckle` | it left the rails on a buckled track (`new`) | +| 7 | `overriding` | it climbed onto the vehicle it hit (`physics.collisions new`) | +| 8 | `pushed_off` | the force pressing its ends pushed it off the track (`physics.collisions new`) | +| 9 | `overspeed` | the legacy draw: too fast in a curve (`old`, `monitor`) | +| 10 | `track_gauge` | the gauge of the track doesn't fit | +| 11 | `track_type` | a track of another kind (a road vehicle on rails, say) | +| 12 | `trailed_switch` | it trailed through a switch with a movable nose set the other way | +| 13 | `other` | something else set the derailment (a `SetDamage` command) | + +The memory cell isn't made by the simulator because a node made at the start would take the random numbers of the +scene and change every run of a scenery. `eu07_td_off_track_end_scenery_told` is an example. + A signal is passed at danger when the head of a train goes past a signal which its driver has in its speed table, showing stop. So it's the driver's view that counts: a train without a driver isn't watched, and neither is a signal the driver never scanned (a train placed at @@ -240,7 +284,7 @@ to `logs/`. | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | | `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model. An optional `"fiz_from": "/"` copies that file instead of the vehicle's own `.fiz`, named in full, e.g. `pkp/e6act_v2/e6acta.fiz.inc` for a vehicle whose `.fiz` only includes it (`e6actad.fiz`); the `.mmd` still comes from `from`. Keys for a section of the included file can't go after the include on a line of their own: a second `Power:` line loads the power source anew | -| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | +| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill`, `error` or `derailment`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | | `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) | @@ -395,6 +439,12 @@ on level ground, on an embankment 4 m high and in a cutting, made of triangle st centre (-600, 400), the cross section swept along it every 0.03 rad; the banks of the cutting rise 4 m at 1:1.5, then on at 1:5). +`eu07_td_off_track_end_scenery_told` is `eu07_td_off_track_end` with the memory cell and the events of a derailment +declared in `vars.track_nodes` (see *A derailment, for the scenery*): the event `:derailed` of the locomotive +checks the cell and marks a cell of the case, which the log shows. `eu07_td_buckle_derails_ends_test` is `eu07_td_buckle_derails` with +`test.fail_on_derailment yes`: the derailment of the EU07 under test ends the run with `derailment`. The runner's +summary tells the derailment of the train under test after the case, from the verdict line. + `eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake (`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps diff --git a/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json b/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json new file mode 100644 index 000000000..f0eb5fd46 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json @@ -0,0 +1,38 @@ +{ + "description": "eu07_td_buckle_derails with test.fail_on_derailment yes: the EU07 under test leaves the rails on the buckled curve tdo_n222 at the 46 km/h it has there, and the derailment ends the test at once with its own result (exit code 15) instead of the timeout, the verdict telling the vehicle, the cause (buckle), the track and the speed.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "600 8" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new" + ], + "test_config": [ + "test.fail_on_derailment yes" + ], + "expect": "derailment", + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" + }, + { + "type": "log_contains", + "pattern": "test: derailment \\(exit code 15\\) after [0-9.]+ s of simulation time: autotest_\\S+ derailed \\(buckle\\) on track tdo_n222 at [0-9]+ km/h" + }, + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "distance", + "max": 1100 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json new file mode 100644 index 000000000..58e804567 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json @@ -0,0 +1,55 @@ +{ + "description": "The scenery is told of a derailment: eu07_td_off_track_end (an EU07 with three coaches and no driver runs off the end of autotest_stub at 60 km/h) with the memory cell __simulation.derailment, the event of the same name (logvalues of the cell) and the event :derailed of the locomotive declared in the fragment. The cell holds the vehicle, the cause, the track and the speed and the code of the cause when the events run; the event of the locomotive checks the cell (its name, end of track: code 3) and marks a cell of the case. test.fail_on_derailment yes doesn't end the test: the derailed train isn't the one under test (the EU07 standing on track 1), so the run ends on the timeout as eu07_td_off_track_end does.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "autotest_stub", + "offset": "100", + "velocity": "60", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack\nnode -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell\nnode -1 0 autotest_seen memcell 0 0 0 none 0 0 none endmemcell\nevent __simulation.derailment logvalues 0 __simulation.derailment endevent\nevent {{vehicle}}_off:derailed multiple 0 __simulation.derailment autotest_derail_seen autotest_derail_log condition memcompare {{vehicle}}_off* * 3 endevent\nevent autotest_derail_seen UpdateValues 0 autotest_seen end_of_track_seen 1 * endevent\nevent autotest_derail_log logvalues 0 autotest_seen endevent", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "test_config": [ + "test.fail_on_derailment yes" + ], + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off derailed \\(end_of_track\\) on track autotest_stub at [0-9]+ km/h" + }, + { + "type": "log_contains", + "pattern": "Memcell __simulation\\.derailment: \\[autotest_\\S+_off end_of_track autotest_stub\\] \\[(59|60)\\.[0-9]+\\] \\[3\\.00\\]" + }, + { + "type": "log_contains", + "pattern": "Memcell autotest_seen: \\[end_of_track_seen\\] \\[1\\.00\\]" + }, + { + "type": "log_lacks", + "pattern": "test: derailment" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "end of track", + "max_offset": 0.5, + "min_distance": 5, + "max_distance": 60, + "lying": false + } + ] +} diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index ad7ac5bcb..ecbafff5e 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -12,7 +12,8 @@ mode should end with, and checks on the vehicle's physics log. The runner: that turns on physicslog, 3. waits until the simulator quits by itself and reads the test result from its exit code: pass, fail, signal passed at danger, timeout (after `duration` seconds of - simulation, if the case gives one), standstill or error, + simulation, if the case gives one), standstill, error or derailment (with + test.fail_on_derailment), 4. compares the result with the one the case expects, evaluates the checks on the physicslog and prints PASS/FAIL per check. @@ -65,6 +66,7 @@ EXIT_RESULTS = { 12: "timeout", 13: "standstill", 14: "error", + 15: "derailment", } # the timeout of the simulator's real time watchdog (test.wall_timeout) has the timeout code too; told # apart by its verdict, so a run that hung doesn't pass a case that expects the simulation time to run out @@ -311,7 +313,7 @@ BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as point BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed -BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new) +BLACKBOX_DERAILMENT = 0x38 # a vehicle derailed (phase 2), left the track or came to rest off it (physics.derailment new) DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"} COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state @@ -1282,6 +1284,26 @@ def count_lines(path: Path) -> int: return 0 +# the simulator's verdict line: "test: (exit code N) after T s of simulation time: ", the reason +# of a derailment " derailed () on track at km/h"; a run that ended otherwise after a +# train under test derailed has " [derailed: ]" at its end (simulation/simulationtestrules.h) +VERDICT_REASON = re.compile(r"^test: .*? \(exit code \d+\) after [\d.]+ s of simulation time: (.*)$") +VERDICT_DERAILED = re.compile(r" \[derailed: (.*)\]$") + + +def derailment_note(verdict: str, exit_code: int | None) -> str: + """What the summary says of a derailment of a train under test, from the verdict line; empty for none.""" + if EXIT_RESULTS.get(exit_code) == "derailment": + reason = VERDICT_REASON.match(verdict) + return "derailment: " + (reason.group(1) if reason else verdict) + derailed = VERDICT_DERAILED.search(verdict) + return "derailed: " + derailed.group(1) if derailed else "" + + +# notes for the summary of the cases run, by name: a derailment of the train under test +NOTES: dict[str, str] = {} + + def describe_exit(code: int | None) -> str: if code is None: return "none, still running" @@ -1395,6 +1417,9 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float else: if result.verdict: say(f" {result.verdict}") + note = derailment_note(result.verdict, result.exit_code) + if note: + NOTES[name] = note got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None if got == "timeout" and "of real time" in result.verdict: got = WALL_TIMEOUT @@ -1521,7 +1546,7 @@ def main() -> int: print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {results[n]:5} {n}") + print(f" {results[n]:5} {n}" + (f" ({NOTES[n]})" if n in NOTES else "")) # a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1 diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index 77e3e55f4..f952278bf 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -473,6 +473,41 @@ TEST_CASE("blackbox: a vehicle off the track is written field by field") { CHECK(derailment.get() == -1.5f); CHECK(derailment.get() == 87.5f); CHECK(derailment.get() == 1); + // added later, at the end: the finer cause and the track + CHECK(derailment.get() == 0); + CHECK(derailment.text() == ""); + CHECK(derailment.done()); +} + +TEST_CASE("blackbox: a derailment as it happens has the finer cause and the track at the end") { + std::ostringstream file; + blackbox::writer out{file}; + out.header(); + blackbox::derailment_state state; + state.time = 3.0; + state.vehicle = 2; + state.phase = blackbox::derailment_phases::derailed; + state.cause = blackbox::derailment_causes::flange_climbed; + state.speed_kmh = 46.0f; + state.reason = 6; // a buckle + state.track = "tdo_n222"; + out.derailment(state); + auto const all{records(file.str())}; + REQUIRE(all.size() == 1); + reader derailment{all[0].payload}; + CHECK(derailment.get() == 3.0); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 1); + for (int i = 0; i < 3; ++i) + derailment.get(); + derailment.get(); + CHECK(derailment.get() == 46.0f); + for (int i = 0; i < 3; ++i) // offset, roll, travelled + derailment.get(); + CHECK(derailment.get() == 0); // upright + CHECK(derailment.get() == 6); + CHECK(derailment.text() == "tdo_n222"); CHECK(derailment.done()); } diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 3afca6a26..13fac6ea4 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -343,3 +343,44 @@ TEST_CASE("derailment: the report of the log") { verdict.result = dr::outcome::off_rails; CHECK(dr::report(verdict, vehicle, track, 20.0, "").starts_with("derailed, the flange climbed the rail at 72 km/h on track (none),")); } + +TEST_CASE("derailment: what the scenery and the test mode are told") { + SUBCASE("the codes of the causes are public, 1 to 5 those of the motion off the track") { + CHECK(static_cast(dr::reason::flange_climb) == 1); + CHECK(static_cast(dr::reason::overturned) == 2); + CHECK(static_cast(dr::reason::end_of_track) == 3); + CHECK(static_cast(dr::reason::pulled_off) == 4); + CHECK(static_cast(dr::reason::collision) == 5); + CHECK(static_cast(dr::reason::buckle) == 6); + CHECK(static_cast(dr::reason::overriding) == 7); + CHECK(static_cast(dr::reason::pushed_off) == 8); + CHECK(static_cast(dr::reason::overspeed) == 9); + CHECK(static_cast(dr::reason::track_gauge) == 10); + CHECK(static_cast(dr::reason::track_type) == 11); + CHECK(static_cast(dr::reason::trailed_switch) == 12); + CHECK(static_cast(dr::reason::other) == 13); + } + SUBCASE("each cause has a name of one word") { + for (int code = 0; code <= 13; ++code) { + auto const name{dr::reason_name(static_cast(code))}; + CAPTURE(code); + CHECK_FALSE(name.empty()); + CHECK(name.find(' ') == std::string_view::npos); + } + CHECK(dr::reason_name(dr::reason::end_of_track) == "end_of_track"); + CHECK(dr::reason_name(dr::reason::flange_climb) == "flange_climb"); + } + SUBCASE("the memory cell: the vehicle, the cause and the track, none for a track without a name") { + dr::notice notice{"ep07-424", dr::reason::overturned, "tdo_n222", 113.4}; + CHECK(dr::cell_text(notice) == "ep07-424 overturned tdo_n222"); + notice.track.clear(); + CHECK(dr::cell_text(notice) == "ep07-424 overturned none"); + } + SUBCASE("the log and the verdict of a test") { + dr::notice notice{"autotest_x", dr::reason::buckle, "tdo_n222", 46.4}; + CHECK(dr::describe(notice) == "autotest_x derailed (buckle) on track tdo_n222 at 46 km/h"); + notice.track.clear(); + notice.velocity = -12.6; + CHECK(dr::describe(notice) == "autotest_x derailed (buckle) on a track without a name at 13 km/h"); + } +} diff --git a/tests/unit/test_test_mode.cpp b/tests/unit/test_test_mode.cpp index eba641096..b96bd9137 100644 --- a/tests/unit/test_test_mode.cpp +++ b/tests/unit/test_test_mode.cpp @@ -43,7 +43,8 @@ std::optional run(simulation::test_progress &Progress, TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or aborted process") { - std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error}; + std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error, + test_result::derailment}; for (auto const result : results) { auto const code{static_cast(result)}; @@ -60,6 +61,8 @@ TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or abort CHECK(static_cast(test_result::timeout) == 12); CHECK(static_cast(test_result::standstill) == 13); CHECK(static_cast(test_result::error) == 14); + CHECK(static_cast(test_result::derailment) == 15); + CHECK(simulation::to_string(test_result::derailment) == "derailment"); } TEST_CASE("test mode: seconds on the command line are a number, not negative") @@ -266,3 +269,51 @@ TEST_CASE("test mode: what ended a run the simulator didn't end") CHECK(simulation::describe_exception(nullptr) == "the simulator was terminated"); } } + +TEST_CASE("test mode: a derailment") +{ + simulation::test_limits limits; + simulation::test_progress progress; + auto const first{"autotest_x derailed (buckle) on track tdo_n222 at 46 km/h"}; + auto const second{"autotest_x_w1 derailed (pulled_off) on track tdo_n222 at 31 km/h"}; + + SUBCASE("off by default: a tested train derailing doesn't end the test, the verdict tells it") + { + CHECK_FALSE(limits.fail_on_derailment); + CHECK_FALSE(simulation::evaluate_derailment(progress, true, first, limits).has_value()); + CHECK(progress.derailments == 1); + auto const verdict{run(progress, limits, 4000.0, frame(false))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::timeout); + CHECK(simulation::verdict_reason(*verdict, progress) == "no result after 3600 s [derailed: autotest_x derailed (buckle) on track tdo_n222 at 46 km/h]"); + } + SUBCASE("the verdict counts the ones after the first") + { + simulation::evaluate_derailment(progress, true, first, limits); + simulation::evaluate_derailment(progress, true, second, limits); + simulation::evaluate_derailment(progress, true, second, limits); + CHECK(simulation::verdict_reason({test_result::pass, "__test.result set to 1 and the tested trains stopped"}, progress) == + "__test.result set to 1 and the tested trains stopped [derailed: autotest_x derailed (buckle) on track tdo_n222 at 46 km/h, and 2 more]"); + } + SUBCASE("test.fail_on_derailment ends the test at once, with the derailment as the reason") + { + limits.fail_on_derailment = true; + auto const verdict{simulation::evaluate_derailment(progress, true, first, limits)}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::derailment); + CHECK(verdict->reason == first); + CHECK(simulation::verdict_reason(*verdict, progress) == first); + } + SUBCASE("another train doesn't count, either way") + { + CHECK_FALSE(simulation::evaluate_derailment(progress, false, first, limits).has_value()); + limits.fail_on_derailment = true; + CHECK_FALSE(simulation::evaluate_derailment(progress, false, first, limits).has_value()); + CHECK(progress.derailments == 0); + CHECK(simulation::verdict_reason({test_result::timeout, "no result after 60 s"}, progress) == "no result after 60 s"); + } + SUBCASE("a verdict without a derailment keeps its reason") + { + CHECK(simulation::verdict_reason({test_result::fail, "__test.result set to 0"}, progress) == "__test.result set to 0"); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a4d5f6669..3a9bbfca8 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -623,6 +623,12 @@ bool global_settings::ConfigParseTest(cParser& Parser, std::string_view const To return true; } + if (Token == "test.fail_on_derailment") + { + ParseOne(Parser, test.fail_on_derailment); + return true; + } + return false; } @@ -2733,6 +2739,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill ); export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran ); export_as_text( Output, "test.no_movement_before_pass", test.no_movement_before_pass ); + export_as_text( Output, "test.fail_on_derailment", test.fail_on_derailment ); for( auto const &vehicle : test.vehicles ) { export_as_text( Output, "test.vehicle", vehicle ); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 3364c49a0..b076d5ec4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -106,6 +106,7 @@ struct global_settings { bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged bool no_movement_before_pass{ true }; // a pass waits until the tested trains stand still; with false it ends the test at once + bool fail_on_derailment{ false }; // a derailment of a vehicle of the tested trains ends the test; with false it's only logged std::vector vehicles; // test.vehicle: the trains under test are the consists of these; none = every vehicle bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it std::optional wall_timeout; // [s] of real time since the start; none = test.timeout + time for the loading, 0 = no limit diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index fb28557a0..97585ec54 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3105,6 +3105,30 @@ double TDynamicObject::off_track_gap( int const End ) const { return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; } +derailment::notice const *TDynamicObject::new_derailment() { + + if( false == TestFlag( MoverParameters->DamageFlag, dtrain_out ) ) { + m_derailment.reset(); + return nullptr; + } + if( m_derailment ) { + return nullptr; + } + // what derailed it, at the speed it had then; the flag of the damage set by something else (SetDamage) is other + auto const known { MoverParameters->DerailedBy != derailment::reason::none }; + auto const *track { RaTrackGet() }; + // run off the end of a track it's on the piece made past the end (TTrack::NullCreate(), auto_null): the track it ran off + if( ( track != nullptr ) && ( ( track->iCategoryFlag & 0x80 ) != 0 ) && ( track->CurrentPrev() != nullptr ) ) { + track = track->CurrentPrev(); + } + m_derailment = derailment::notice { + asName, + known ? MoverParameters->DerailedBy : derailment::reason::other, + track != nullptr ? track->name() : std::string(), + known ? MoverParameters->DerailVelocity : std::abs( MoverParameters->V ) * 3.6 }; + return &*m_derailment; +} + double TDynamicObject::off_track_offset() const { if( false == MoverParameters->OffTrack.active() ) { @@ -9918,6 +9942,8 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { update_brake_pipes( Deltatime ); Timer::subsystem.vehicles_update.stop(); + report_derailments(); + // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); @@ -9993,6 +10019,17 @@ std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const } // namespace +void +vehicle_table::report_derailments() { + + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + if( auto const *notice { vehicle->new_derailment() } ) { + simulation::State.report_derailment( *vehicle, *notice ); + } + } +} + void vehicle_table::update_off_track_contacts( double const Deltatime ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index ca82a0950..f2d4b630f 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -756,6 +756,11 @@ private: // physics.derailment new, the vehicle off the track (vehicle/derailmotion.h): the offset of its body from the axis of // the track at the place nearest to it, to the left of its front positive [m]; 0 while it's on the track double off_track_offset() const; + // the vehicle derailed since the last look, by any model: what the scenery and the test mode are told, once each + // time it leaves the rails; nothing otherwise. put back on the rails it's forgotten + derailment::notice const *new_derailment(); + // its derailment while it's off the rails, nothing on them + derailment::notice const *derailment_notice() const { return m_derailment ? &*m_derailment : nullptr; } // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the // buffers pressed in double off_track_gap( int End ) const; @@ -805,6 +810,7 @@ private: bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit + std::optional m_derailment; // of new_derailment(), while the vehicle is off the rails // the model, the axes and the coupling points placed by the motion off the track void place_off_track(); public: @@ -1044,6 +1050,9 @@ private: // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void update_brake_pipes( double const Deltatime ); + // the vehicles which derailed in the update, after all of them moved: told to the scenery and the test mode + void + report_derailments(); // physics.derailment new: the bodies of the vehicles off the track and those near them run into each other instead // of into one another: the impulses of the hits, the bodies moved apart, a vehicle on the rails pushed off them; // what the bodies overlap by goes to the log every second diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index 0138b6acd..df6bb7416 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -394,6 +394,8 @@ void writer::derailment(derailment_state const &State) { out.f32(State.roll); out.f32(State.travelled); out.u8(State.lying ? 1 : 0); + out.u8(State.reason); + out.text(State.track); emit(record::derailment); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 26fe5c6a1..20b98bfa2 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -337,6 +337,7 @@ inline constexpr std::uint8_t collision{5}; namespace derailment_phases { inline constexpr std::uint8_t left_track{0}; // it left the track inline constexpr std::uint8_t at_rest{1}; // it came to rest off the track +inline constexpr std::uint8_t derailed{2}; // it derailed, by any model: written as it happens } // namespace derailment_phases // a vehicle off the track (physics.derailment new): as it leaves it, and where it comes to rest @@ -352,6 +353,8 @@ struct derailment_state { float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side float travelled{0.0f}; // [m] on the ground since it left the rails bool lying{false}; // on its side + std::uint8_t reason{0}; // what derailed it, finer: the code of derailment::reason (McZapkie/derailment.h), 0 not known + std::string track; // name of the track it derailed on, empty for a track without one }; struct vehicle_state {