From aa84e41f0984e38b26a4f0e663ba77e2111748d8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 00:17:22 +0100 Subject: [PATCH] feat: timetable service flags for the AI driver (eu07/maszyna#95) A timetable can now tell the AI how the train is served, for trams, underground trains and the like. The whole train gets them from a new row of the first box of the header: [ Flagi AI | drzwi_centralne=tak,stopien=nie,kierownik=nie,proba_hamulca=nie ] and a station changes them from there on with entries of its station ware (the second line of the station, next to R2, ph, @): [ | | po,kierownik=nie 1 12.54 | ] - drzwi_centralne=tak: the driver opens all the doors from the cab, those of mixed control too (otherwise left to the passengers) - stopien=tak/nie: the doorsteps switched on/off before the doors open (the AI didn't touch them before; new driver hints for it) - kierownik=nie: no conductor, so no departure signal (direct or by radio) and no first door kept open for him before the departure - proba_hamulca=nie: no running brake test A flag left out keeps today's behaviour, so a timetable without flags drives as before. Old builds skip the header row and keep the station entries as station ware text (none starts with R or holds @, po, pt). The reader moves out of TTrainParameters::LoadTTfile into world/timetablereader.cpp (eu07_core) unchanged, so the tests can run it; the flags come out of the station ware there. It now ends at the end of the file with an error where the old one spun forever (a truncated file, a missing number), and stops at 100 stations instead of writing past the table. Every .txt of the game's sceneries and of the SVN data reads the same as with the old reader (compared field by field against a verbatim copy of it); EU07_UNIT_TESTS_TIMETABLES= reads them in the unit tests and EU07_UNIT_TESTS_TIMETABLES_DUMP writes what was read. --- CMakeLists.txt | 3 + application/driverhints.cpp | 23 +++ application/driverhints_def.h | 2 + tests/unit/test_timetable.cpp | 321 ++++++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 26 ++- vehicle/Driver.h | 1 + vehicle/timetableservice.cpp | 49 ++++++ vehicle/timetableservice.h | 37 ++++ world/mtable.cpp | 307 +++----------------------------- world/mtable.h | 25 +-- world/timetableflags.cpp | 103 +++++++++++ world/timetableflags.h | 59 +++++++ world/timetablereader.cpp | 321 ++++++++++++++++++++++++++++++++++ world/timetablereader.h | 66 +++++++ 14 files changed, 1038 insertions(+), 305 deletions(-) create mode 100644 tests/unit/test_timetable.cpp create mode 100644 vehicle/timetableservice.cpp create mode 100644 vehicle/timetableservice.h create mode 100644 world/timetableflags.cpp create mode 100644 world/timetableflags.h create mode 100644 world/timetablereader.cpp create mode 100644 world/timetablereader.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..7fb845ba3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -553,6 +553,9 @@ set(CORE_SOURCES "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"vehicle/timetableservice.cpp" +"world/timetableflags.cpp" +"world/timetablereader.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..2c3fbd66b 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -1150,6 +1150,29 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return IsAnyDoorPermitActive[side::left] == false; } ); break; } + // doorsteps, as the timetable asks (eu07/maszyna#95) + case driver_hint::doorstepon: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( true ); + } + remove_hint( driver_hint::doorstepoff ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == true; } ); + break; + } + case driver_hint::doorstepoff: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( false ); + } + remove_hint( driver_hint::doorstepon ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == false; } ); + break; + } // consist lights case driver_hint::consistlightson: { if( AIControllFlag ) { diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..6f5c86474 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -72,6 +72,8 @@ DRIVER_HINT_DEF(doorrightpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorrightpermitoff, STRN("Revoke permit to open doors")) DRIVER_HINT_DEF(doorleftpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorleftpermitoff, STRN("Revoke permit to open doors")) +DRIVER_HINT_DEF(doorstepon, STRN("Switch on doorsteps")) +DRIVER_HINT_DEF(doorstepoff, STRN("Switch off doorsteps")) DRIVER_HINT_DEF(hornon, STRN("Sound the horn")) DRIVER_HINT_DEF(hornoff, STRN("Switch off horn")) DRIVER_HINT_DEF(consistlightson, STRN("Switch on consist lights")) diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp new file mode 100644 index 000000000..f4387e7f8 --- /dev/null +++ b/tests/unit/test_timetable.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/MOVER.h" +#include "utilities/utilities.h" +#include "vehicle/timetableservice.h" +#include "world/timetablereader.h" + +#include +#include +#include +#include +#include + +// the timetables of the trains (.txt next to the scenery, world/timetablereader.cpp) and the service flags they +// give the AI driver (eu07/maszyna#95): the reader as it was, the flags of the header and of the stations, and what +// the driver does with them + +using timetable::service_flags; +using timetable::tristate; + +namespace { + +// a timetable the way the game's sceneries have them: the header, three stations, a speed change at the second one +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "%FLAGS%" + "[________________________________________________|__________________]\n" + "[ | Gorna ]\n" + "[ Relacja pociagu | Dolna ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Gorna 1 | | ]\n" + "[ | | %WARE1% 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Srodkowa 1 12.54 | 7 ]\n" + "[ | 40 | %WARE2% 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | Dolna 2 13.01 | 6 ]\n" + "[ | | %WARE3% 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +std::string replaced(std::string Text, std::string const &Key, std::string const &Value) { + for (auto at{Text.find(Key)}; at != std::string::npos; at = Text.find(Key, at + Value.size())) { + Text.replace(at, Key.size(), Value); + } + return Text; +} + +std::string timetable_with(std::string const &Flags, std::string const &Ware1, std::string const &Ware2, std::string const &Ware3) { + return replaced(replaced(replaced(replaced(timetable_text, "%FLAGS%", Flags), "%WARE1%", Ware1), "%WARE2%", Ware2), "%WARE3%", Ware3); +} + +struct read_result { + int error; + Mtable::timetable_data data; +}; + +read_result read(std::string const &Text) { + std::istringstream input{Text}; + read_result result; + result.data.TrainName = "file"; + result.error = Mtable::read_timetable(input, result.data); + return result; +} + +service_flags flags(tristate const Doors, tristate const Doorstep, tristate const Conductor, tristate const Braketest) { + return {Doors, Doorstep, Conductor, Braketest}; +} + +auto const unset{tristate::unset}; +auto const yes{tristate::yes}; +auto const no{tristate::no}; + +// what the timetable gives, but for the service flags: to compare a timetable with flags to one without +std::string contents(Mtable::timetable_data const &Data) { + auto text{std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}\n", Data.TrainName, Data.TrainCategory, Data.TrainLabel, Data.Relation1, Data.Relation2, Data.BrakeRatio, + Data.LocSeries, Data.LocLoad, Data.StationCount)}; + for (auto i{0}; i <= Data.StationCount; ++i) { + auto const &row{Data.TimeTable[i]}; + text += std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}\n", i, row.km, row.vmax, row.StationName, row.StationWare, row.TrackNo, row.Ah, row.Am, row.Dh, row.Dm, + row.tm, row.is_maintenance, row.radio_channel); + } + return text; +} + +std::string flags_text(service_flags const &Flags) { + auto const one{[](tristate const Flag) { return Flag == tristate::unset ? '-' : Flag == tristate::yes ? 'y' : 'n'; }}; + return {one(Flags.central_doors), one(Flags.doorstep), one(Flags.conductor), one(Flags.brake_test)}; +} + +} // namespace + +TEST_CASE("timetable: the reader reads a timetable the way it always did") { + auto const [error, data]{read(timetable_with("", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.Relation2 == "Dolna"); + CHECK(data.BrakeRatio == 60.0); + CHECK(data.LocSeries == "EN57"); + CHECK(data.LocLoad == 120.0); + REQUIRE(data.StationCount == 3); + + auto const &first{data.TimeTable[1]}; + CHECK(first.StationName == "Gorna"); + CHECK(first.km == doctest::Approx(1.13)); + CHECK(first.Ah == -1); // no arrival: LoadTTfile makes it a stop, the first station being the start of the relation + CHECK(first.Dh == 12); + CHECK(first.Dm == 47.f); + CHECK(first.StationWare == "R2,H"); + CHECK(first.radio_channel == 2); + + auto const &second{data.TimeTable[2]}; + CHECK(second.StationName == "Srodkowa"); + CHECK(second.Ah == 12); + CHECK(second.Am == 54.f); + CHECK(second.Dm == 55.f); + CHECK(second.tm == 7.f); + CHECK(second.StationWare == "po"); + CHECK(second.radio_channel == -1); + + auto const &last{data.TimeTable[3]}; + CHECK(last.StationName == "Dolna"); + CHECK(last.TrackNo == 2); + CHECK(last.Ah == 13); + CHECK(last.Dh == 13); // departure as the arrival, for the delay + CHECK(last.radio_channel == 3); + // 60 km/h up to the change at the second station, 40 km/h after it + CHECK(data.TimeTable[1].vmax == 60.f); + CHECK(data.TimeTable[2].vmax == 60.f); + CHECK(data.TimeTable[3].vmax == 40.f); + // a timetable without flags leaves all of them to the vehicles + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } +} + +TEST_CASE("timetable: the row Flagi of the header sets the flags of the whole train") { + auto const [error, data]{read(timetable_with("[ Flagi AI | kierownik=nie, proba_hamulca=nie ]\n", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.Flags == flags(unset, unset, no, no)); + // every station has them + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].flags == data.Flags); + } + // and the rest of the header reads as before + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a station's flags hold from that station on") { + auto const [error, data]{read(timetable_with("[ Flagi AI | proba_hamulca=nie ]\n", "R2,H", "po,stopien=nie,drzwi_centralne=tak", "R3,stopien=tak"))}; + + CHECK(error == 0); + CHECK(data.TimeTable[1].flags == flags(unset, unset, unset, no)); + CHECK(data.TimeTable[2].flags == flags(yes, no, unset, no)); + CHECK(data.TimeTable[3].flags == flags(yes, yes, unset, no)); + // the flags are taken out of the station ware, the rest of it stays + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[3].StationWare == "R3"); + CHECK(data.TimeTable[3].radio_channel == 3); +} + +TEST_CASE("timetable: the flags change nothing else the timetable gives") { + auto const plain{read(timetable_with("", "R2,H", "po", "R3"))}; + auto const flagged{read(timetable_with("[ Flagi AI | kierownik=nie ]\n", "kierownik=tak,R2,H", "po,drzwi_centralne=tak", "R3,stopien=nie,proba_hamulca=nie"))}; + + CHECK(flagged.error == plain.error); + CHECK(contents(flagged.data) == contents(plain.data)); +} + +TEST_CASE("timetable: entries which aren't flags stay in the station ware") { + service_flags read_flags; + SUBCASE("no flags: the list as it was, empty entries too") { + CHECK(timetable::extract_flags("po,,R2", read_flags) == "po,,R2"); + CHECK(timetable::extract_flags("", read_flags).empty()); + CHECK(read_flags.empty()); + } + SUBCASE("an unknown key stays, a known one with an unknown value is dropped") { + CHECK(timetable::extract_flags("po,foo=1,kierownik=moze,R2", read_flags) == "po,foo=1,R2"); + CHECK(read_flags.empty()); + } + SUBCASE("keys and values in either case, 1 and 0 for tak and nie") { + CHECK(timetable::extract_flags("Kierownik=NIE,STOPIEN=1,ph", read_flags) == "ph"); + CHECK(read_flags == flags(unset, yes, no, unset)); + } +} + +TEST_CASE("timetable: a truncated timetable is an error, not a hang") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + // cut in the middle of a station, in the middle of the header, right after the top line: the reader used to go + // on reading past the end of the file forever + for (auto const cut : {text.find("Srodkowa"), text.find("Wymagany"), text.find("Rodzaj")}) { + CAPTURE(cut); + auto const [error, data]{read(text.substr(0, cut))}; + CHECK(error == Mtable::timetable_truncated); + } + // cut between two stations: the row the reader expects isn't there + auto const [error, data]{read(text.substr(0, text.find("[ 9.16")))}; + CHECK(error == -4); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a timetable longer than the table is an error") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const begin{text.find("[ 5.06")}; + auto const end{text.find("[ 9.16")}; + auto const station{text.substr(begin, end - begin)}; + std::string stations; + for (auto i{0}; i < Mtable::MaxTTableSize; ++i) { + stations += station; + } + auto const [error, data]{read(text.substr(0, begin) + stations + text.substr(end))}; + CHECK(error == Mtable::timetable_too_long); + CHECK(data.StationCount == Mtable::MaxTTableSize); +} + +TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { + // before the timetable is loaded, and with none + CHECK(timetable::stop_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(1, 0) == 0); + // making for (or standing at) the first station: its flags at the stop, the header's on the way + CHECK(timetable::stop_flags_entry(1, 3) == 1); + CHECK(timetable::run_flags_entry(1, 3) == 0); + // after the departure from the second station + CHECK(timetable::stop_flags_entry(3, 3) == 3); + CHECK(timetable::run_flags_entry(3, 3) == 2); + // past the end of the timetable + CHECK(timetable::stop_flags_entry(4, 3) == 3); + CHECK(timetable::run_flags_entry(5, 3) == 3); +} + +TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the timetable say") { + test::vehicle unit{test::definition::load("wagon")}; + auto const central{flags(yes, unset, unset, unset)}; + auto const notcentral{flags(no, unset, unset, unset)}; + + unit->Doors.open_control = control_t::driver; + CHECK(timetable::opens_doors(unit.mover(), {})); + CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + unit->Doors.open_control = control_t::conductor; + CHECK(timetable::opens_doors(unit.mover(), {})); + // doors of mixed control are left to the passengers, unless the timetable has the driver open them all + unit->Doors.open_control = control_t::mixed; + CHECK_FALSE(timetable::opens_doors(unit.mover(), {})); + CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); + CHECK(timetable::opens_doors(unit.mover(), central)); + // the passengers' own doors and the automatic ones can't be opened from the cab + unit->Doors.open_control = control_t::passenger; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + unit->Doors.open_control = control_t::autonomous; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); +} + +TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { + // no flags: the doorsteps as they are, the conductor and the brake test as before + CHECK_FALSE(timetable::doorstep({}).has_value()); + CHECK(timetable::has_conductor({})); + CHECK(timetable::makes_brake_test({})); + + CHECK(timetable::doorstep(flags(unset, no, unset, unset)) == false); + CHECK(timetable::doorstep(flags(unset, yes, unset, unset)) == true); + CHECK_FALSE(timetable::has_conductor(flags(unset, unset, no, unset))); + CHECK(timetable::has_conductor(flags(unset, unset, yes, unset))); + CHECK_FALSE(timetable::makes_brake_test(flags(unset, unset, unset, no))); + CHECK(timetable::makes_brake_test(flags(unset, unset, unset, yes))); +} + +// reads every .txt file under the folder given in EU07_UNIT_TESTS_TIMETABLES (the scenery/ of the game), the way the +// game reads a timetable, and checks none of them has flags; EU07_UNIT_TESTS_TIMETABLES_DUMP names a file to write +// what was read to, to compare the reading of two builds +TEST_CASE("timetable: the timetables of the game, when asked for") { + auto const *source{std::getenv("EU07_UNIT_TESTS_TIMETABLES")}; + if (source == nullptr) { + return; + } + std::vector files; + for (auto const &entry : std::filesystem::recursive_directory_iterator{source}) { + if (entry.is_regular_file() && ToLower(entry.path().extension().string()) == ".txt") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + std::string dump; + auto timetables{0}; + for (auto const &file : files) { + auto const name{std::filesystem::relative(file, source).generic_string()}; + CAPTURE(name); + std::ifstream input{file}; + Mtable::timetable_data data; + data.TrainName = file.stem().string(); + auto const error{Mtable::read_timetable(input, data)}; + if (error == 0 && data.StationCount > 0) { + ++timetables; + } + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } + dump += std::format("== {} error {}\n", name, error) + contents(data); + } + MESSAGE(std::format("{} files, {} read as timetables", files.size(), timetables)); + if (auto const *output{std::getenv("EU07_UNIT_TESTS_TIMETABLES_DUMP")}; output != nullptr) { + std::ofstream{output, std::ios::binary} << dump; + } +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..6ff904431 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" +#include "vehicle/timetableservice.h" #include "world/mtable.h" #include "vehicle/DynObj.h" #include "world/Event.h" @@ -1345,6 +1346,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { // to się wykona tylko raz po zatrzymaniu na W4 record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); if( TrainParams.StationIndex < TrainParams.StationCount ) { // jeśli są dalsze stacje, bez trąbienia przed odjazdem // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop @@ -1443,7 +1446,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) } - if( false == tsGuardSignal.empty() ) { + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { // jeśli mamy głos kierownika, to odegrać iDrivigFlags |= moveGuardSignal; } @@ -1451,7 +1455,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } // koniec startu z zatrzymania else { cue_action(driver_hint::waitdeparturetime); - if (TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure iDrivigFlags |= moveGuardOpenDoor; GuardOpenDoor(); } @@ -4790,6 +4795,11 @@ void TController::Doors( bool const Open, int const Side ) { auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } // grant door control permission if it's not automatic // TBD: stricter requirements? if( true == pVehicle->MoverParameters->Doors.permit_needed ) { @@ -4801,10 +4811,9 @@ void TController::Doors( bool const Open, int const Side ) { } } // consist-wide remote signals to open doors doors - if( pVehicle->MoverParameters->Doors.open_control == control_t::conductor - || pVehicle->MoverParameters->Doors.open_control == control_t::driver - // NOTE: disabled for mixed controls, leave it up to passengers to open doors by themselves -/* || ( pVehicle->MoverParameters->Doors.open_control == control_t::mixed ) */ ) { + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { if( Side & prawe ) { cue_action( driver_hint::doorrightopen ); } @@ -4954,6 +4963,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams = TTrainParameters(NewCommand); // rozkład jazdy tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika m_lastexchangestop.clear(); + m_stopflags = {}; if (NewCommand != "none") { if (false == TrainParams.LoadTTfile( @@ -4988,6 +4998,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams.StationIndexInc(); // przejście do następnej TrainParams.StationStart = TrainParams.StationIndex; asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); m_lastannouncement = announcement_t::idle; iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym // NewCommand = Global.asCurrentSceneryPath + NewCommand; @@ -8588,6 +8600,8 @@ TController::adjust_desired_speed_for_braking_test() { // if( false == Global.DynamicBrakeTest ) { return; } if( DynamicBrakeTest >= 5 ) { return; } // all done + if( ( DynamicBrakeTest == 0 ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable diff --git a/vehicle/Driver.h b/vehicle/Driver.h index cfa27757e..2ed51b6a1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -663,6 +663,7 @@ private: std::string m_lastexchangestop; // HACK: safeguard to prevent multiple load exchanges per station int m_lastexchangeplatforms { 0 }; // cached station platforms for last exchange int m_lastexchangedirection { 0 }; // + timetable::service_flags m_stopflags; // service flags of the timetable at the stop the train is at or left last double fLastStopExpDist = -1.0; // odległość wygasania ostateniego przystanku int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp new file mode 100644 index 000000000..913e9d2d4 --- /dev/null +++ b/vehicle/timetableservice.cpp @@ -0,0 +1,49 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/timetableservice.h" + +#include "McZapkie/MOVER.h" + +namespace timetable { + +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { + switch (Vehicle.Doors.open_control) { + case control_t::conductor: + case control_t::driver: + return true; + case control_t::mixed: + // left to the passengers, unless the timetable has the driver open them all + return Flags.central_doors == tristate::yes; + default: + return false; + } +} + +std::optional doorstep(service_flags const &Flags) { + switch (Flags.doorstep) { + case tristate::yes: + return true; + case tristate::no: + return false; + default: + return std::nullopt; + } +} + +bool has_conductor(service_flags const &Flags) { + return Flags.conductor != tristate::no; +} + +bool makes_brake_test(service_flags const &Flags) { + return Flags.brake_test != tristate::no; +} + +} // namespace timetable diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h new file mode 100644 index 000000000..b5c72adf7 --- /dev/null +++ b/vehicle/timetableservice.h @@ -0,0 +1,37 @@ +/* +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 "world/timetableflags.h" + +class TMoverParameters; + +// what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with +// no flags each answer is the one the AI gave before the flags +namespace timetable { + +// whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors +// the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are +// otherwise left to the passengers +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags); + +// the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are +std::optional doorstep(service_flags const &Flags); + +// whether a conductor serves the train: gives the departure signal (by radio or by voice) and keeps the first door +// open for himself until the departure +bool has_conductor(service_flags const &Flags); + +// whether the driver makes the running brake test after the departure +bool makes_brake_test(service_flags const &Flags); + +} // namespace timetable diff --git a/world/mtable.cpp b/world/mtable.cpp index 123ae00f6..daf7b6637 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -109,6 +109,16 @@ sound_source TTrainParameters::current_stop_sound() const { return { sound_placement::engine }; } +timetable::service_flags const &TTrainParameters::stop_flags() const { + + return TimeTable[ timetable::stop_flags_entry( StationIndex, StationCount ) ].flags; +} + +timetable::service_flags const &TTrainParameters::run_flags() const { + + return TimeTable[ timetable::run_flags_entry( StationIndex, StationCount ) ].flags; +} + bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string const &NewName ) { return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); @@ -257,21 +267,16 @@ void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { - std::string lines; std::string s; std::ifstream fin; - bool EndTable; - double vActual; int conversionerror = 0; - EndTable = false; if (TrainName == "") { // jeśli pusty rozkład // UpdateVelocity(StationCount,vMax); //ograniczenie do prędkości startowej } else { - vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach @@ -293,284 +298,22 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } else { /*analiza rozkładu jazdy*/ - conversionerror = 0; - while (fin.good() && !(conversionerror != 0 || EndTable)) - { - std::getline(fin, lines); /*wczytanie linii*/ - if (contains( lines, "___________________") ) /*linia pozioma górna*/ - { - fin >> s; - if (s == "[") /*lewy pion*/ - { - fin >> s; - if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ - do - { - fin >> s; - } while (!(s == "|") || fin.eof()); /*środkowy pion*/ - } - } - else if (lines == "") - { - fin.close(); - break; - } - fin >> s; /*nazwa pociągu*/ - // if LowerCase(s)<>ExtractFileName(TrainName) then {musi być taka sama, jak nazwa - // pliku} - // ConversionError:=-7 {błąd niezgodności} - TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) - while (fin >> s || fin.bad()) - { - if (contains( s,"_______|") ) - { - break; - } - if (s == "Kategoria") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainCategory; - continue; - } - if (s == "Nazwa") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainLabel; - continue; - } - } // while (!(s == "Seria")); - // else - { /*czytaj naglowek*/ - while (fin >> s || !fin.bad()) - { - if (s == "[") - break; - } // while (!() || (fin.eof())); /*pierwsza linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s != "|") - break; - } // while (!(() || fin.eof())); - if( s != "|" ) { - Relation1 = s; - win1250_to_ascii( Relation1 ); - } - else - conversionerror = -5; - while (fin >> s || !fin.bad()) - { - if (s == "Relacja") - break; - } // while ( - // !( || (fin.eof()))); /*druga linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s == "|") - break; - } // while (!( || (fin.eof()))); - fin >> Relation2; - win1250_to_ascii( Relation2 ); - while (fin >> s || !fin.bad()) - { - if (s == "Wymagany") - break; - } // while (!(); - while (fin >> s || !fin.bad()) - { - if (s == "|" || s == "\n") - break; - } // while (!()); - fin >> s; - s = s.substr(0, s.find("%")); - BrakeRatio = atof(s.c_str()); - while (fin >> s || fin.bad()) - { - if (s == "Seria") - break; - } // while (!(s == "Seria")); - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> LocSeries; - fin >> LocLoad; // = s2rE(ReadWord(fin)); - do - { - fin >> s; - } while (!(contains( s,"[______________" ) || fin.bad())); - auto activeradiochannel{ -1 }; - while (!fin.bad() && !EndTable) - { - ++StationCount; - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - TMTableLine *record = &TimeTable[StationCount]; - { - if (s == "[") - fin >> s; - else - conversionerror = -4; - if (false == contains( s,"|") ) - { - record->km = static_cast(atof(s.c_str())); - fin >> s; - } - if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains( s,"|")) - fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii( record->StationName ); - do - { - fin >> s; - } while (!(s == "1" || s == "2" || fin.bad())); - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu - } - else - { - record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - fin >> s; - if (false == contains(s,"|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (s.find("|_____|") != - std::string::npos) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains(s,"|")) - fin >> s; - // stationware. added fix for empty entry - fin >> s; - while( false == ( s == "1" - || s == "2" - || fin.bad() ) ) { - record->StationWare += s; - fin >> s; - } - // cache relevant station data - record->is_maintenance = contains(s, "pt"); - { - auto const stationware { Split( record->StationWare, ',' ) }; - for( auto const &entry : stationware ) { - if( entry.front() != 'R' ) { - continue; - } - auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; - if( entrytype == "R" - && entrynumber <= 10 ) { - auto const radiochannel { entrynumber }; - if( record->radio_channel == -1 - || radiochannel != activeradiochannel ) { - // if the station has more than one radiochannel listed, - // it generally means we should switch to the one we weren't using so far - // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system - record->radio_channel = radiochannel; - } - } - } - if( record->radio_channel != -1 ) { - activeradiochannel = record->radio_channel; - } - } - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu - } - else - { - record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - else - { - record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) - record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(contains( s, "[" ) || fin.bad())); - if (false == contains( s, "_|_")) - fin >> s; - if (false == contains( s, "|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (contains( s, "|_____|") ) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains( s, "|")) - vActual = atof(s.c_str()); - } - while (false == contains( s, "|" ) ) - fin >> s; - while (false == contains(s, "]")) - fin >> s; - if (contains( s,"_|_") ) - EndTable = true; - } /*timetableline*/ - } - } - } /*while eof*/ + timetable_data data; + data.TrainName = TrainName; + conversionerror = read_timetable( fin, data ); fin.close(); + TrainName = data.TrainName; + TrainCategory = data.TrainCategory; + TrainLabel = data.TrainLabel; + Relation1 = data.Relation1; + Relation2 = data.Relation2; + BrakeRatio = data.BrakeRatio; + LocSeries = data.LocSeries; + LocLoad = data.LocLoad; + StationCount = data.StationCount; + for( auto i = 0; i <= MaxTTableSize; ++i ) { + static_cast( TimeTable[ i ] ) = data.TimeTable[ i ]; + } } } // jeśli nazwa pierwszego zgodna z relacją diff --git a/world/mtable.h b/world/mtable.h index 841fea815..31fdd8810 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -13,32 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" +#include "world/timetablereader.h" namespace Mtable { -static int const MaxTTableSize = 100; // można by to robić dynamicznie static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount -struct TMTableLine +// a station of the timetable as the file gives it (TMTableEntry, world/timetablereader.h), with its name announcement +struct TMTableLine : TMTableEntry { - float km{ 0.f }; // kilometraz linii - float vmax{ -1.f }; // predkosc rozkladowa przed przystankiem - // StationName:string[32]; //nazwa stacji ('_' zamiast spacji) - // StationWare:string[32]; //typ i wyposazenie stacji, oddz. przecinkami} - std::string StationName{ "nowhere" }; // nazwa stacji ('_' zamiast spacji) - std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami} - int TrackNo{ 1 }; // ilosc torow szlakowych - int Ah{ -1 }; - float Am{ -1.f }; // godz. i min. przyjazdu, -1 gdy bez postoju - int Dh{ -1 }; - float Dm{ -1.f }; // godz. i min. odjazdu - float tm{ 0.f }; // czas jazdy do tej stacji w min. (z kolumny) - bool is_maintenance{ false }; - int radio_channel{ -1 }; sound_source name_sound{ sound_placement::engine }; }; @@ -58,7 +45,7 @@ class TTrainParameters double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; - TMTable TimeTable; + TMTable TimeTable; // TimeTable[0].flags holds the service flags of the whole train int StationCount; // ilość przystanków (0-techniczny) int StationIndex; // numer najbliższego (aktualnego) przystanku int StationStart; // numer pierwszej stacji pokazywanej na podglądzie rozkładu @@ -95,6 +82,10 @@ class TTrainParameters int radio_channel() const; // returns: sound file associated with current station, or -1 sound_source current_stop_sound() const; + // service flags (eu07/maszyna#95) which hold at the stop the train makes for or stands at + timetable::service_flags const &stop_flags() const; + // service flags which hold on the way, since the stop the train left last + timetable::service_flags const &run_flags() const; private: void load_sounds(); }; diff --git a/world/timetableflags.cpp b/world/timetableflags.cpp new file mode 100644 index 000000000..5c7d6ae9e --- /dev/null +++ b/world/timetableflags.cpp @@ -0,0 +1,103 @@ +/* +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/timetableflags.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace timetable { + +namespace { + +void apply_one(tristate &Flag, tristate const Other) { + if (Other != tristate::unset) { + Flag = Other; + } +} + +tristate *flag_named(std::string_view const Key, service_flags &Flags) { + if (Key == "drzwi_centralne") { + return &Flags.central_doors; + } + if (Key == "stopien") { + return &Flags.doorstep; + } + if (Key == "kierownik") { + return &Flags.conductor; + } + if (Key == "proba_hamulca") { + return &Flags.brake_test; + } + return nullptr; +} + +} // namespace + +void service_flags::apply(service_flags const &Other) { + apply_one(central_doors, Other.central_doors); + apply_one(doorstep, Other.doorstep); + apply_one(conductor, Other.conductor); + apply_one(brake_test, Other.brake_test); +} + +bool read_flag(std::string_view const Entry, service_flags &Flags) { + auto const separator{Entry.find('=')}; + if (separator == std::string_view::npos) { + return false; + } + auto const key{ToLower(std::string{Entry.substr(0, separator)})}; + auto *flag{flag_named(key, Flags)}; + if (flag == nullptr) { + return false; + } + auto const value{ToLower(std::string{Entry.substr(separator + 1)})}; + if (value == "tak" || value == "1") { + *flag = tristate::yes; + } + else if (value == "nie" || value == "0") { + *flag = tristate::no; + } + else { + ErrorLog("Bad timetable: unknown value of " + key + " in \"" + std::string{Entry} + "\", expected tak or nie"); + } + return true; +} + +std::string extract_flags(std::string const &Ware, service_flags &Flags) { + if (false == contains(Ware, '=')) { + // no flags, the list as it was + return Ware; + } + std::string rest; + for (auto const &entry : Split(Ware, ',')) { + if (read_flag(entry, Flags)) { + continue; + } + if (contains(entry, '=')) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in station ware \"" + Ware + "\""); + } + if (false == rest.empty()) { + rest += ','; + } + rest += entry; + } + return rest; +} + +int stop_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex, 0, std::max(StationCount, 0)); +} + +int run_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex - 1, 0, std::max(StationCount, 0)); +} + +} // namespace timetable diff --git a/world/timetableflags.h b/world/timetableflags.h new file mode 100644 index 000000000..8c463d3f3 --- /dev/null +++ b/world/timetableflags.h @@ -0,0 +1,59 @@ +/* +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 + +// the way a train is served, set by its timetable for the AI driver (eu07/maszyna#95): trams and underground trains +// open all the doors from the cab, have no doorstep, no conductor, no running brake test. each flag the timetable +// leaves out keeps the behaviour of the vehicles, as before the flags. +// +// the whole train: a row of the first box of the header +// [ Flagi AI | kierownik=nie,proba_hamulca=nie ] +// from a station on: entries of its station ware (the second line of the station, with R2, ph, @...) +// [ | | R2,ph,drzwi_centralne=tak,stopien=nie 1 12.47 | ] +// a station's entry holds from that station on, until another station changes it +namespace timetable { + +enum class tristate : std::uint8_t { + unset, // left to the vehicles, as before the flags + yes, + no +}; + +struct service_flags { + tristate central_doors{tristate::unset}; // drzwi_centralne: the driver opens all the doors, of mixed control too + tristate doorstep{tristate::unset}; // stopien: the doorsteps on (tak) or off (nie) before the doors open + tristate conductor{tristate::unset}; // kierownik: no conductor (nie), no departure signal, no door kept open for him + tristate brake_test{tristate::unset}; // proba_hamulca: no running brake test (nie) + + bool operator==(service_flags const &) const = default; + bool empty() const { return *this == service_flags{}; } + // the flags Other sets explicitly override these + void apply(service_flags const &Other); +}; + +// reads one entry, key=value (tak/nie, 1/0), into Flags. returns false for an entry which isn't a flag, so the caller +// keeps it; a flag with a value it doesn't know is reported to the log and taken as handled +bool read_flag(std::string_view Entry, service_flags &Flags); + +// reads the flags out of a station ware list (comma separated entries) into Flags. returns the list without them: the +// list as it was when it had none +std::string extract_flags(std::string const &Ware, service_flags &Flags); + +// the timetable entry whose flags hold at the stop the train makes for or stands at: the current one (StationIndex), +// within 0 (the header's flags) and the last station +int stop_flags_entry(int StationIndex, int StationCount); +// the entry whose flags hold on the way: the station the train left last, 0 (the header's flags) before the first one +int run_flags_entry(int StationIndex, int StationCount); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp new file mode 100644 index 000000000..3d340e8bd --- /dev/null +++ b/world/timetablereader.cpp @@ -0,0 +1,321 @@ +/* +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/timetablereader.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace Mtable { + +namespace { + +char const *const hrsd = "."; + +// the rest of the row "Flagi" of the header after its label: flag entries up to the closing bracket. returns true when +// a row with no closing bracket ran into the line under the box +bool read_header_flags(std::istream &fin, timetable_data &Data) { + std::string s; + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + while (fin >> s) { + if (s.starts_with('[')) { + // the next row, or the line under the box + ErrorLog("Bad timetable: row \"Flagi\" of " + Data.TrainName + " without the closing bracket"); + return contains(s, "_______|"); + } + auto const closing{s.ends_with(']')}; + for (auto const &entry : Split(closing ? std::string_view{s}.substr(0, s.size() - 1) : std::string_view{s}, ',')) { + if (false == entry.empty() && false == timetable::read_flag(entry, Data.Flags)) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in row \"Flagi\" of " + Data.TrainName); + } + } + if (closing) { + break; + } + } + return false; +} + +} // namespace + +// the reader as TTrainParameters::LoadTTfile had it, but for: the row "Flagi" of the header and the flags of the +// station ware; the loops end with the end of the file, where they used to spin forever (on a truncated file, or one +// with a number where the reader expects it which isn't one). a file the old reader read gets read the same +int read_timetable(std::istream &fin, timetable_data &Data) { + std::string lines; + std::string s; + bool EndTable{false}; + double vActual{-1}; + int conversionerror{0}; + auto &TimeTable{Data.TimeTable}; + auto &StationCount{Data.StationCount}; + // zapisywanie prędkości maksymalnej do wcześniejszych odcinków + auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { + int i = StationCount; + while (i >= 0 && TimeTable[i].vmax == -1) { + TimeTable[i].vmax = static_cast(Velocity); // prędkość dojazdu do przystanku i + --i; // ewentualnie do poprzedniego też + } + }}; + + while (fin.good() && !(conversionerror != 0 || EndTable)) { + std::getline(fin, lines); /*wczytanie linii*/ + if (contains(lines, "___________________")) /*linia pozioma górna*/ + { + fin >> s; + if (s == "[") /*lewy pion*/ + { + fin >> s; + if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ + do { + fin >> s; + } while (!(s == "|" || fin.fail())); /*środkowy pion*/ + } + } + else if (lines == "") { + break; + } + fin >> s; /*nazwa pociągu*/ + Data.TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) + while (fin >> s) { + if (contains(s, "_______|")) { + break; + } + if (s == "Kategoria") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainCategory; + continue; + } + if (s == "Nazwa") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainLabel; + continue; + } + if (s == "Flagi") { + // service flags of the whole train (eu07/maszyna#95) + if (read_header_flags(fin, Data)) { + break; + } + continue; + } + } + { /*czytaj naglowek*/ + while (fin >> s) { + if (s == "[") + break; + } /*pierwsza linia z relacją*/ + while (fin >> s) { + if (s != "|") + break; + } + if (s != "|") { + Data.Relation1 = s; + win1250_to_ascii(Data.Relation1); + } + else + conversionerror = -5; + while (fin >> s) { + if (s == "Relacja") + break; + } /*druga linia z relacją*/ + while (fin >> s) { + if (s == "|") + break; + } + fin >> Data.Relation2; + win1250_to_ascii(Data.Relation2); + while (fin >> s) { + if (s == "Wymagany") + break; + } + while (fin >> s) { + if (s == "|" || s == "\n") + break; + } + fin >> s; + s = s.substr(0, s.find("%")); + Data.BrakeRatio = atof(s.c_str()); + while (fin >> s) { + if (s == "Seria") + break; + } + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.LocSeries; + fin >> Data.LocLoad; // = s2rE(ReadWord(fin)); + do { + fin >> s; + } while (!(contains(s, "[______________") || fin.fail())); + // the header's flags hold from the start, entry 0 keeps them for the stations to inherit + TimeTable[0].flags = Data.Flags; + auto activeradiochannel{-1}; + while (!fin.fail() && !EndTable) { + ++StationCount; + if (StationCount > MaxTTableSize) { + --StationCount; + conversionerror = timetable_too_long; + break; + } + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + TMTableEntry *record = &TimeTable[StationCount]; + { + if (s == "[") + fin >> s; + else + conversionerror = -4; + if (false == contains(s, "|")) { + record->km = static_cast(atof(s.c_str())); + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + fin >> record->StationName; + // get rid of non-ascii chars. TODO: run correct version based on locale + win1250_to_ascii(record->StationName); + do { + fin >> s; + } while (!(s == "1" || s == "2" || fin.fail())); + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Ah = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu + } + else { + record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (s.find("|_____|") != std::string::npos) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // stationware. added fix for empty entry + fin >> s; + while (false == (s == "1" || s == "2" || fin.fail())) { + record->StationWare += s; + fin >> s; + } + // cache relevant station data + record->is_maintenance = contains(s, "pt"); + // service flags (eu07/maszyna#95): the ones of the station before, changed by the ones given here + record->flags = TimeTable[StationCount - 1].flags; + record->StationWare = timetable::extract_flags(record->StationWare, record->flags); + { + auto const stationware{Split(record->StationWare, ',')}; + for (auto const &entry : stationware) { + if (entry.front() != 'R') { + continue; + } + auto const [entrytype, entrynumber]{split_string_and_number(entry)}; + if (entrytype == "R" && entrynumber <= 10) { + auto const radiochannel{entrynumber}; + if (record->radio_channel == -1 || radiochannel != activeradiochannel) { + // if the station has more than one radiochannel listed, + // it generally means we should switch to the one we weren't using so far + // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system + record->radio_channel = radiochannel; + } + } + } + if (record->radio_channel != -1) { + activeradiochannel = record->radio_channel; + } + } + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu + } + else { + record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + else { + record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) + record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(contains(s, "[") || fin.fail())); + if (false == contains(s, "_|_")) + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + while (false == contains(s, "]") && false == fin.fail()) + fin >> s; + if (contains(s, "_|_")) + EndTable = true; + } /*timetableline*/ + } + if (false == EndTable && conversionerror == 0) { + // the old reader went on reading past the end of the file here, forever + conversionerror = timetable_truncated; + } + } + } /*while eof*/ + return conversionerror; +} + +} // namespace Mtable diff --git a/world/timetablereader.h b/world/timetablereader.h new file mode 100644 index 000000000..aaf43e34c --- /dev/null +++ b/world/timetablereader.h @@ -0,0 +1,66 @@ +/* +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 "world/timetableflags.h" + +// the reader of the timetable files (.txt next to the scenery), without the parts of the engine the timetable +// of a running train needs (sounds, scenario time), so it can be tested on its own +namespace Mtable { + +static int const MaxTTableSize = 100; // można by to robić dynamicznie + +// one station of a timetable, as the file gives it +struct TMTableEntry { + float km{0.f}; // kilometraz linii + float vmax{-1.f}; // predkosc rozkladowa przed przystankiem + std::string StationName{"nowhere"}; // nazwa stacji ('_' zamiast spacji) + std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi + int TrackNo{1}; // ilosc torow szlakowych + int Ah{-1}; + float Am{-1.f}; // godz. i min. przyjazdu, -1 gdy bez postoju + int Dh{-1}; + float Dm{-1.f}; // godz. i min. odjazdu + float tm{0.f}; // czas jazdy do tej stacji w min. (z kolumny) + bool is_maintenance{false}; + int radio_channel{-1}; + // the service flags which hold from this station on: the header's, changed by this and the earlier stations. + // entry 0 holds the header's + timetable::service_flags flags; +}; + +// what a timetable file holds +struct timetable_data { + std::string TrainName; // the name the file is looked up by, then the one the file gives + std::string TrainCategory; + std::string TrainLabel; + std::string Relation1; + std::string Relation2; + double BrakeRatio{0.0}; + std::string LocSeries; + double LocLoad{0.0}; + timetable::service_flags Flags; // of the whole train, the row "Flagi" of the header + int StationCount{0}; // stations 1..StationCount, entry 0 is the technical one + std::array TimeTable; +}; + +// conversion errors of read_timetable, besides the ones it always had (-4: no station row where expected, -5: no +// first station of the relation) +int const timetable_truncated{-9}; // the file ends before the bottom line of the table (the reader used to hang) +int const timetable_too_long{-10}; // more stations than MaxTTableSize (the reader used to write past the table) + +// reads the timetable from Input into Data. returns the conversion error, 0 when read +int read_timetable(std::istream &Input, timetable_data &Data); + +} // namespace Mtable