diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f189096b..0bdbe3980 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -552,6 +552,7 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"simulation/simulationsnapshot.cpp" "vehicle/blackbox.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" diff --git a/simulation/simulationsnapshot.cpp b/simulation/simulationsnapshot.cpp new file mode 100644 index 000000000..0990cac71 --- /dev/null +++ b/simulation/simulationsnapshot.cpp @@ -0,0 +1,516 @@ +/* +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 "simulation/simulationsnapshot.h" + +#include "utilities/parser.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +namespace { + +// a value which is no text at all is written as this, there's no way to write an empty token +constexpr std::string_view empty_mark{"<>"}; +// lines of the file are kept shorter than this, where the tokens allow +constexpr std::size_t line_width{110}; + +// characters a token can hold without quotes around it: nothing which ends a token, starts a comment or a quoted text +bool is_plain(std::string_view const Text) +{ + if (Text.find("//") != std::string_view::npos || Text.find("/*") != std::string_view::npos) + return false; + return std::ranges::none_of(Text, [](char const Character) { + auto const code{static_cast(Character)}; + return code <= ' ' || Character == ';' || Character == '"' || Character == '\\' || code == 127; + }); +} + +// the value as a token of the file; Terminator is the word which ends the entry the value is written in +std::string encode(std::string_view const Value, std::string_view const Terminator) +{ + if (Value.empty()) + return std::string(empty_mark); + std::string text; + if (Value.front() == '<' || Value == Terminator) + { + // one more '<' in front keeps the value apart from the mark of an empty one, and from the end of its entry + text += '<'; + } + text += Value; + if (is_plain(text)) + return text; + std::string quoted{"\""}; + for (auto const character : text) + { + if (character == '"' || character == '\\') + quoted += '\\'; + quoted += character; + } + quoted += '"'; + return quoted; +} + +// the value a token of the file stands for; the parser has taken the quotes off already +std::string decode(std::string const &Token) +{ + if (Token == empty_mark) + return {}; + if (Token.starts_with('<')) + return Token.substr(1); + return Token; +} + +std::string next_token(cParser &Input) +{ + return Input.getToken(false); +} + +// the headings put before the entries of a type, for a reader of the file +std::string_view heading(std::string_view const Type) +{ + using entry = std::pair; + static constexpr std::array headings{ + entry{"time", "date and time of the simulation"}, + entry{"weather", "weather"}, + entry{"random", "random number engine"}, + entry{"memcell", "memory cells: text, value 1, value 2"}, + entry{"switch", "switches: the path set"}, + entry{"track", "tracks changed by events: speed limit, damage"}, + entry{"crossing", "road crossings: the way through which was taken last"}, + entry{"madetrack", "tracks made on the run where a track of the scenery ends: turning loops, derailing tracks"}, + entry{"powersource", "traction power sources: voltage, current, admittance now and before, output, fuses, their timer and count"}, + entry{"isolated", "isolated sections: axles counted in"}, + entry{"event", "queued events: seconds left, the vehicle which set them off"}, + entry{"launcher", "event launchers: their timers"}, + entry{"model", "lights of the models which events switch: the signals"}, + entry{"vehicle", "vehicles: place, speed, couplings, load, machinery"}, + entry{"driver", "drivers: orders, timetable"}, + entry{"player", "the vehicle of the player"}, + }; + auto const lookup{std::ranges::find(headings, Type, &entry::first)}; + return lookup != headings.end() ? lookup->second : std::string_view{}; +} + +void write_record(std::ostream &Output, record const &Record) +{ + auto const terminator{"end" + Record.type}; + std::string line{Record.type + ' ' + encode(Record.name, terminator)}; + for (auto const &[key, value] : Record.fields) + { + auto const token{key + ' ' + encode(value, terminator)}; + if (line.size() + 1 + token.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + line += ' '; + line += token; + } + if (line.size() + 1 + terminator.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + Output << line << ' ' << terminator << '\n'; +} + +// reads the keys and values of an entry, up to its end. returns: what went wrong, if anything +std::string read_fields(cParser &Input, record &Record) +{ + auto const terminator{"end" + Record.type}; + while (true) + { + auto key{next_token(Input)}; + if (key == terminator) + return {}; + if (key.empty()) + return std::format("entry \"{} {}\" isn't closed with {}", Record.type, Record.name, terminator); + auto const value{next_token(Input)}; + if (value.empty() || value == terminator) + return std::format("entry \"{} {}\" has key {} without a value", Record.type, Record.name, key); + Record.fields.emplace_back(std::move(key), decode(value)); + } +} + +using coupler_key = std::pair; + +struct coupler_link { + std::string other; + int otherend{0}; + int flags{0}; +}; + +using coupler_map = std::map>; + +// the links by each of their ends; a link to nothing is the vehicle's end standing free +coupler_map by_coupler(std::vector const &Links) +{ + coupler_map map; + for (auto const &link : Links) + { + auto const linked{false == link.other.empty() && link.flags != 0}; + map[coupler_key{link.vehicle, link.end}] = linked ? coupler_link{link.other, link.otherend, link.flags} : coupler_link{}; + if (linked) + map[coupler_key{link.other, link.otherend}] = coupler_link{link.vehicle, link.end, link.flags}; + } + return map; +} + +bool same_partner(coupler_link const &Left, coupler_link const &Right) +{ + return Left.other == Right.other && Left.otherend == Right.otherend; +} + +// each link once: the end it's listed by first is the one which comes first in the list +std::vector unique_links(std::vector const &Links) +{ + std::vector unique; + std::set> seen; + for (auto const &link : Links) + { + if (link.other.empty() || link.flags == 0) + continue; + if (seen.contains(coupler_key{link.vehicle, link.end}) || seen.contains(coupler_key{link.other, link.otherend})) + continue; + seen.emplace(link.vehicle, link.end); + seen.emplace(link.other, link.otherend); + unique.emplace_back(link); + } + return unique; +} + +// what the snapshot wants of a coupler, if it says anything of it +coupler_link const *wanted_link(coupler_map const &Wanted, std::string const &Vehicle, int const End) +{ + auto const lookup{Wanted.find(coupler_key{Vehicle, End})}; + return lookup != Wanted.end() ? &lookup->second : nullptr; +} + +} // namespace + +std::string number_text(double const Value) +{ + if (std::isnan(Value)) + return "nan"; + if (std::isinf(Value)) + return Value > 0.0 ? "inf" : "-inf"; + // the shortest text which reads back as the same value + return std::format("{}", Value); +} + +std::string number_text(float const Value) +{ + if (std::isnan(Value) || std::isinf(Value)) + return number_text(static_cast(Value)); + return std::format("{}", Value); +} + +std::optional text_number(std::string_view Text) +{ + if (Text.empty()) + return std::nullopt; + if (Text == "nan") + return std::nan(""); + if (Text == "inf") + return HUGE_VAL; + if (Text == "-inf") + return -HUGE_VAL; + if (Text.front() == '+') + Text.remove_prefix(1); + double value{0.0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [parsed, error]{std::from_chars(Text.data(), end, value)}; error == std::errc{} && parsed == end) + return value; + return std::nullopt; +} + +std::string numbers_text(std::span const Numbers) +{ + std::string text; + for (auto const number : Numbers) + { + if (false == text.empty()) + text += ','; + text += number_text(number); + } + return text; +} + +std::vector text_numbers(std::string_view Text) +{ + std::vector numbers; + while (false == Text.empty()) + { + auto const comma{Text.find(',')}; + if (auto const number{text_number(Text.substr(0, comma))}; number.has_value()) + numbers.emplace_back(*number); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +std::string const *record::find(std::string_view const Key) const +{ + auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; + return lookup != fields.end() ? &lookup->second : nullptr; +} + +std::string record::text(std::string_view const Key, std::string_view const Fallback) const +{ + auto const *value{find(Key)}; + return value != nullptr ? *value : std::string(Fallback); +} + +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()) + { + lookup->second = std::move(Value); + return; + } + fields.emplace_back(std::string(Key), std::move(Value)); +} + +record &document::add(std::string_view const Type, std::string_view const Name) +{ + return records.emplace_back(Type, Name); +} + +std::vector document::of(std::string_view const Type) const +{ + std::vector found; + for (auto const &entry : records) + { + if (entry.type == Type) + found.emplace_back(&entry); + } + return found; +} + +record const *document::find(std::string_view const Type, std::string_view const Name) const +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? &*lookup : nullptr; +} + +record *document::find(std::string_view const Type, std::string_view const Name) +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? &*lookup : nullptr; +} + +record const *document::header() const +{ + return false == records.empty() && records.front().type == "snapshot" ? &records.front() : nullptr; +} + +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; +} + +void write(std::ostream &Output, document const &Document) +{ + Output << "// MaSzyna simulation snapshot: the state of a running scenery, loaded over it with --load-snapshot\n"; + std::string lasttype; + for (auto const &entry : Document.records) + { + if (entry.type != lasttype) + { + lasttype = entry.type; + if (auto const text{heading(entry.type)}; false == text.empty()) + Output << "\n// " << text << '\n'; + } + write_record(Output, entry); + } +} + +std::string to_text(document const &Document) +{ + std::ostringstream output; + write(output, Document); + return output.str(); +} + +document read(cParser &Input) +{ + // a value can be any word, "include" among them + Input.expandIncludes = false; + document result; + auto type{next_token(Input)}; + while (false == type.empty()) + { + auto name{next_token(Input)}; + if (name.empty()) + { + result.problems.emplace_back(std::format("the file ends after \"{}\"", type)); + break; + } + auto &entry{result.records.emplace_back(type, decode(name))}; + if (auto problem{read_fields(Input, entry)}; false == problem.empty()) + result.problems.emplace_back(std::move(problem)); + type = next_token(Input); + } + if (result.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; +} + +document parse(std::string const &Text) +{ + cParser parser(Text, cParser::buffer_TEXT); + return read(parser); +} + +document load(std::string const &File) +{ + std::ifstream input(File, std::ios::binary); + if (false == input.is_open()) + { + document result; + result.problems.emplace_back(std::format("file \"{}\" can't be opened", File)); + return result; + } + std::ostringstream text; + text << input.rdbuf(); + return parse(text.str()); +} + +std::string reference(std::string_view const Name, std::size_t const Index, bool const Foundbyname) +{ + if (Foundbyname && false == Name.empty() && Name.front() != '#') + return std::string(Name); + return std::format("#{}", Index); +} + +std::optional reference_index(std::string_view const Reference) +{ + if (Reference.size() < 2 || Reference.front() != '#') + return std::nullopt; + std::size_t index{0}; + auto const *const begin{Reference.data() + 1}; + auto const *const end{Reference.data() + Reference.size()}; + if (auto const [parsed, error]{std::from_chars(begin, end, index)}; error == std::errc{} && parsed == end) + return index; + return std::nullopt; +} + +void name_hash::add(std::string_view const Name) +{ + constexpr std::uint64_t prime{1099511628211ULL}; + for (auto const character : Name) + { + m_hash ^= static_cast(character); + m_hash *= prime; + } + // the end of the name counts too: "ab", "c" isn't "a", "bc" + m_hash ^= 0xffU; + m_hash *= prime; +} + +std::string name_hash::text() const +{ + return std::format("{:016x}", m_hash); +} + +int option_value_count(std::string_view const Option) +{ + if (Option == "--snapshot-at") + return 2; + if (Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini" || Option == "--test-timeout" || Option == "--test-wall-timeout" || + Option == "--load-snapshot") + return 1; + return 0; +} + +command_line parse_command_line(std::span const Arguments) +{ + command_line result; + std::size_t index{1}; + while (index < Arguments.size()) + { + 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 (complete) + result.load = Arguments[index + 1]; + else if (result.error.empty()) + result.error = "--load-snapshot needs the name of a snapshot file"; + } + else if (option == "--snapshot-at") + { + auto const seconds{complete ? text_number(Arguments[index + 1]) : std::nullopt}; + if (seconds.has_value() && std::isfinite(*seconds) && *seconds >= 0.0) + result.saves.emplace_back(*seconds, Arguments[index + 2]); + else if (result.error.empty()) + result.error = "--snapshot-at needs a number of seconds and the name of a file"; + } + index += 1 + values; + } + return result; +} + +coupling_plan plan_couplings(std::vector const &Current, std::vector const &Wanted, std::vector const &Present) +{ + coupling_plan plan; + auto const current{by_coupler(Current)}; + auto const wanted{by_coupler(Wanted)}; + std::set> const present(Present.begin(), Present.end()); + + // what's coupled and shouldn't be, or should be another way + for (auto const &link : unique_links(Current)) + { + auto const *here{wanted_link(wanted, link.vehicle, link.end)}; + auto const *there{wanted_link(wanted, link.other, link.otherend)}; + if (here == nullptr && there == nullptr) + continue; + auto const kept{here != nullptr && same_partner(*here, coupler_link{link.other, link.otherend, link.flags})}; + if (false == kept) + { + plan.part.emplace_back(link); + continue; + } + if (here->flags != link.flags) + plan.change.emplace_back(link.vehicle, link.end, link.other, link.otherend, here->flags); + } + // what should be coupled and isn't + for (auto const &link : unique_links(Wanted)) + { + if (false == present.contains(link.vehicle) || false == present.contains(link.other)) + { + plan.missing.emplace_back(link); + continue; + } + auto const lookup{current.find(coupler_key{link.vehicle, link.end})}; + if (lookup != current.end() && same_partner(lookup->second, coupler_link{link.other, link.otherend, link.flags})) + continue; + plan.join.emplace_back(link); + } + return plan; +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshot.h b/simulation/simulationsnapshot.h new file mode 100644 index 000000000..36588e7a9 --- /dev/null +++ b/simulation/simulationsnapshot.h @@ -0,0 +1,232 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class cParser; + +// snapshot of a running simulation (stage A of the saved game): a text file in the syntax of the scenery files, which +// names the scenery it was taken in and holds what changed since that scenery was loaded. loading one means loading the +// scenery the usual way and then putting the saved state over it. +// this file is the text itself: the entries, how they're written and read. what goes into them is in +// simulationsnapshotmover.cpp (the state of a vehicle's machinery) and simulationsnapshotworld.cpp (the rest) +namespace simulation::snapshot { + +// version of the format, the name of the "snapshot" entry which starts the file. a reader takes the files of its own +// version and older ones, and of a newer file what it knows: unknown entries and keys are skipped +inline constexpr int format_version{1}; + +// writes a number so that reading it back gives the very same value +std::string number_text(double Value); +// a single precision value takes fewer digits to come back the same +std::string number_text(float Value); +// reads a number written by number_text(), or any other the standard reads. returns: empty if the text isn't a number +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); + +// 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 +class record { + +public: + record() = default; + record(std::string_view Type, std::string_view Name) : type(Type), name(Name) {} + + // adds the value, or replaces the one the key has + template record &set(std::string_view Key, Type_ const &Value); + // the value of the key, or nullptr + 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 + template bool get(std::string_view Key, Type_ &Target) const; + // the value of the key, or Fallback + template Type_ value(std::string_view Key, Type_ Fallback) const; + std::string text(std::string_view Key, std::string_view Fallback = {}) const; + + bool operator==(record const &) const = default; + + std::string type; + std::string name; + std::vector> fields; + +private: + void set_text(std::string_view Key, std::string Value); +}; + +// 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 + std::vector problems; + + record &add(std::string_view Type, std::string_view Name); + // the entries of the type, in the order of the file + std::vector of(std::string_view Type) const; + // the first entry of the type with the name, or nullptr + record const *find(std::string_view Type, std::string_view Name) const; + record *find(std::string_view Type, std::string_view Name); + // the header, or nullptr if the document doesn't start with one + record const *header() const; + // the version the header gives, 0 without a header + int version() const; +}; + +// the document as text +void write(std::ostream &Output, document const &Document); +std::string to_text(document const &Document); +// reads the entries until the input ends +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); + +// 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 +// of the scenery files, so the same scenery gives the same places +std::string reference(std::string_view Name, std::size_t Index, bool Foundbyname); +// the place in the table a reference gives, if it's of the "#12" kind +std::optional reference_index(std::string_view Reference); + +// a hash of names (FNV-1a, 64 bits), for the fingerprint of the scenery in the header: the snapshot remembers how many +// tracks, memory cells, events and vehicles the scenery had and a hash of their names, and a scenery which gives +// other numbers when the snapshot is loaded isn't the one it was taken in +class name_hash { + +public: + void add(std::string_view Name); + std::uint64_t value() const { return m_hash; } + // as text, 16 hexadecimal digits + std::string text() const; + +private: + std::uint64_t m_hash{14695981039346656037ULL}; +}; + +// 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 { + std::string vehicle; + int end{0}; + std::string other; + int otherend{0}; + int flags{0}; + + bool operator==(coupling_link const &) const = default; +}; + +// what has to be done to the couplings of the scenery to get the ones of the snapshot: the links to part first, then +// the links to make. a link is listed once, by the vehicle and end which come first in the given lists +struct coupling_plan { + std::vector part; + std::vector join; + // the links to set other flags on: joined to the same vehicle and end already, but by other means + std::vector change; + // the links of the snapshot to vehicles which aren't in Present + std::vector missing; +}; +// 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 snapshots asked for on the command line of the simulator +struct command_line { + struct save_request { + double time{0.0}; // of the simulation, seconds since the scenery started (Timer::GetTime()) + std::string file; + }; + std::string load; // --load-snapshot : put over the scenery once it's loaded + 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 +}; +// picks the snapshot options out of a command line (the first argument is the program), skipping the values of the +// other options the simulator takes +command_line parse_command_line(std::span Arguments); +// how many values follow an option of the simulator on its command line, for the parsers which pick out their own +int option_value_count(std::string_view Option); + +// implementation of the templates + +namespace detail { + +template std::string value_text(Type_ const &Value) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + return Value ? "1" : "0"; + else if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else if constexpr (std::is_integral_v) + return std::to_string(Value); + else if constexpr (std::is_same_v) + return number_text(Value); + else if constexpr (std::is_floating_point_v) + return number_text(static_cast(Value)); + else + return std::string(std::string_view(Value)); +} + +template bool text_value(std::string const &Text, Type_ &Target) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + { + Target = Text; + return true; + } + else + { + auto const number{text_number(Text)}; + if (false == number.has_value()) + return false; + if constexpr (std::is_same_v) + Target = *number != 0.0; + else + Target = static_cast(*number); + return true; + } +} + +} // namespace detail + +template record &record::set(std::string_view const Key, Type_ const &Value) +{ + set_text(Key, detail::value_text(Value)); + return *this; +} + +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); +} + +template Type_ record::value(std::string_view const Key, Type_ Fallback) const +{ + get(Key, Fallback); + return Fallback; +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp index fcedaed7d..8b851cb20 100644 --- a/simulation/simulationtestrules.cpp +++ b/simulation/simulationtestrules.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "simulation/simulationtestrules.h" +#include "simulation/simulationsnapshot.h" + #include #include #include @@ -28,11 +30,6 @@ std::string reason_suffix(std::string_view const Reason) return Reason.empty() ? std::string() : std::format(" ({})", Reason); } -// options of the simulator which take a value, see eu07_application::init_settings() -bool takes_value(std::string_view const Option) -{ - return Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini"; -} // a number of seconds given to Option, at Index of Arguments; the index is moved past the value std::optional option_seconds(std::span const Arguments, std::size_t &Index) @@ -96,9 +93,10 @@ test_command_line parse_test_command_line(std::span const Arg else result.wall_timeout = seconds; } - else if (takes_value(option)) + else { - ++i; + // the values of the other options, see eu07_application::init_settings() + i += static_cast(snapshot::option_value_count(option)); } } return result; diff --git a/tests/unit/test_snapshot.cpp b/tests/unit/test_snapshot.cpp new file mode 100644 index 000000000..8aa249e21 --- /dev/null +++ b/tests/unit/test_snapshot.cpp @@ -0,0 +1,424 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "simulation/simulationsnapshot.h" +#include "utilities/parser.h" + +#include +#include +#include +#include + +// the text of a simulation snapshot (simulation/simulationsnapshot.cpp): entries written and read back, what the +// reader makes of a damaged file, the names of the things of the scenery, the couplings to change + +namespace { + +namespace snapshot = simulation::snapshot; + +snapshot::document sample() +{ + snapshot::document document; + document.add("snapshot", "1").set("scenery", "td.scn").set("seed", 1234567890U).set("tracks", 812); + document.add("time", "now").set("year", 2026).set("month", 11).set("day", 18).set("hour", 10).set("minute", 32).set("second", 15.125); + document.add("memcell", "sem_a").set("text", "SetVelocity").set("value1", 40.0).set("value2", -1.0); + document.add("memcell", "status").set("text", "").set("value1", 0.1).set("value2", 1e-300); + document.add("switch", "#17").set("state", 1); + document.add("event", "sem_a_s1").set("sibling", 0).set("delay", 12.5).set("activator", "EU07-424"); + return document; +} + +} // namespace + +TEST_CASE("snapshot: a document written and read back is the same, and so is its text") +{ + auto const document{sample()}; + auto const text{snapshot::to_text(document)}; + auto const read{snapshot::parse(text)}; + CHECK(read.problems.empty()); + CHECK(read.records == document.records); + CHECK(snapshot::to_text(read) == text); + CHECK(read.version() == snapshot::format_version); + REQUIRE(read.header() != nullptr); + CHECK(read.header()->text("scenery") == "td.scn"); + CHECK(read.header()->value("seed", 0U) == 1234567890U); +} + +TEST_CASE("snapshot: the values keep their case, their spaces and whatever else they hold") +{ + std::vector const values{ + "plain", + "MiXeD_Case", + "", + "<>", + "<", + "< const values{ + 0.0, + -0.0, + 1.0, + -1.0, + 0.1, + 1.0 / 3.0, + 5.000000000000001, + 123456789.123456789, + 1e-300, + 1e300, + std::numeric_limits::min(), + std::numeric_limits::max(), + std::numeric_limits::denorm_min(), + std::numeric_limits::epsilon(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), + }; + for (auto const value : values) + { + auto const text{snapshot::number_text(value)}; + CAPTURE(text); + auto const read{snapshot::text_number(text)}; + REQUIRE(read.has_value()); + CHECK(*read == value); + CHECK(std::signbit(*read) == std::signbit(value)); + } + auto const nan{snapshot::text_number(snapshot::number_text(std::nan("")))}; + REQUIRE(nan.has_value()); + CHECK(std::isnan(*nan)); + + // single precision values are written as short as they can be, and read back the same + for (auto const value : {0.1f, 1.435f, 3.4028235e38f, 1.17549435e-38f, -2.5f}) + { + snapshot::record entry{"vehicle", "test"}; + entry.set("value", value); + CAPTURE(entry.text("value")); + CHECK(entry.value("value", 0.f) == value); + } + // whole numbers stay whole + CHECK(snapshot::number_text(5.0) == "5"); + CHECK(snapshot::number_text(-120.0) == "-120"); + + CHECK_FALSE(snapshot::text_number("").has_value()); + CHECK_FALSE(snapshot::text_number("abc").has_value()); + CHECK_FALSE(snapshot::text_number("12abc").has_value()); + CHECK_FALSE(snapshot::text_number("1 2").has_value()); + CHECK(snapshot::text_number("+2.5") == 2.5); +} + +TEST_CASE("snapshot: an entry gives its values in the type asked for, and leaves alone what it doesn't have") +{ + snapshot::record entry{"vehicle", "eu07-424"}; + entry.set("battery", true).set("mains", false).set("mainctrl", 12).set("pipe", 4.85).set("load", "coal").set("direction", -1); + CHECK(entry.value("battery", false)); + CHECK_FALSE(entry.value("mains", true)); + CHECK(entry.value("mainctrl", 0) == 12); + CHECK(entry.value("pipe", 0.0) == 4.85); + CHECK(entry.text("load") == "coal"); + CHECK(entry.value("direction", 0) == -1); + + // a key the entry doesn't have + auto untouched{7}; + CHECK_FALSE(entry.get("scndctrl", untouched)); + CHECK(untouched == 7); + CHECK(entry.value("scndctrl", 3) == 3); + CHECK(entry.text("destination", "none") == "none"); + // a value which isn't a number, asked for as one + CHECK_FALSE(entry.get("load", untouched)); + CHECK(untouched == 7); + + // a key set again keeps its place + entry.set("mains", true); + CHECK(entry.fields[1].first == "mains"); + CHECK(entry.fields[1].second == "1"); + CHECK(entry.fields.size() == 6); + + enum class mode { off, on, automatic }; + entry.set("mode", mode::automatic); + CHECK(entry.value("mode", mode::off) == mode::automatic); +} + +TEST_CASE("snapshot: the reader says what's wrong with a damaged file and keeps what it could read") +{ + SUBCASE("no header") + { + auto const read{snapshot::parse("memcell a text x value1 1 value2 2 endmemcell")}; + CHECK(read.version() == 0); + REQUIRE(read.problems.size() == 1); + CHECK(read.problems[0].find("snapshot") != std::string::npos); + CHECK(read.records.size() == 1); + } + SUBCASE("empty file") + { + auto const read{snapshot::parse("// nothing here\n")}; + CHECK(read.records.empty()); + CHECK(read.problems.size() == 1); + } + SUBCASE("cut in the middle of an entry") + { + auto const read{snapshot::parse("snapshot 1 scenery td.scn endsnapshot memcell a text x value1")}; + REQUIRE(read.records.size() == 2); + CHECK(read.records[1].text("text") == "x"); + REQUIRE(read.problems.size() == 1); + CHECK(read.problems[0].find("value1") != std::string::npos); + } + SUBCASE("entry not closed") + { + auto const read{snapshot::parse("snapshot 1 endsnapshot memcell a text x")}; + REQUIRE(read.problems.size() == 1); + CHECK(read.problems[0].find("endmemcell") != std::string::npos); + } + SUBCASE("key without a value") + { + auto const read{snapshot::parse("snapshot 1 endsnapshot memcell a text endmemcell switch s state 1 endswitch")}; + REQUIRE(read.problems.size() == 1); + // the entries after it are read all the same + REQUIRE(read.records.size() == 3); + CHECK(read.records[2].value("state", 0) == 1); + } + SUBCASE("newer version") + { + auto const read{snapshot::parse("snapshot 99 endsnapshot")}; + CHECK(read.version() == 99); + REQUIRE(read.problems.size() == 1); + CHECK(read.problems[0].find("99") != std::string::npos); + } + SUBCASE("missing file") + { + auto const read{snapshot::load("no/such/file.snapshot")}; + CHECK(read.records.empty()); + CHECK(read.problems.size() == 1); + } +} + +TEST_CASE("snapshot: entries and keys of a newer version pass through a reader which doesn't know them") +{ + auto const text{std::string{"snapshot 1 scenery td.scn endsnapshot\n" + "hologram deck3 brightness 0.5 endhologram\n" + "memcell a text x value1 1 value2 2 colour red endmemcell\n"}}; + auto const read{snapshot::parse(text)}; + CHECK(read.problems.empty()); + REQUIRE(read.records.size() == 3); + CHECK(read.of("hologram").size() == 1); + REQUIRE(read.find("memcell", "a") != nullptr); + CHECK(read.find("memcell", "a")->text("colour") == "red"); + CHECK(read.find("memcell", "b") == nullptr); + // comments, line breaks and the semicolons of the scenery files are all the same to the reader + auto const loose{snapshot::parse("snapshot 1 scenery td.scn endsnapshot // header\n\n/* the cells */ memcell a\n\ttext x;\n value1 1 value2 2 colour red\nendmemcell")}; + CHECK(loose.problems.empty()); + REQUIRE(loose.records.size() == 2); + CHECK(loose.records[1] == *read.find("memcell", "a")); +} + +TEST_CASE("snapshot: things of the scenery are named by their own names, or by their place in the table") +{ + CHECK(snapshot::reference("tor_12", 5, true) == "tor_12"); + // a name which doesn't lead to the thing, as a shared one or none at all + CHECK(snapshot::reference("tor_12", 5, false) == "#5"); + CHECK(snapshot::reference("", 0, true) == "#0"); + // a name which reads as a place + CHECK(snapshot::reference("#3", 9, true) == "#9"); + + CHECK(snapshot::reference_index("#5") == 5U); + CHECK(snapshot::reference_index("#0") == 0U); + CHECK_FALSE(snapshot::reference_index("tor_12").has_value()); + CHECK_FALSE(snapshot::reference_index("#").has_value()); + CHECK_FALSE(snapshot::reference_index("#1a").has_value()); + CHECK_FALSE(snapshot::reference_index("").has_value()); +} + +TEST_CASE("snapshot: the hash of the names tells sceneries apart") +{ + auto const hash{[](std::vector const &Names) { + snapshot::name_hash result; + for (auto const &name : Names) + result.add(name); + return result.text(); + }}; + CHECK(hash({"a", "b"}) == hash({"a", "b"})); + CHECK(hash({"a", "b"}) != hash({"b", "a"})); + CHECK(hash({"ab", "c"}) != hash({"a", "bc"})); + CHECK(hash({"a"}) != hash({"a", ""})); + CHECK(hash({}).size() == 16); +} + +TEST_CASE("snapshot: the couplings of the scenery are changed into the ones of the snapshot") +{ + using link = snapshot::coupling_link; + constexpr int full{3}; + std::vector const present{"loco", "w1", "w2", "w3", "other"}; + + SUBCASE("nothing to do when they agree, whichever end a link is given from") + { + std::vector const current{{"loco", 1, "w1", 0, full}, {"w1", 1, "w2", 0, full}}; + std::vector const wanted{{"loco", 0, "", 0, 0}, {"loco", 1, "w1", 0, full}, {"w1", 0, "loco", 1, full}, {"w1", 1, "w2", 0, full}, + {"w2", 0, "w1", 1, full}, {"w2", 1, "", 0, 0}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + CHECK(plan.part.empty()); + CHECK(plan.join.empty()); + CHECK(plan.change.empty()); + CHECK(plan.missing.empty()); + } + SUBCASE("a wagon left behind is parted") + { + std::vector const current{{"loco", 1, "w1", 0, full}, {"w1", 1, "w2", 0, full}}; + std::vector const wanted{{"loco", 0, "", 0, 0}, {"loco", 1, "w1", 0, full}, {"w1", 0, "loco", 1, full}, {"w1", 1, "", 0, 0}, + {"w2", 0, "", 0, 0}, {"w2", 1, "", 0, 0}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + REQUIRE(plan.part.size() == 1); + CHECK(plan.part[0] == link{"w1", 1, "w2", 0, full}); + CHECK(plan.join.empty()); + } + SUBCASE("a wagon picked up is joined, once") + { + std::vector const current{{"loco", 1, "w1", 0, full}}; + std::vector const wanted{{"loco", 1, "w1", 0, full}, {"w1", 0, "loco", 1, full}, {"w1", 1, "w3", 1, 1}, {"w3", 1, "w1", 1, 1}, {"w3", 0, "", 0, 0}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + CHECK(plan.part.empty()); + REQUIRE(plan.join.size() == 1); + CHECK(plan.join[0] == link{"w1", 1, "w3", 1, 1}); + } + SUBCASE("a locomotive run round its train parts at one end and joins at the other") + { + std::vector const current{{"loco", 1, "w1", 0, full}, {"w1", 1, "w2", 0, full}}; + std::vector const wanted{{"loco", 0, "w2", 1, full}, {"loco", 1, "", 0, 0}, {"w1", 0, "", 0, 0}, {"w1", 1, "w2", 0, full}, + {"w2", 0, "w1", 1, full}, {"w2", 1, "loco", 0, full}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + REQUIRE(plan.part.size() == 1); + CHECK(plan.part[0] == link{"loco", 1, "w1", 0, full}); + REQUIRE(plan.join.size() == 1); + CHECK(plan.join[0] == link{"loco", 0, "w2", 1, full}); + } + SUBCASE("hoses taken off change the coupling without parting it") + { + std::vector const current{{"loco", 1, "w1", 0, full}}; + std::vector const wanted{{"loco", 1, "w1", 0, 1}, {"w1", 0, "loco", 1, 1}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + CHECK(plan.part.empty()); + CHECK(plan.join.empty()); + REQUIRE(plan.change.size() == 1); + CHECK(plan.change[0] == link{"loco", 1, "w1", 0, 1}); + } + SUBCASE("a coupler taken by a vehicle the snapshot doesn't know is freed for the one it wants there") + { + std::vector const current{{"other", 1, "w1", 0, full}}; + std::vector const wanted{{"loco", 1, "w1", 0, full}, {"w1", 0, "loco", 1, full}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + REQUIRE(plan.part.size() == 1); + CHECK(plan.part[0] == link{"other", 1, "w1", 0, full}); + REQUIRE(plan.join.size() == 1); + } + SUBCASE("couplings between vehicles the snapshot doesn't know stay") + { + std::vector const current{{"other", 1, "w3", 0, full}, {"loco", 1, "w1", 0, full}}; + std::vector const wanted{{"loco", 1, "w1", 0, full}, {"w1", 0, "loco", 1, full}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + CHECK(plan.part.empty()); + CHECK(plan.join.empty()); + } + SUBCASE("a vehicle the scenery no longer has can't be coupled to") + { + std::vector const current{{"loco", 1, "w1", 0, full}}; + std::vector const wanted{{"loco", 1, "gone", 0, full}, {"gone", 0, "loco", 1, full}, {"w1", 0, "", 0, 0}}; + auto const plan{snapshot::plan_couplings(current, wanted, present)}; + REQUIRE(plan.part.size() == 1); + CHECK(plan.join.empty()); + REQUIRE(plan.missing.size() == 1); + CHECK(plan.missing[0].other == "gone"); + } +} + +TEST_CASE("snapshot: the command line says which snapshot to load and when to take others") +{ + auto const parse{[](std::vector Arguments) { + Arguments.insert(Arguments.begin(), "eu07"); + return snapshot::parse_command_line(Arguments); + }}; + SUBCASE("none asked for") + { + auto const line{parse({"-s", "td.scn", "--test"})}; + CHECK(line.load.empty()); + CHECK(line.saves.empty()); + CHECK(line.error.empty()); + } + SUBCASE("one to load, two to take") + { + auto const line{parse({"--test", "-s", "td.scn", "--load-snapshot", "saves/a.snapshot", "--snapshot-at", "120", "b.snapshot", "--snapshot-at", "60.5", "c.snapshot"})}; + CHECK(line.error.empty()); + CHECK(line.load == "saves/a.snapshot"); + REQUIRE(line.saves.size() == 2); + CHECK(line.saves[0].time == 120.0); + CHECK(line.saves[0].file == "b.snapshot"); + CHECK(line.saves[1].time == 60.5); + CHECK(line.saves[1].file == "c.snapshot"); + } + SUBCASE("the values of other options aren't taken for options") + { + auto const line{parse({"-s", "--load-snapshot", "-v", "--snapshot-at", "-ini", "--load-snapshot", "--test-timeout", "--snapshot-at"})}; + CHECK(line.load.empty()); + CHECK(line.saves.empty()); + CHECK(line.error.empty()); + } + SUBCASE("a file name is missing") + { + CHECK_FALSE(parse({"--load-snapshot"}).error.empty()); + CHECK_FALSE(parse({"--snapshot-at", "60"}).error.empty()); + CHECK_FALSE(parse({"--snapshot-at"}).error.empty()); + } + SUBCASE("the time isn't a number of seconds") + { + CHECK_FALSE(parse({"--snapshot-at", "soon", "a.snapshot"}).error.empty()); + CHECK_FALSE(parse({"--snapshot-at", "-5", "a.snapshot"}).error.empty()); + CHECK_FALSE(parse({"--snapshot-at", "nan", "a.snapshot"}).error.empty()); + CHECK(parse({"--snapshot-at", "0", "a.snapshot"}).error.empty()); + } + SUBCASE("how many values the options of the simulator take") + { + CHECK(snapshot::option_value_count("-s") == 1); + CHECK(snapshot::option_value_count("--load-snapshot") == 1); + CHECK(snapshot::option_value_count("--snapshot-at") == 2); + CHECK(snapshot::option_value_count("--test") == 0); + CHECK(snapshot::option_value_count("td.scn") == 0); + } +}