From ac1ebd5426b7ac9926656c0dfea82008edd17bfc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:29:20 +0100 Subject: [PATCH] fix(simulation): every value of a snapshot file is checked before it's used A damaged or edited snapshot could put an index past a table, a count which takes forever or a number out of the range of its type into the simulation, and a file cut short was put back half way. - Reading a value: a whole number has to be whole and fit its type (an enum its underlying one), a float can't be past its largest value; what doesn't fit is refused. Every refusal names the entry, the key and the value, and goes to the log (errors.txt), up to 100 lines and a count. - Ranges: coupler ends 0 or 1 and the flags of a coupling; couplings which would close a ring of vehicles; the count of the points of a driver's table and of its point limits (not past the keys of the entry), the indices into the table (tablelast, semnext, semnextstop); the order stack and its position, the timetable station, the driver's enums and directions; the path, events and distance of an axle, facing and first axle; the date and time; switch states, made track ends, crossing segments, event siblings and times, launcher timers, the weather; the load (amount, and a name which isn't a path); the whole numbers inside number lists (flags of a table point, the stop of a coupler pair, the track flags under a vehicle, the fuse count of a power source, the cab of the vigilance device). - The positions of the controllers are brought within the ranges of the vehicle: master and secondary controller (set and actual), reverser, cabs, light, compressor and wiper switches, brake handle, hand brake, dimmer. - A document with problems isn't loaded unless --load-snapshot-force says so; a test run ends with the error code then. The header counts the entries, so a file cut between two entries is found too. A file of a newer version is a warning, not a problem. - A snapshot is written to .tmp and renamed over the file only when the stream didn't fail. - Unit tests of the reader on damaged input. --- application/application.cpp | 4 +- simulation/simulationsnapshot.cpp | 200 +++++++++++++- simulation/simulationsnapshot.h | 150 ++++++++++- simulation/simulationsnapshotdriver.cpp | 131 +++++++--- simulation/simulationsnapshotmover.cpp | 97 ++++++- simulation/simulationsnapshotvehicle.cpp | 28 +- simulation/simulationsnapshotworld.cpp | 198 +++++++++----- tests/scenarios/README.md | 13 +- tests/unit/test_snapshot.cpp | 320 ++++++++++++++++++++++- tests/unit/test_snapshot_vehicle.cpp | 69 +++++ 10 files changed, 1068 insertions(+), 142 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index 26778005a..7098e336a 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -1302,7 +1302,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // taken from the command line above, with its value ++i; } - else if (token == "--load-snapshot" || token == "--snapshot-at") + else if (token == "--load-snapshot" || token == "--snapshot-at" || token == "--load-snapshot-force") { // taken from the command line above, with their values i += simulation::snapshot::option_value_count(token); @@ -1325,7 +1325,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) << " [-seed number|word]" << " [-ini settingsfile]" << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" - << " [--load-snapshot file] [--snapshot-at seconds file]" << std::endl; + << " [--load-snapshot file [--load-snapshot-force]] [--snapshot-at seconds file]" << std::endl; simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } diff --git a/simulation/simulationsnapshot.cpp b/simulation/simulationsnapshot.cpp index 0990cac71..b32dcd45d 100644 --- a/simulation/simulationsnapshot.cpp +++ b/simulation/simulationsnapshot.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -202,6 +203,55 @@ coupler_link const *wanted_link(coupler_map const &Wanted, std::string const &Ve return lookup != Wanted.end() ? &lookup->second : nullptr; } +// the consists the links make, as sets of vehicles: two vehicles are of one consist if a chain of links joins them +class consists { + +public: + // joins the consists of the two vehicles. returns: false if they're of one consist already, which the link would + // make into a ring + bool join(std::string const &Left, std::string const &Right) + { + auto const left{root(Left)}; + auto const right{root(Right)}; + if (left == right) + return false; + m_parents[left] = right; + return true; + } + +private: + std::string root(std::string const &Vehicle) const + { + auto current{Vehicle}; + for (auto lookup{m_parents.find(current)}; lookup != m_parents.end(); lookup = m_parents.find(current)) + current = lookup->second; + return current; + } + + std::map> m_parents; +}; + +// what's refused is kept in the order it came, up to this many lines +constexpr std::size_t refusals_kept{100}; + +struct refusal_list { + std::vector lines; + std::size_t more{0}; +}; + +refusal_list &refusals() +{ + static refusal_list list; + return list; +} + +// a value of the file in what's told of it: a damaged file can have anything in a value, a whole other file too +std::string shortened(std::string_view const Text) +{ + constexpr std::size_t length{40}; + return Text.size() <= length ? std::string(Text) : std::string(Text.substr(0, length)) + "..."; +} + } // namespace std::string number_text(double const Value) @@ -252,6 +302,31 @@ std::string numbers_text(std::span const Numbers) return text; } +std::optional whole_number(double const Value, int const Min, int const Max) +{ + if (false == detail::fits_integer(Value) || Value < Min || Value > Max) + return std::nullopt; + return static_cast(Value); +} + +void refuse(std::string Text) +{ + auto &list{refusals()}; + if (list.lines.size() < refusals_kept) + list.lines.emplace_back(std::move(Text)); + else + ++list.more; +} + +std::vector take_refusals() +{ + auto list{std::move(refusals())}; + refusals() = {}; + if (list.more != 0) + list.lines.emplace_back(std::format("and {} more values refused", list.more)); + return std::move(list.lines); +} + std::vector text_numbers(std::string_view Text) { std::vector numbers; @@ -277,6 +352,11 @@ std::string record::text(std::string_view const Key, std::string_view const Fall return value != nullptr ? *value : std::string(Fallback); } +void record::refuse(std::string_view const Key, std::string_view const Why) const +{ + snapshot::refuse(std::format("{} {}: {} \"{}\" refused, {}", type, shortened(name), Key, shortened(text(Key)), Why)); +} + void record::set_text(std::string_view const Key, std::string Value) { if (auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; lookup != fields.end()) @@ -287,6 +367,26 @@ void record::set_text(std::string_view const Key, std::string Value) fields.emplace_back(std::string(Key), std::move(Value)); } +std::optional read_count(record const &Entry, std::string_view const Key) +{ + if (std::size_t count{0}; Entry.get(Key, count, std::size_t{0}, Entry.fields.size())) + return count; + return std::nullopt; +} + +std::optional read_index(record const &Entry, std::string_view const Key, std::size_t const Size) +{ + std::size_t index{0}; + if (false == Entry.get(Key, index)) + return std::nullopt; + if (index >= Size) + { + Entry.refuse(Key, std::format("it's past the end of a table of {}", Size)); + return std::nullopt; + } + return index; +} + record &document::add(std::string_view const Type, std::string_view const Name) { return records.emplace_back(Type, Name); @@ -325,8 +425,8 @@ int document::version() const auto const *first{header()}; if (first == nullptr) return 0; - auto const number{text_number(first->name)}; - return number.has_value() ? static_cast(*number) : 0; + // a version which isn't a whole number is no version this build knows + return whole_number(text_number(first->name).value_or(0.0), 0, std::numeric_limits::max()).value_or(0); } void write(std::ostream &Output, document const &Document) @@ -371,10 +471,23 @@ document read(cParser &Input) result.problems.emplace_back(std::move(problem)); type = next_token(Input); } - if (result.header() == nullptr) + auto const *header{result.header()}; + if (header == nullptr) + { result.problems.emplace_back("the file doesn't start with a \"snapshot\" entry"); - else if (result.version() > format_version) - result.problems.emplace_back(std::format("the file is of version {}, newer than {} which this build writes", result.version(), format_version)); + return result; + } + if (result.version() > format_version) + result.warnings.emplace_back(std::format("the file is of version {}, newer than {} which this build writes", result.version(), format_version)); + // the header counts the entries of the file: a file cut short between two entries reads without a fault otherwise + if (auto const *entries{header->find("entries")}; entries != nullptr) + { + if (auto const count{text_number(*entries)}; false == count.has_value() || *count != static_cast(result.records.size())) + { + result.problems.emplace_back(std::format("the header says the file has {} entries, it has {}: it's cut short, or it was put together from pieces", + shortened(*entries), result.records.size())); + } + } return result; } @@ -384,6 +497,43 @@ document parse(std::string const &Text) return read(parser); } +bool accepted(document const &Document, bool const Force) +{ + return Document.header() != nullptr && (Document.problems.empty() || Force); +} + +std::string write_file(std::string const &File, std::function const &Writer) +{ + auto const temporary{File + ".tmp"}; + std::error_code error; + { + std::ofstream output{temporary, std::ios::binary | std::ios::trunc}; + if (false == output.is_open()) + return std::format("file \"{}\" can't be written", temporary); + Writer(output); + output.flush(); + output.close(); + if (output.fail()) + { + std::filesystem::remove(temporary, error); + return std::format("writing file \"{}\" failed", temporary); + } + } + // the whole text is there: it takes the place of the file at once + std::filesystem::rename(temporary, File, error); + if (error) + { + std::filesystem::remove(temporary, error); + return std::format("file \"{}\" can't be put in place of \"{}\"", temporary, File); + } + return {}; +} + +std::string write_file(std::string const &File, document const &Document) +{ + return write_file(File, [&Document](std::ostream &Output) { write(Output, Document); }); +} + document load(std::string const &File) { std::ifstream input(File, std::ios::binary); @@ -454,7 +604,11 @@ command_line parse_command_line(std::span const Arguments) std::string_view const option{Arguments[index]}; auto const values{static_cast(option_value_count(option))}; auto const complete{index + values < Arguments.size()}; - if (option == "--load-snapshot") + if (option == "--load-snapshot-force") + { + result.force = true; + } + else if (option == "--load-snapshot") { if (complete) result.load = Arguments[index + 1]; @@ -510,7 +664,41 @@ coupling_plan plan_couplings(std::vector const &Current, std::vec continue; plan.join.emplace_back(link); } + // the links which stay and the ones to make mustn't close a ring of vehicles + consists joined; + for (auto const &link : unique_links(Current)) + { + if (std::ranges::find(plan.part, link) == plan.part.end()) + joined.join(link.vehicle, link.other); + } + std::erase_if(plan.join, [&](coupling_link const &Link) { + if (Link.vehicle != Link.other && joined.join(Link.vehicle, Link.other)) + return false; + plan.refused.emplace_back(Link); + return true; + }); return plan; } +std::vector read_couplings(std::vector const &Entries) +{ + std::vector links; + for (auto const *entry : Entries) + { + for (auto const side : {0, 1}) + { + auto const key{std::format("coupler{}", side)}; + if (false == entry->has(key + "flags")) + continue; + // the end of the coupler on the other side is the index of one of the two couplers of a vehicle + auto otherend{0}; + auto flags{0}; + if (false == entry->get(key + "end", otherend, 0, 1) || false == entry->get(key + "flags", flags, 0, coupling_flags_mask)) + continue; + links.emplace_back(entry->name, side, entry->text(key), otherend, flags); + } + } + return links; +} + } // namespace simulation::snapshot diff --git a/simulation/simulationsnapshot.h b/simulation/simulationsnapshot.h index 36588e7a9..1adcb7358 100644 --- a/simulation/simulationsnapshot.h +++ b/simulation/simulationsnapshot.h @@ -10,10 +10,13 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include #include +#include #include +#include #include #include #include @@ -44,6 +47,18 @@ std::optional text_number(std::string_view Text); // a few numbers as one value, with commas between them, and back; what isn't a number is left out std::string numbers_text(std::span Numbers); std::vector text_numbers(std::string_view Text); +// a number of the file as a whole number between Min and Max. returns: empty if it isn't one (not finite, a fraction, +// out of the range) +std::optional whole_number(double Value, int Min, int Max); + +// the values of the file the reader doesn't take: a number out of the range of what it's put into, a count past what +// the entry can hold, a text where a number is needed. a snapshot from a damaged or edited file mustn't put an index +// past the end of a table nor a count which takes forever, so each such value is left out (or brought into its range, +// where that's said) and told of here; the simulation collects them while a snapshot is put back, for the log +void refuse(std::string Text); +// the refusals told of since the last call, in their order. a damaged file can give a great many: past the first +// hundred only their number is kept, given as the last line +std::vector take_refusals(); // one entry of a snapshot: " ... end". the values are single tokens, // kept as text in the order of the file, so an entry read and written back comes out the same, whatever it holds @@ -59,11 +74,20 @@ public: std::string const *find(std::string_view Key) const; bool has(std::string_view Key) const { return find(Key) != nullptr; } // the value of the key in the type of Target, which stays as it is when the entry has no such key or the value - // can't be read as that type. returns: true if Target was set + // can't be read as that type (a whole number for a whole one, within the range of the type). a value which can't + // be read is refused (refuse()). returns: true if Target was set template bool get(std::string_view Key, Type_ &Target) const; + // the same, for a value which has to be between Min and Max: one past them is refused + template bool get(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const; + // the same, but a value past Min or Max is brought to it, and that's told of (refuse()) + template bool get_clamped(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const; // the value of the key, or Fallback template Type_ value(std::string_view Key, Type_ Fallback) const; + // the value of the key between Min and Max, or Fallback + template Type_ value(std::string_view Key, Type_ Fallback, Type_ Min, Type_ Max) const; std::string text(std::string_view Key, std::string_view Fallback = {}) const; + // tells of a value of the entry the reader didn't take, and why (refuse()) + void refuse(std::string_view Key, std::string_view Why) const; bool operator==(record const &) const = default; @@ -75,11 +99,22 @@ private: void set_text(std::string_view Key, std::string Value); }; +// a count the entry gives of things it lists, each under a key of its own (the points of a table of a driver: "table" +// and "p0", "p1"...): a count past the number of keys of the entry can't be the count of what it lists, and is refused, +// as is one which isn't a whole number. returns: empty if the entry hasn't the key or its value is refused +std::optional read_count(record const &Entry, std::string_view Key); +// an index the entry gives into a table of Size things: one past the end of the table is refused. +// returns: empty if the entry hasn't the key or its value is refused +std::optional read_index(record const &Entry, std::string_view Key, std::size_t Size); + // the whole file: the entries in their order. the first one is the header, "snapshot ... endsnapshot" struct document { std::vector records; - // what the reader couldn't make sense of; a document with problems may still be of use + // what the reader couldn't make sense of: the file is damaged or cut short. a document with problems isn't put + // over a scenery unless that's forced (accepted()) std::vector problems; + // what a reader should know, but which doesn't keep the document from being used: a file of a newer version + std::vector warnings; record &add(std::string_view Type, std::string_view Name); // the entries of the type, in the order of the file @@ -101,6 +136,14 @@ document read(cParser &Input); document parse(std::string const &Text); // reads the file; a file which can't be opened gives a document with that as its problem document load(std::string const &File); +// whether the document is to be put over the scenery: it has to start with a header, and to have no problems unless +// Force says to use what could be read of it all the same (--load-snapshot-force) +bool accepted(document const &Document, bool Force); +// writes the text Writer gives to the file, whole or not at all: to ".tmp" first, which takes the place of the +// file only once it's all written. a write which fails leaves the file as it was, and no .tmp behind. +// returns: what went wrong, empty if nothing did +std::string write_file(std::string const &File, std::function const &Writer); +std::string write_file(std::string const &File, document const &Document); // a thing of the scenery is named in a snapshot by its name where it has one of its own, which is the one the tables // of the simulation find it by, and by its place in the table otherwise ("#12"): the tables are filled in the order @@ -124,6 +167,10 @@ private: std::uint64_t m_hash{14695981039346656037ULL}; }; +// the flags of a coupling a snapshot can give: every bit of the coupling enum of the physics (MOVER.h), from coupler +// (0x1) to power3x400v (0x400) +inline constexpr int coupling_flags_mask{0x7ff}; + // what the vehicles of a snapshot are coupled to: for a vehicle and its end (0 front, 1 rear) the vehicle and the end // on the other side, and the coupling::flags of what's joined struct coupling_link { @@ -145,11 +192,18 @@ struct coupling_plan { std::vector change; // the links of the snapshot to vehicles which aren't in Present std::vector missing; + // the links of the snapshot which would close a ring of vehicles (a vehicle coupled to itself, or the last vehicle + // of a consist to its first): a consist is a line, and the code which walks along one would never get to its end + std::vector refused; }; // Current: the links as they are, each given from both of its ends or from one. Wanted: the same for the snapshot. // Present: the names of the vehicles of the scenery. links of vehicles the snapshot says nothing of stay as they are, // unless a vehicle of the snapshot needs the coupler at their other end coupling_plan plan_couplings(std::vector const &Current, std::vector const &Wanted, std::vector const &Present); +// the couplings of the vehicle entries ("coupler0", "coupler0end", "coupler0flags" and the same for 1), for +// plan_couplings(). an end other than 0 or 1, or flags which aren't those of a coupling, are refused (refuse()): that +// coupler is left out, as if the entry said nothing of it +std::vector read_couplings(std::vector const &Entries); // the snapshots asked for on the command line of the simulator struct command_line { @@ -158,6 +212,7 @@ struct command_line { std::string file; }; std::string load; // --load-snapshot : put over the scenery once it's loaded + bool force{false}; // --load-snapshot-force: a damaged file is put over the scenery as far as it could be read std::vector saves; // --snapshot-at , any number of them: written when the time comes std::string error; // what's wrong with the options; empty if nothing }; @@ -188,6 +243,17 @@ template std::string value_text(Type_ const &Value) return std::string(std::string_view(Value)); } +// whether the number fits a variable of the integer type: whole, and within its range +template bool fits_integer(double const Number) +{ + using limits = std::numeric_limits; + // the bounds as exact doubles: -2^63 .. 2^63 for a 64 bit signed type, 0 .. 2^64 for an unsigned one; the upper one + // is past the range + auto const lowest{limits::is_signed ? -std::ldexp(1.0, limits::digits) : 0.0}; + auto const past{std::ldexp(1.0, limits::digits)}; + return std::isfinite(Number) && std::trunc(Number) == Number && Number >= lowest && Number < past; +} + template bool text_value(std::string const &Text, Type_ &Target) { using type = std::remove_cvref_t; @@ -202,13 +268,42 @@ template bool text_value(std::string const &Text, Type_ &Target if (false == number.has_value()) return false; if constexpr (std::is_same_v) + { + if (std::isnan(*number)) + return false; Target = *number != 0.0; + } + else if constexpr (std::is_enum_v || std::is_integral_v) + { + // an integer out of the range of its type is undefined, a fraction isn't what was written + using integer = typename std::conditional_t, std::underlying_type, std::type_identity>::type; + if (false == fits_integer(*number)) + return false; + Target = static_cast(static_cast(*number)); + } else + { + // not a number and the infinities are values like any other, a finite number too big for the type isn't: one + // which rounds past its largest value + auto const top{static_cast(std::numeric_limits::max())}; + auto const step{top - static_cast(std::nextafter(std::numeric_limits::max(), type{0}))}; + if (std::isfinite(*number) && std::abs(*number) >= top + step / 2) + return false; Target = static_cast(*number); + } return true; } } +// the text of a bound, for what's told of a value out of its range +template std::string bound_text(Type_ const Value) +{ + if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else + return value_text(Value); +} + } // namespace detail template record &record::set(std::string_view const Key, Type_ const &Value) @@ -220,7 +315,50 @@ template record &record::set(std::string_view const Key, Type_ template bool record::get(std::string_view const Key, Type_ &Target) const { auto const *text{find(Key)}; - return text != nullptr && detail::text_value(*text, Target); + if (text == nullptr) + return false; + if (detail::text_value(*text, Target)) + return true; + refuse(Key, "it can't be read as a value of its kind"); + return false; +} + +template bool record::get(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const +{ + auto value{Target}; + if (false == get(Key, value)) + return false; + // written so that not a number fails too + if (false == (value >= Min && value <= Max)) + { + refuse(Key, std::format("it's out of the range {} .. {}", detail::bound_text(Min), detail::bound_text(Max))); + return false; + } + Target = value; + return true; +} + +template bool record::get_clamped(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const +{ + auto value{Target}; + if (false == get(Key, value)) + return false; + if constexpr (std::is_floating_point_v) + { + if (std::isnan(value)) + { + refuse(Key, "it's not a number"); + return false; + } + } + if (value < Min || value > Max) + { + auto const clamped{value < Min ? Min : Max}; + refuse(Key, std::format("it's out of the range {} .. {}, {} is taken", detail::bound_text(Min), detail::bound_text(Max), detail::bound_text(clamped))); + value = clamped; + } + Target = value; + return true; } template Type_ record::value(std::string_view const Key, Type_ Fallback) const @@ -229,4 +367,10 @@ template Type_ record::value(std::string_view const Key, Type_ return Fallback; } +template Type_ record::value(std::string_view const Key, Type_ Fallback, Type_ const Min, Type_ const Max) const +{ + get(Key, Fallback, Min, Max); + return Fallback; +} + } // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotdriver.cpp b/simulation/simulationsnapshotdriver.cpp index f8461dcb5..9a86bae5e 100644 --- a/simulation/simulationsnapshotdriver.cpp +++ b/simulation/simulationsnapshotdriver.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include // the part of a simulation snapshot kept by the driver of a train (TController): the orders it has and which one it's @@ -28,10 +29,27 @@ namespace { namespace snapshot = simulation::snapshot; -// a variable of the driver kept under a key of the entry +// a variable of the driver kept under a key of the entry, and for a number the range a value of the file has to be in template struct member { std::string_view key; Type_ TController::*variable; + Type_ min{lowest()}; + Type_ max{highest()}; + + static constexpr Type_ lowest() + { + if constexpr (std::is_arithmetic_v) + return std::numeric_limits::lowest(); + else + return Type_{}; + } + static constexpr Type_ highest() + { + if constexpr (std::is_arithmetic_v) + return std::numeric_limits::max(); + else + return Type_{}; + } }; template void save_members(snapshot::record &Entry, TController const &Driver, Table_ const &Table) @@ -43,9 +61,20 @@ template void save_members(snapshot::record &Entry, TControlle template void load_members(TController &Driver, snapshot::record const &Entry, Table_ const &Table) { for (auto const &item : Table) - Entry.get(item.key, Driver.*(item.variable)); + { + // the whole numbers in their ranges; a number of another kind is a measure, which can be anything + if constexpr (std::is_integral_v && false == std::is_same_v) + Entry.get(item.key, Driver.*(item.variable), item.min, item.max); + else + Entry.get(item.key, Driver.*(item.variable)); + } } +// the most events sharing a name a snapshot looks among +constexpr int most_siblings{100000}; +// every order the driver knows, as bits (TOrders) +constexpr int every_order{(Jump_to_first_order << 1) - 1}; + // the orders as their numbers joined with commas: "1,128,16,32" std::string join(std::span const Orders) { @@ -59,14 +88,18 @@ std::string join(std::span const Orders) return text; } -std::vector split(std::string_view Text) +// the whole numbers of a list between Min and Max. returns: empty if one of them isn't such a number +std::optional> split(std::string_view Text, int const Min, int const Max) { std::vector numbers; while (false == Text.empty()) { auto const comma{Text.find(',')}; - if (auto const number{snapshot::text_number(Text.substr(0, comma))}; number.has_value()) - numbers.emplace_back(static_cast(*number)); + auto const number{snapshot::text_number(Text.substr(0, comma))}; + auto const whole{number.has_value() ? snapshot::whole_number(*number, Min, Max) : std::nullopt}; + if (false == whole.has_value()) + return std::nullopt; + numbers.emplace_back(*whole); Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); } return numbers; @@ -85,7 +118,10 @@ void save_event(snapshot::record &Entry, std::string const &Key, basic_event con basic_event *load_event(snapshot::record const &Entry, std::string const &Key) { auto const name{Entry.text(Key)}; - return name.empty() ? nullptr : snapshot::find_event(name, Entry.value(Key + "sibling", 0)); + auto sibling{0}; + if (name.empty() || (false == Entry.get(Key + "sibling", sibling, 0, most_siblings) && Entry.has(Key + "sibling"))) + return nullptr; + return snapshot::find_event(name, sibling); } // a point of the table of what's ahead: its numbers under "", its track and its event beside them @@ -105,11 +141,18 @@ bool load_point(snapshot::record const &Entry, std::string const &Key, TSpeedPos auto const numbers{snapshot::text_numbers(Entry.text(Key))}; if (numbers.size() != 10) return false; + // the flags of a point are bits of a whole number + auto const flags{snapshot::whole_number(numbers[4], std::numeric_limits::min(), std::numeric_limits::max())}; + if (false == flags.has_value()) + { + Entry.refuse(Key, "its flags aren't a whole number"); + return false; + } Point.fDist = numbers[0]; Point.fVelNext = numbers[1]; Point.fSectionVelocityDist = numbers[2]; Point.fPointDist = numbers[3]; - Point.iFlags = static_cast(numbers[4]); + Point.iFlags = *flags; Point.bMoved = numbers[5] != 0.0; Point.fMoved = numbers[6]; Point.vPos = {numbers[7], numbers[8], numbers[9]}; @@ -203,8 +246,8 @@ struct TController::snapshot_members { }; static constexpr std::array numbers{ member{"flags", &TController::iDrivigFlags}, - member{"direction", &TController::iDirection}, - member{"directionorder", &TController::iDirectionOrder}, + member{"direction", &TController::iDirection, -1, 1}, + member{"directionorder", &TController::iDirectionOrder, -1, 1}, member{"vehiclecount", &TController::iVehicleCount}, member{"coupler", &TController::iCoupler}, member{"failcount", &TController::iDriverFailCount}, @@ -337,26 +380,34 @@ bool TController::snapshot_load_table(simulation::snapshot::record const &Entry) TableClear(); m_pointlimits.clear(); m_pointlimitsvehicle = nullptr; - std::size_t count{0}; - if (false == Entry.get("table", count)) + // each point of the table has a key of its own: a count past the keys of the entry can't be the count of its points + auto const points{snapshot::read_count(Entry, "table")}; + if (false == points.has_value()) return false; + auto const count{*points}; std::vector table(count); for (std::size_t index{0}; index < count; ++index) { if (false == load_point(Entry, std::format("p{}", index), table[index])) return false; } + // the indices into the table point at one of its points, or at none (-1 and npos, which the entry doesn't write) + auto last{-1}; + auto const next{snapshot::read_index(Entry, "semnext", count)}; + auto const nextstop{snapshot::read_index(Entry, "semnextstop", count)}; + if ((false == Entry.get("tablelast", last, -1, static_cast(count) - 1) && Entry.has("tablelast")) || (false == next.has_value() && Entry.has("semnext")) || + (false == nextstop.has_value() && Entry.has("semnextstop"))) + return false; sSpeedTable = std::move(table); - Entry.get("tablelast", iLast); - Entry.get("tabledirection", iTableDirection); + iLast = last; + Entry.get("tabledirection", iTableDirection, -1, 1); Entry.get("tablelastvel", fLastVel); tLast = snapshot::find_track(Entry.text("tablelasttrack")); - SemNextIndex = Entry.value("semnext", npos); - SemNextStopIndex = Entry.value("semnextstop", npos); + SemNextIndex = next.value_or(npos); + SemNextStopIndex = nextstop.value_or(npos); eSignNext = load_event(Entry, "signnext"); - std::size_t limits{0}; - Entry.get("limits", limits); + auto const limits{snapshot::read_count(Entry, "limits").value_or(0)}; for (std::size_t index{0}; index < limits; ++index) { auto const key{std::format("l{}", index)}; @@ -393,14 +444,16 @@ void TController::snapshot_load(simulation::snapshot::record const &Entry) if (train != "none" && false == TrainParams.LoadTTfile(Global.asCurrentSceneryPath, 0, Entry.value("ttvmax", 0.0))) ErrorLog(std::format("snapshot: timetable \"{}\" of {} can't be loaded", train, OwnerName())); } - Entry.get("station", TrainParams.StationIndex); - Entry.get("stationstart", TrainParams.StationStart); + // the stations are entries of the table of the timetable, 1..StationCount, and the one after the last + auto const laststation{std::clamp(TrainParams.StationCount + 1, 0, MaxTTableSize)}; + Entry.get("station", TrainParams.StationIndex, 0, laststation); + Entry.get("stationstart", TrainParams.StationStart, 0, laststation); Entry.get("nextstation", TrainParams.NextStationName); Entry.get("latency", TrainParams.LastStationLatency); - Entry.get("timetabledirection", TrainParams.Direction); + Entry.get("timetabledirection", TrainParams.Direction, -1, 1); Entry.get("ttvmax", TrainParams.TTVmax); m_stopflags = TrainParams.stop_flags(); - if (auto const stopflags{split(Entry.text("stopflags"))}; stopflags.size() == 4) + if (auto const stopflags{split(Entry.text("stopflags"), 0, static_cast(timetable::tristate::no)).value_or(std::vector{})}; stopflags.size() == 4) { using timetable::tristate; m_stopflags.central_doors = static_cast(stopflags[0]); @@ -413,16 +466,22 @@ void TController::snapshot_load(simulation::snapshot::record const &Entry) // the orders if (Entry.has("orders")) { - auto const orders{split(Entry.text("orders"))}; - OrdersClear(); - OrderTop = std::min(static_cast(orders.size()), maxorders); - for (auto index{0}; index < OrderTop; ++index) - OrderList[index] = static_cast(orders[index]); + // the orders are bits, and the stack holds so many of them + if (auto const orders{split(Entry.text("orders"), 0, every_order)}; orders.has_value() && orders->size() <= static_cast(maxorders)) + { + OrdersClear(); + OrderTop = static_cast(orders->size()); + for (auto index{0}; index < OrderTop; ++index) + OrderList[index] = static_cast((*orders)[index]); + } + else + Entry.refuse("orders", std::format("they aren't up to {} numbers of orders", maxorders)); } - Entry.get("orderpos", OrderPos); + // the order the driver is on is an index into the stack + Entry.get("orderpos", OrderPos, 0, maxorders - 1); - Entry.get("action", eAction); - Entry.get("stopreason", eStopReason); + Entry.get("action", eAction, TAction::actUnknown, TAction::actTrial); + Entry.get("stopreason", eStopReason, stopNone, stopError); load_members(*this, Entry, snapshot_members::numbers); load_members(*this, Entry, snapshot_members::flags); load_members(*this, Entry, snapshot_members::speeds); @@ -434,19 +493,23 @@ void TController::snapshot_load(simulation::snapshot::record const &Entry) std::ranges::copy(numbers, fBrake_a0); if (auto const numbers{snapshot::text_numbers(Entry.text("brakea1"))}; numbers.size() == std::size(fBrake_a1)) std::ranges::copy(numbers, fBrake_a1); - Entry.get("brakesystem", BrakeSystem); - Entry.get("doorclosure", DoorClosure); - Entry.get("lastannouncement", m_lastannouncement); + Entry.get("brakesystem", BrakeSystem, TBrakeSystem::Individual, TBrakeSystem::ElectroPneumatic); + Entry.get("doorclosure", DoorClosure, door_closure_t::none, door_closure_t::open); + Entry.get("lastannouncement", m_lastannouncement, announcement_t::idle, announcement_t::end); Entry.get("vellimitlastdist0", VelLimitLastDist.first); Entry.get("vellimitlastdist1", VelLimitLastDist.second); Entry.get("lighthint0", m_lighthints[end::front]); Entry.get("lighthint1", m_lighthints[end::rear]); iDirectionBackup.reset(); - if (auto direction{0}; Entry.get("directionbackup", direction)) + if (auto direction{0}; Entry.get("directionbackup", direction, -1, 1)) iDirectionBackup = direction; iCouplingVehicle.reset(); + // the end of the vehicle to couple to is one of its two couplers if (auto *vehicle{snapshot::find_vehicle(Entry.text("couplingvehicle"))}; vehicle != nullptr) - iCouplingVehicle = std::make_pair(vehicle, Entry.value("couplingend", 0)); + { + if (auto end{0}; Entry.get("couplingend", end, 0, 1) || false == Entry.has("couplingend")) + iCouplingVehicle = std::make_pair(vehicle, end); + } // the consist: its ends as they were, the vehicles driven and braked found anew among what's coupled now if (auto *front{snapshot::find_vehicle(Entry.text("front"))}; front != nullptr) diff --git a/simulation/simulationsnapshotmover.cpp b/simulation/simulationsnapshotmover.cpp index 877c11651..ca9810a1f 100644 --- a/simulation/simulationsnapshotmover.cpp +++ b/simulation/simulationsnapshotmover.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include namespace simulation::snapshot { @@ -253,6 +255,43 @@ template void apply_members(TMoverParameters &Mover, record co Entry.get(item.key, Mover.*(item.variable)); } +// the positions a controller or a switch of the vehicle can take. they index tables of the vehicle (the resistors of +// the start by the master controller, the settings of the compressor, the lights, the wipers), so a position of the +// file past them is brought within them: a file edited by hand, or a vehicle definition with fewer positions since +std::pair position_range(TMoverParameters const &Mover, std::string_view const Key) +{ + if (Key == "mainctrl") + return {0, std::clamp(Mover.MainCtrlPosNo, 0, ResArraySize)}; + if (Key == "mainctrlactual") + return {0, std::clamp(std::max(Mover.MainCtrlPosNo, Mover.RlistSize), 0, ResArraySize - 1)}; + if (Key == "scndctrl" || Key == "scndctrlactual") + return {0, std::max(Mover.ScndCtrlPosNo, 0)}; + if (Key == "diractive" || Key == "dirabsolute" || Key == "cabactive" || Key == "caboccupied") + return {-1, 1}; + if (Key == "lightspos") + return {0, std::clamp(Mover.LightsPosNo, 0, static_cast(std::size(Mover.Lights[0])))}; + if (Key == "compressorlistpos") + return {0, std::clamp(Mover.CompressorListPosNo, 0, static_cast(std::size(Mover.CompressorList[0])) - 1)}; + if (Key == "wiperswitchpos") + return {0, static_cast(std::size(Mover.WiperList)) - 1}; + if (Key == "brakectrl") + return {-2, std::max(Mover.BrakeCtrlPosNo, 0)}; + if (Key == "manualbrake") + return {0, ManualBrakePosNo}; + if (Key == "dimmer") + return {0, std::max(static_cast(Mover.dimPositions.size()) - 1, 0)}; + return {std::numeric_limits::min(), std::numeric_limits::max()}; +} + +void apply_positions(TMoverParameters &Mover, record const &Entry) +{ + for (auto const &item : positions) + { + auto const [lowest, highest]{position_range(Mover, item.key)}; + Entry.get_clamped(item.key, Mover.*(item.variable), lowest, highest); + } +} + // keys of the parts a vehicle has two of, or a few: "pant0valve", "door1open" std::string indexed(std::string_view const Part, int const Index, std::string_view const Key) { @@ -346,7 +385,13 @@ void apply_power(TMoverParameters &Mover, record const &Entry) } } if (Entry.has("security")) - Mover.SecuritySystem.state(text_numbers(Entry.text("security"))); + { + // the last one is the cab it watches + if (auto const state{text_numbers(Entry.text("security"))}; false == state.empty() && whole_number(state.back(), -1, 1).has_value()) + Mover.SecuritySystem.state(state); + else + Entry.refuse("security", "its cab isn't -1, 0 or 1"); + } if (auto const drive{text_numbers(Entry.text("eimv"))}; drive.size() == std::size(Mover.eimv)) std::ranges::copy(drive, std::begin(Mover.eimv)); auto &control{Mover.SpeedCtrlUnit}; @@ -680,7 +725,7 @@ void apply_brake(TMoverParameters &Mover, record const &Entry) Mover.Pipe2->CreatePress(Mover.ScndPipePress); Mover.Pipe2->Act(); } - if (auto setting{Mover.LoadFlag}; Entry.get("brakeload", setting)) + if (auto setting{Mover.LoadFlag}; Entry.get("brakeload", setting, 0, 3)) { // by the steps of the lever, which change the ratio of the rigging with it auto moved{true}; @@ -708,7 +753,19 @@ void apply_load(TMoverParameters &Mover, record const &Entry) { auto amount{Mover.LoadAmount}; auto name{Mover.LoadType.name}; - auto const given{Entry.get("load", amount)}; + // the share of the load shown is worked out from it: what can be read as a load, up to a thousand times what the + // vehicle is rated for + auto const most{1000.f * std::max(Mover.MaxLoad, 1.f)}; + auto const given{Entry.get("load", amount, 0.f, most)}; + if (Entry.has("load") && false == given) + return; + // the name of the load is that of its model, looked up in the folder of the vehicle + if (auto const *text{Entry.find("loadtype")}; + text != nullptr && (text->find_first_of("/\\:") != std::string::npos || text->find("..") != std::string::npos)) + { + Entry.refuse("loadtype", "a load is named by a name, not by a path"); + return; + } if (false == Entry.get("loadtype", name) && false == given) return; if (amount == Mover.LoadAmount && name == Mover.LoadType.name) @@ -771,13 +828,23 @@ void apply_running(TMoverParameters &Mover, record const &Entry) } if (auto const numbers{text_numbers(Entry.text("runningtrack"))}; numbers.size() == 6) { - auto &track{Mover.RunningTrack}; - track.Width = numbers[0]; - track.friction = numbers[1]; - track.CategoryFlag = static_cast(numbers[2]); - track.QualityFlag = static_cast(numbers[3]); - track.DamageFlag = static_cast(numbers[4]); - track.Velmax = numbers[5]; + constexpr auto lowest{std::numeric_limits::min()}; + constexpr auto highest{std::numeric_limits::max()}; + auto const category{whole_number(numbers[2], lowest, highest)}; + auto const quality{whole_number(numbers[3], lowest, highest)}; + auto const damage{whole_number(numbers[4], lowest, highest)}; + if (category.has_value() && quality.has_value() && damage.has_value()) + { + auto &track{Mover.RunningTrack}; + track.Width = numbers[0]; + track.friction = numbers[1]; + track.CategoryFlag = *category; + track.QualityFlag = *quality; + track.DamageFlag = *damage; + track.Velmax = numbers[5]; + } + else + Entry.refuse("runningtrack", "its flags aren't whole numbers"); } if (auto const numbers{text_numbers(Entry.text("loc"))}; numbers.size() == 3) Mover.Loc = {numbers[0], numbers[1], numbers[2]}; @@ -814,6 +881,12 @@ void apply_couplers(TMoverParameters &Mover, record const &Entry) auto const values{text_numbers(Entry.text(indexed("couplerstate", side, "")))}; if (values.size() != 17) continue; + auto const stop{whole_number(values[15], std::numeric_limits::min(), std::numeric_limits::max())}; + if (false == stop.has_value()) + { + Entry.refuse(indexed("couplerstate", side, ""), "the stop of the pair isn't a whole number"); + continue; + } auto &coupler{Mover.Couplers[side]}; auto &pair{coupler.physics_state}; coupler.CForce = values[0]; @@ -831,7 +904,7 @@ void apply_couplers(TMoverParameters &Mover, record const &Entry) pair.buffers.deflection = values[12]; pair.elongation = values[13]; pair.gap = values[14]; - pair.stop = static_cast(values[15]); + pair.stop = *stop; pair.stop_force = values[16]; } } @@ -861,7 +934,7 @@ void apply_mover(TMoverParameters &Mover, record const &Entry) apply_load(Mover, Entry); apply_members(Mover, Entry, motion); apply_members(Mover, Entry, forces); - apply_members(Mover, Entry, positions); + apply_positions(Mover, Entry); apply_members(Mover, Entry, levels); apply_members(Mover, Entry, switches); apply_members(Mover, Entry, relays); diff --git a/simulation/simulationsnapshotvehicle.cpp b/simulation/simulationsnapshotvehicle.cpp index 6b2e044fc..bcfa2fdf6 100644 --- a/simulation/simulationsnapshotvehicle.cpp +++ b/simulation/simulationsnapshotvehicle.cpp @@ -63,14 +63,19 @@ struct axle_place { } }; +// returns: the place, without its track if the entry doesn't give one which can be used axle_place read_axle(snapshot::record const &Entry, int const Index) { axle_place place; place.track = snapshot::find_track(Entry.text(indexed("track", Index))); - Entry.get(indexed("path", Index), place.path); - Entry.get(indexed("at", Index), place.distance); - Entry.get(indexed("dir", Index), place.direction); - Entry.get(indexed("events", Index), place.events); + // the path is a segment of a switch (0, 1) or of a crossing (1..6, the sign the way through it), the events two + // pairs of flags. the axle is put at a distance along its track, which has to be a number + auto const usable{(Entry.get(indexed("path", Index), place.path, -6, 6) || false == Entry.has(indexed("path", Index))) && + (Entry.get(indexed("at", Index), place.distance, -1e7, 1e7) || false == Entry.has(indexed("at", Index))) && + (Entry.get(indexed("dir", Index), place.direction, -1e7, 1e7) || false == Entry.has(indexed("dir", Index))) && + (Entry.get(indexed("events", Index), place.events, 0, 15) || false == Entry.has(indexed("events", Index)))}; + if (false == usable) + place.track = nullptr; return place; } @@ -172,11 +177,13 @@ void load_machinery(TDynamicObject &Vehicle, snapshot::record const &Entry) } auto &exchange{Vehicle.m_exchange}; exchange = {}; - Entry.get("exchangeunload", exchange.unload_count); - Entry.get("exchangeload", exchange.load_count); + // the counts of the passengers getting off and on are counted down step by step + constexpr auto most_passengers{1e6f}; + Entry.get("exchangeunload", exchange.unload_count, -most_passengers, most_passengers); + Entry.get("exchangeload", exchange.load_count, -most_passengers, most_passengers); Entry.get("exchangeplatforms", exchange.platforms); Entry.get("exchangetime", exchange.time); - Entry.get("raillength", Vehicle.dRailLength); + Entry.get("raillength", Vehicle.dRailLength, -1.0, 1e6); if (auto const joints{snapshot::text_numbers(Entry.text("railjoints"))}; joints.size() == 2 * Vehicle.m_axlesounds.size()) { for (std::size_t index{0}; index < Vehicle.m_axlesounds.size(); ++index) @@ -195,7 +202,7 @@ void load_machinery(TDynamicObject &Vehicle, snapshot::record const &Entry) Entry.get("highbeamlights", Vehicle.HighBeamLights); Entry.get("headlightsaoff", Vehicle.HeadlightsAoff); Entry.get("headlightsboff", Vehicle.HeadlightsBoff); - Vehicle.MED_oldFED = Entry.value("medoldfed", 0.0); + Vehicle.MED_oldFED = Entry.value("medoldfed", 0.0, -1e9, 1e9); } } // namespace @@ -252,7 +259,8 @@ bool TDynamicObject::snapshot_place(simulation::snapshot::record const &Entry) if (places[0].track == nullptr || places[1].track == nullptr) return false; - Entry.get("facing", iDirection); + // which of the ends of the vehicle leads in its consist, which of its axles is the first: 0 or 1 + Entry.get("facing", iDirection, 0, 1); // the axles a hair off the ends of their tracks first, for the body of the vehicle to be worked out from them: // Move() does that, and takes an axle standing at the very end of a track over to the next one constexpr double inset{1e-6}; @@ -263,7 +271,7 @@ bool TDynamicObject::snapshot_place(simulation::snapshot::record const &Entry) // then exactly where they were places[0].put(Axle0, 0.0); places[1].put(Axle1, 0.0); - Entry.get("first", iAxleFirst); + Entry.get("first", iAxleFirst, 0, 1); // the vehicle is on the list of the track its leading axle is on if (auto *track{iAxleFirst != 0 ? Axle1.GetTrack() : Axle0.GetTrack()}; track != MyTrack) diff --git a/simulation/simulationsnapshotworld.cpp b/simulation/simulationsnapshotworld.cpp index 2bad43d91..0a520ae86 100644 --- a/simulation/simulationsnapshotworld.cpp +++ b/simulation/simulationsnapshotworld.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "simulation/simulation.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" #include "simulation/simulationtime.h" #include "utilities/Globals.h" #include "utilities/Logs.h" @@ -42,6 +43,11 @@ namespace { // the cells the simulation itself writes each frame: the weather, the time and the date for the scripts constexpr std::string_view scripting_cells{"__simulation."}; +// a speed limit beyond any a track has: a value of the file past it is refused +constexpr double big_velocity{1e6}; +// the most events sharing a name a snapshot looks among, the most seconds an event waits in the queue +constexpr int most_siblings{100000}; +constexpr double longest_wait{1e9}; // the place of each thing of a table, to name the ones without a name of their own template class table_index { @@ -167,19 +173,33 @@ void capture_time(document &Document) entry.set("hour", time.wHour).set("minute", time.wMinute).set("second", time.wSecond).set("milliseconds", Time.milliseconds()); } -void apply_time(record const &Entry) +bool apply_time(record const &Entry) { + // the month and the day pick entries of the tables of the clock: a date which isn't one is refused whole auto time{Time.data()}; - Entry.get("year", time.wYear); - Entry.get("month", time.wMonth); - Entry.get("day", time.wDay); - Entry.get("weekday", time.wDayOfWeek); - Entry.get("hour", time.wHour); - Entry.get("minute", time.wMinute); - Entry.get("second", time.wSecond); - Time.restore(time, Entry.value("milliseconds", Time.milliseconds())); + if (false == Entry.get("year", time.wYear, WORD{1}, WORD{9999}) && Entry.has("year")) + return false; + if (false == Entry.get("month", time.wMonth, WORD{1}, WORD{12}) && Entry.has("month")) + return false; + constexpr std::array days{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + if (false == Entry.get("day", time.wDay, WORD{1}, days[time.wMonth]) && Entry.has("day")) + return false; + if (time.wMonth == 2 && time.wDay == 29 && false == ((time.wYear % 4 == 0 && time.wYear % 100 != 0) || time.wYear % 400 == 0)) + { + Entry.refuse("day", "the year isn't a leap one"); + return false; + } + auto milliseconds{Time.milliseconds()}; + if ((false == Entry.get("weekday", time.wDayOfWeek, WORD{0}, WORD{6}) && Entry.has("weekday")) || + (false == Entry.get("hour", time.wHour, WORD{0}, WORD{23}) && Entry.has("hour")) || + (false == Entry.get("minute", time.wMinute, WORD{0}, WORD{59}) && Entry.has("minute")) || + (false == Entry.get("second", time.wSecond, WORD{0}, WORD{59}) && Entry.has("second")) || + (false == Entry.get("milliseconds", milliseconds, 0.0, 999.999999) && Entry.has("milliseconds"))) + return false; + Time.restore(time, milliseconds); // the season goes by the date, and the weather by the season Environment.compute_season(Time.year_day()); + return true; } void capture_weather(document &Document) @@ -195,15 +215,22 @@ void capture_weather(document &Document) void apply_weather(record const &Entry) { - Entry.get("overcast", Global.Overcast); - Entry.get("fog", Global.fFogEnd); - Entry.get("temperature", Global.AirTemperature); + // the weather is drawn from these: a number which isn't one has no place in it + constexpr auto big{1e9f}; + Entry.get("overcast", Global.Overcast, 0.f, 10.f); + Entry.get("fog", Global.fFogEnd, 0.f, big); + Entry.get("temperature", Global.AirTemperature, -100.f, 100.f); Environment.compute_weather(); auto state{Environment.wind_state()}; if (auto const wind{text_numbers(Entry.text("wind"))}; wind.size() == state.size()) { - std::ranges::transform(wind, state.begin(), [](double const Value) { return static_cast(Value); }); - Environment.wind_state(state); + if (std::ranges::all_of(wind, [](double const Value) { return std::isfinite(Value) && std::abs(Value) < 1e9; })) + { + std::ranges::transform(wind, state.begin(), [](double const Value) { return static_cast(Value); }); + Environment.wind_state(state); + } + else + Entry.refuse("wind", "a number of it isn't finite"); } } @@ -230,7 +257,14 @@ bool apply_power(record const &Entry) auto *source{find_in(Powergrid, Entry.name)}; if (source == nullptr) return false; - source->state(text_numbers(Entry.text("state"))); + auto const state{text_numbers(Entry.text("state"))}; + // the last one counts the times the fuse blew + if (false == state.empty() && false == whole_number(state.back(), 0, std::numeric_limits::max()).has_value()) + { + Entry.refuse("state", "the count of its fuse isn't a whole number"); + return true; + } + source->state(state); return true; } @@ -335,8 +369,8 @@ bool apply_crossing(record const &Entry) auto *track{find_track(Entry.name)}; if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) return false; - auto const index{Entry.value("segment", -1)}; - if (index < 0 || index >= 6 || track->SwitchExtension->Segments[index] == nullptr) + auto const index{Entry.value("segment", -1, 0, 5)}; + if (index < 0 || track->SwitchExtension->Segments[index] == nullptr) return false; track->Segment = track->SwitchExtension->Segments[index]; return true; @@ -365,7 +399,9 @@ bool apply_made_track(record const &Entry) auto *track{find_track(Entry.name)}; if (track == nullptr) return false; - auto const end{Entry.value("end", 0)}; + auto end{0}; + if (false == Entry.get("end", end, 0, 1) && Entry.has("end")) + return false; // made anew unless the scenery has something there by now if ((end == 0 ? track->trPrev : track->trNext) == nullptr) track->NullCreate(end); @@ -377,9 +413,9 @@ bool apply_switch(record const &Entry) auto *track{find_track(Entry.name)}; if (track == nullptr || track->eType != tt_Switch) return false; - if (auto state{0}; Entry.get("state", state) && state != track->GetSwitchState()) + if (auto state{0}; Entry.get("state", state, 0, 1) && state != track->GetSwitchState()) track->Switch(state); - if (auto velocity{0.0}; Entry.get("velocity", velocity)) + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) track->velocity_limit(velocity); return true; } @@ -389,7 +425,7 @@ bool apply_track(record const &Entry) auto *track{find_track(Entry.name)}; if (track == nullptr) return false; - if (auto velocity{0.0}; Entry.get("velocity", velocity)) + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) track->velocity_limit(velocity); Entry.get("damage", track->iDamageFlag); return true; @@ -412,11 +448,18 @@ void capture_events(document &Document) bool apply_event(record const &Entry) { - auto *event{find_event(Entry.name, Entry.value("sibling", 0))}; + auto sibling{0}; + if (false == Entry.get("sibling", sibling, 0, most_siblings) && Entry.has("sibling")) + return false; + auto *event{find_event(Entry.name, sibling)}; if (event == nullptr) return false; - // without the time it ran at, the seconds it had left count from now - auto const launchtime{Entry.value("at", Timer::GetTime() + Entry.value("left", 0.0))}; + // without the time it ran at, the seconds it had left count from now. the queue is kept in the order of the times, + // which a time that isn't a number has none in + auto const now{Timer::GetTime()}; + auto launchtime{now + Entry.value("left", 0.0, -longest_wait, longest_wait)}; + if (false == Entry.get("at", launchtime, now - longest_wait, now + longest_wait) && Entry.has("at")) + return false; auto const *activator{Entry.has("activator") ? find_vehicle(Entry.text("activator")) : nullptr}; return Events.restore_queued(event, activator, launchtime); } @@ -450,7 +493,7 @@ bool apply_launcher(record const &Entry, std::vector const &La launcher = *lookup; if (launcher == nullptr) return false; - launcher->timer(Entry.value("timer", launcher->timer())); + launcher->timer(Entry.value("timer", launcher->timer(), 0.0, longest_wait)); return true; } @@ -497,7 +540,7 @@ bool apply_lights(record const &Entry) return false; for (auto light{0}; light < iMaxNumLights; ++light) { - if (auto state{0.f}; Entry.get(std::format("light{}", light), state)) + if (auto state{0.f}; Entry.get(std::format("light{}", light), state, -1e6f, 1e6f)) model->LightSet(light, state); } return true; @@ -533,22 +576,7 @@ std::vector current_couplings(std::unordered_map wanted_couplings(std::vector const &Entries) -{ - std::vector links; - for (auto const *entry : Entries) - { - for (auto const side : {end::front, end::rear}) - { - auto const key{std::format("coupler{}", static_cast(side))}; - if (false == entry->has(key + "flags")) - continue; - links.emplace_back(entry->name, side, entry->text(key), entry->value(key + "end", 0), entry->value(key + "flags", 0)); - } - } - return links; -} +static_assert(coupling_flags_mask == (coupling::power3x400v << 1) - 1, "the flags a snapshot takes are every bit of the coupling enum"); void part(TDynamicObject &Vehicle, int const End) { @@ -577,18 +605,20 @@ void apply_couplings(std::vector const &Entries, apply_summary & owners.emplace(vehicle->MoverParameters, vehicle); present.emplace_back(vehicle_reference(vehicle)); } - auto const plan{plan_couplings(current_couplings(owners), wanted_couplings(Entries), present)}; + auto const plan{plan_couplings(current_couplings(owners), read_couplings(Entries), present)}; + // the vehicles of the links are of the scenery (Present), with their physics + auto const with_physics{[](TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->MoverParameters != nullptr; }}; for (auto const &link : plan.part) { - if (auto *vehicle{find_vehicle(link.vehicle)}; vehicle != nullptr) + if (auto *vehicle{find_vehicle(link.vehicle)}; with_physics(vehicle)) part(*vehicle, link.end); } for (auto const &link : plan.change) { auto const *vehicle{find_vehicle(link.vehicle)}; auto const *other{find_vehicle(link.other)}; - if (vehicle == nullptr || other == nullptr) + if (false == with_physics(vehicle) || false == with_physics(other)) continue; vehicle->MoverParameters->Couplers[link.end].CouplingFlag = link.flags; other->MoverParameters->Couplers[link.otherend].CouplingFlag = link.flags; @@ -598,7 +628,8 @@ void apply_couplings(std::vector const &Entries, apply_summary & { auto *vehicle{find_vehicle(link.vehicle)}; auto *other{find_vehicle(link.other)}; - if (vehicle == nullptr || other == nullptr || false == vehicle->MoverParameters->Attach(link.end, link.otherend, other->MoverParameters, link.flags, true, false)) + if (false == with_physics(vehicle) || false == with_physics(other) || + false == vehicle->MoverParameters->Attach(link.end, link.otherend, other->MoverParameters, link.flags, true, false)) { ++failed; continue; @@ -611,6 +642,11 @@ void apply_couplings(std::vector const &Entries, apply_summary & Summary.remarks.emplace_back(std::format("couplings: {} parted, {} joined, {} changed", plan.part.size(), static_cast(plan.join.size()) - failed, plan.change.size())); if (failed != 0 || false == plan.missing.empty()) Summary.notes.emplace_back(std::format("couplings: {} of the snapshot couldn't be made, {} are to vehicles the scenery doesn't have", failed, plan.missing.size())); + if (false == plan.refused.empty()) + { + Summary.notes.emplace_back(std::format("couplings: {} of the snapshot refused, they'd close a ring of vehicles; the first one {} {} to {} {}", plan.refused.size(), + plan.refused.front().vehicle, plan.refused.front().end, plan.refused.front().other, plan.refused.front().otherend)); + } // each vehicle knows the one coupled to it as its neighbour at that end for (auto *vehicle : Vehicles.sequence()) @@ -720,7 +756,7 @@ void apply_isolated(document const &Document, apply_summary &Summary) } // a count beyond any the vehicles of a scenery make auto axles{0}; - if (false == entry->get("axles", axles)) + if (false == entry->get("axles", axles, -1000000, 1000000)) { ++Summary.skipped; continue; @@ -969,6 +1005,8 @@ document capture() capture_player(result); // the long one last, out of the way of whoever reads the file capture_random(result); + // a file cut short between two entries is told by this + result.records.front().set("entries", result.records.size()); return result; } @@ -988,12 +1026,9 @@ apply_summary apply(document const &Document) // set off the events of the tracks, the sections they free and take don't change their signals Events.suspend(true); - if (auto timer{0.0}; header->get("timer", timer)) + if (auto timer{0.0}; header->get("timer", timer, 0.0, longest_wait)) Timer::set_time(timer); - apply_each(Document, "time", summary, [](record const &Entry) { - apply_time(Entry); - return true; - }); + apply_each(Document, "time", summary, apply_time); apply_each(Document, "weather", summary, [](record const &Entry) { apply_weather(Entry); return true; @@ -1024,23 +1059,19 @@ apply_summary apply(document const &Document) } // last, whatever was drawn at random on the way here doesn't count apply_each(Document, "random", summary, apply_random); + // the values of the file which weren't taken + for (auto &refusal : take_refusals()) + summary.notes.emplace_back(std::move(refusal)); return summary; } bool save(std::string const &File) { auto const document{capture()}; - std::ofstream output{File, std::ios::binary | std::ios::trunc}; - if (false == output.is_open()) + // to a file of its own first, which takes the place of the one asked for once it's whole + if (auto const error{write_file(File, document)}; false == error.empty()) { - ErrorLog(std::format("snapshot: file \"{}\" can't be written", File)); - return false; - } - write(output, document); - output.close(); - if (output.fail()) - { - ErrorLog(std::format("snapshot: writing file \"{}\" failed", File)); + ErrorLog(std::format("snapshot: {}", error)); return false; } WriteLog(std::format("snapshot: the simulation at {:.2f} s saved to \"{}\", {} entries", Timer::GetTime(), File, document.records.size())); @@ -1073,10 +1104,17 @@ void request(command_line const &Requests) schedule.pending = load(Requests.load); } +// the snapshot to load, if it's to be used +document const *accepted_pending() +{ + auto const &schedule{requested()}; + return schedule.pending.has_value() && accepted(*schedule.pending, schedule.requests.force) ? &*schedule.pending : nullptr; +} + std::optional requested_seed() { - auto const &pending{requested().pending}; - auto const *header{pending.has_value() ? pending->header() : nullptr}; + auto const *pending{accepted_pending()}; + auto const *header{pending != nullptr ? pending->header() : nullptr}; if (std::uint32_t seed{0}; header != nullptr && header->get("seed", seed)) return seed; return std::nullopt; @@ -1084,8 +1122,8 @@ std::optional requested_seed() std::string requested_player_vehicle() { - auto const &pending{requested().pending}; - if (false == pending.has_value()) + auto const *pending{accepted_pending()}; + if (pending == nullptr) return {}; auto const players{pending->of("player")}; return players.empty() ? std::string{} : players.front()->name; @@ -1094,19 +1132,39 @@ std::string requested_player_vehicle() void start() { auto &schedule{requested()}; - auto const loaded{schedule.pending.has_value()}; - if (loaded) + auto loaded{false}; + if (schedule.pending.has_value()) { auto const document{std::move(*schedule.pending)}; schedule.pending.reset(); for (auto const &problem : document.problems) ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, problem)); - auto const summary{apply(document)}; + for (auto const &warning : document.warnings) + ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, warning)); + // a damaged file would put back part of the world, and leave the rest as the scenery makes it + apply_summary summary; + if (accepted(document, schedule.requests.force)) + { + if (false == document.problems.empty()) + ErrorLog(std::format("snapshot: \"{}\" is loaded as far as it could be read, --load-snapshot-force says so", schedule.requests.load)); + summary = apply(document); + } + else + { + summary.refused = true; + summary.notes.emplace_back(std::format("\"{}\" isn't loaded: it's damaged (--load-snapshot-force loads what can be read of it)", schedule.requests.load)); + } for (auto const ¬e : summary.notes) ErrorLog(std::format("snapshot: {}", note)); for (auto const &remark : summary.remarks) WriteLog(std::format("snapshot: {}", remark)); - if (false == summary.refused) + loaded = (false == summary.refused); + if (false == loaded && Global.test.enabled) + { + // a test run from a snapshot is no test without it + test().finish(test_result::error, "the snapshot to load is damaged or missing"); + } + if (loaded) { // the simulation goes on, it doesn't start: with nobody to wait for in a cab the drivers and the scenery // take the first frame as any other, the way they took it in the run the snapshot comes from diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 52652e40a..24ea2b3f9 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -130,7 +130,7 @@ are doing, what the drivers are up to. Loading one means loading its scenery the state over it before the first frame, so a run can go on from the middle of a scenario: ``` -eu07 -s [--snapshot-at ]... [--load-snapshot ] +eu07 -s [--snapshot-at ]... [--load-snapshot [--load-snapshot-force]] ``` - `--snapshot-at ` writes a snapshot once the simulation has run that long and goes on. The @@ -139,7 +139,9 @@ eu07 -s [--snapshot-at ]... [--load-snapshot ` puts the snapshot over the scenery given with `-s` once it has loaded. Without `-seed` the random seed is taken from the snapshot, so the scenery loads the way it did then; without - `-v` the player starts in the vehicle they were in. + `-v` the player starts in the vehicle they were in. A file the reader finds damaged (an entry cut short, or + fewer entries than its header counts) isn't loaded: the scenery starts as it is, the log says why, and a + test run ends with the error code. `--load-snapshot-force` loads what can be read of it all the same. - Both work with and without `--test`. In the game the `snapshotsave` command ([Ctrl]+[Shift]+[F9], or whatever `eu07_input-keyboard.ini` binds it to) writes one to `snapshots/__