diff --git a/CMakeLists.txt b/CMakeLists.txt index 0bdbe3980..67d05a8a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -179,6 +179,7 @@ set(SOURCES "application/application.cpp" "simulation/simulationtime.cpp" "simulation/simulationtest.cpp" +"simulation/simulationsnapshotworld.cpp" "scene/sceneeditor.cpp" "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" diff --git a/application/application.cpp b/application/application.cpp index 96f578514..26778005a 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include #include #include @@ -1219,6 +1220,15 @@ int eu07_application::init_settings(int Argc, char *Argv[]) Global.test.wall_timeout_from_command_line = true; } + // the simulation snapshots to load and to take (--load-snapshot, --snapshot-at) + auto const snapshotcommandline{simulation::snapshot::parse_command_line(std::vector(Argv, Argv + Argc))}; + if (false == snapshotcommandline.error.empty()) + { + std::cerr << snapshotcommandline.error << std::endl; + simulation::test().conclude(simulation::test_result::error, snapshotcommandline.error); + return -1; + } + fs::path iniPath = user_config_path("eu07.ini"); // a test reads the settings of the game folder only (and those given with -ini), not the player's own @@ -1235,6 +1245,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // process command line arguments bool sceneryfromcommandline{false}; bool editwithoutscenery{false}; + bool seedfromcommandline{false}; + bool vehiclefromcommandline{false}; for (int i = 1; i < Argc; ++i) { @@ -1253,6 +1265,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (i + 1 < Argc) { Global.local_start_vehicle = ToLower(Argv[++i]); + vehiclefromcommandline = true; } } else if (token == "-edit") @@ -1275,6 +1288,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (i + 1 < Argc) { Global.random_seed = seed_of(Argv[++i]); + seedfromcommandline = true; WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); } } @@ -1288,6 +1302,11 @@ 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") + { + // taken from the command line above, with their values + i += simulation::snapshot::option_value_count(token); + } else if (token == "-ini") { // extra settings file read on top of eu07.ini, so a run can override a few keys @@ -1305,7 +1324,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) << " [-edit [sceneryfilepath]]" << " [-seed number|word]" << " [-ini settingsfile]" - << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl; + << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" + << " [--load-snapshot file] [--snapshot-at seconds file]" << std::endl; simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } @@ -1313,6 +1333,17 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (editwithoutscenery && false == sceneryfromcommandline) Global.SceneryFile.clear(); + simulation::snapshot::request(snapshotcommandline); + // the scenery of a snapshot loads the way it did when the snapshot was taken only with the seed it had then + if (auto const seed{simulation::snapshot::requested_seed()}; seed.has_value() && false == seedfromcommandline) + { + Global.random_seed = *seed; + WriteLog(std::format("seed taken from the snapshot to load: {}", Global.random_seed)); + } + // and the player goes on in the vehicle they were in + if (auto const vehicle{simulation::snapshot::requested_player_vehicle()}; false == vehicle.empty() && false == vehiclefromcommandline) + Global.local_start_vehicle = vehicle; + if (Global.test.enabled) { if (false == sceneryfromcommandline || Global.SceneryFile.empty()) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 47ab3ae0c..fb2526a34 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "simulation/blackboxrecorder.h" #include "scene/scene.h" #include "rendering/lightarray.h" @@ -347,6 +348,8 @@ bool driver_mode::update() { simulation::test().update(deltatime); } + // the frame is complete: the snapshots asked for at this time are taken (--snapshot-at) + simulation::snapshot::update(); } // render time routines follow: @@ -520,6 +523,9 @@ void driver_mode::enter() Timer::ResetTimers(); + // the scenery is loaded and nothing runs yet: the state saved in a snapshot goes over it (--load-snapshot) + simulation::snapshot::start(); + if (Global.test.enabled) { // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..b6c713ee9 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -226,6 +226,23 @@ world_environment::update_moon() { m_moon.update( true ); } +std::array +world_environment::wind_state() const { + + return { m_wind.azimuth, m_wind.azimuth_change, m_wind.velocity, m_wind.velocity_change, m_wind.change_time, m_wind.vector.x, m_wind.vector.y, m_wind.vector.z }; +} + +void +world_environment::wind_state( std::array const &State ) { + + m_wind.azimuth = State[ 0 ]; + m_wind.azimuth_change = State[ 1 ]; + m_wind.velocity = State[ 2 ]; + m_wind.velocity_change = State[ 3 ]; + m_wind.change_time = State[ 4 ]; + m_wind.vector = { State[ 5 ], State[ 6 ], State[ 7 ] }; +} + void world_environment::update_wind() { diff --git a/simulation/simulationenvironment.h b/simulation/simulationenvironment.h index 218a2d18c..4b3548659 100644 --- a/simulation/simulationenvironment.h +++ b/simulation/simulationenvironment.h @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/precipitation.h" #include "audio/sound.h" +#include + class opengl_renderer; class opengl33_renderer; @@ -64,6 +66,12 @@ public: inline auto const & wind_azimuth() const { return m_wind.azimuth; } + // the wind as it blows and as it is about to change, for a snapshot of the simulation, which puts it back: + // azimuth and its change, velocity and its change, the time to the next change, the vector + std::array + wind_state() const; + void + wind_state( std::array const &State ); private: // types diff --git a/simulation/simulationsnapshotworld.cpp b/simulation/simulationsnapshotworld.cpp new file mode 100644 index 000000000..5a2aedb87 --- /dev/null +++ b/simulation/simulationsnapshotworld.cpp @@ -0,0 +1,778 @@ +/* +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/simulationsnapshotworld.h" + +#include "McZapkie/MOVER.h" +#include "model/AnimModel.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "simulation/simulationtime.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/utilities.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/EvLaunch.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/Track.h" +#include "world/TractionPower.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +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."}; + +// the place of each thing of a table, to name the ones without a name of their own +template class table_index { + +public: + // the place of the item in the sequence, or the size of the sequence for an item which isn't there + template std::size_t of(Sequence_ const &Sequence, Item_ const *Item) + { + if (auto const place{known(Sequence, Item)}; place < Sequence.size()) + return place; + // the table has grown, or it's the table of another scenery now + m_places.clear(); + std::size_t place{0}; + for (auto const *item : Sequence) + m_places.emplace(item, place++); + return known(Sequence, Item); + } + +private: + template std::size_t known(Sequence_ const &Sequence, Item_ const *Item) const + { + auto const lookup{m_places.find(Item)}; + return lookup != m_places.end() && lookup->second < Sequence.size() && Sequence[lookup->second] == Item ? lookup->second : Sequence.size(); + } + + std::unordered_map m_places; +}; + +// a thing of a table by its reference: its name, or its place +template auto find_in(Table_ const &Table, std::string const &Reference) -> decltype(Table.find(Reference)) +{ + if (auto const index{reference_index(Reference)}; index.has_value()) + return *index < Table.sequence().size() ? Table.sequence()[*index] : nullptr; + return Table.find(Reference); +} + +template std::string reference_in(Table_ const &Table, table_index &Index, Item_ const *Item) +{ + if (Item == nullptr) + return {}; + auto const place{Index.of(Table.sequence(), Item)}; + if (place >= Table.sequence().size()) + return {}; + return reference(Item->name(), place, Table.find(Item->name()) == Item); +} + +table_index &track_index() +{ + static table_index index; + return index; +} + +table_index &vehicle_index() +{ + static table_index index; + return index; +} + +table_index &powersource_index() +{ + static table_index index; + return index; +} + +table_index &model_index() +{ + static table_index index; + return index; +} + +// a track the simulation made on the run, where a track of the scenery ends: the loop a road vehicle turns back on, +// the track a train runs off the rails along (TTrack::NullCreate()) +bool made_on_the_run(TTrack const &Track) +{ + return (Track.iCategoryFlag & 0x80) != 0; +} + +// what the scenery is made of, by which a snapshot tells whether it's put over the scenery it was taken in +void capture_fingerprint(record &Header) +{ + name_hash names; + auto switches{0}; + auto tracks{0}; + for (auto const *track : Paths.sequence()) + { + // the tracks made on the run aren't the scenery's + if (track == nullptr || made_on_the_run(*track)) + continue; + ++tracks; + names.add(track->name()); + if (track->eType == tt_Switch) + ++switches; + } + for (auto const *cell : Memory.sequence()) + names.add(cell != nullptr ? cell->name() : std::string{}); + for (auto const *event : Events.sequence()) + names.add(event != nullptr ? event->m_name : std::string{}); + for (auto const *vehicle : Vehicles.sequence()) + names.add(vehicle != nullptr ? vehicle->name() : std::string{}); + Header.set("tracks", tracks); + Header.set("switches", switches); + Header.set("memcells", Memory.sequence().size()); + Header.set("events", Events.sequence().size()); + Header.set("launchers", Events.launchers().size()); + Header.set("vehicles", Vehicles.sequence().size()); + Header.set("names", names.text()); +} + +void capture_header(document &Document) +{ + auto &header{Document.add("snapshot", std::to_string(format_version))}; + header.set("scenery", Global.SceneryFile); + header.set("seed", Global.random_seed); + header.set("timer", Timer::GetTime()); + capture_fingerprint(header); +} + +void capture_time(document &Document) +{ + auto const &time{Time.data()}; + auto &entry{Document.add("time", "now")}; + entry.set("year", time.wYear).set("month", time.wMonth).set("day", time.wDay).set("weekday", time.wDayOfWeek); + entry.set("hour", time.wHour).set("minute", time.wMinute).set("second", time.wSecond).set("milliseconds", Time.milliseconds()); +} + +void apply_time(record const &Entry) +{ + 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())); + // the season goes by the date, and the weather by the season + Environment.compute_season(Time.year_day()); +} + +void capture_weather(document &Document) +{ + auto &entry{Document.add("weather", "now")}; + entry.set("overcast", Global.Overcast).set("fog", Global.fFogEnd).set("temperature", Global.AirTemperature); + // the wind: it changes now and then, by numbers drawn at random + std::vector wind; + for (auto const value : Environment.wind_state()) + wind.emplace_back(value); + entry.set("wind", numbers_text(wind)); +} + +void apply_weather(record const &Entry) +{ + Entry.get("overcast", Global.Overcast); + Entry.get("fog", Global.fFogEnd); + Entry.get("temperature", Global.AirTemperature); + 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); + } +} + +// the sources of the traction power: the voltage an event may have set, the load of the step before, the fuses +void capture_power(document &Document) +{ + // what a source which has fed nothing yet says of itself, but for its voltage + std::vector const idle{0.0, 1e-10, 1e-10, 0.0, 0.0, 0.0, 0.0, 0.0}; + for (auto const *source : Powergrid.sequence()) + { + if (source == nullptr) + continue; + auto const state{source->state()}; + // the sources made for single wires are many, and most of them idle + if (source->IsAutogenerated && std::ranges::equal(state.begin() + 1, state.end(), idle.begin(), idle.end())) + continue; + if (auto const name{reference_in(Powergrid, powersource_index(), source)}; false == name.empty()) + Document.add("powersource", name).set("state", numbers_text(state)); + } +} + +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"))); + return true; +} + +// the engine the simulation draws its random numbers from, as the numbers of its state, eight to a line +void capture_random(document &Document) +{ + std::ostringstream state; + state << Global.random_engine; + std::istringstream numbers{state.str()}; + std::string text; + std::string number; + auto count{0}; + while (numbers >> number) + { + if (false == text.empty()) + text += (count % 8 == 0 ? "\n " : " "); + text += number; + ++count; + } + Document.add("random", "engine").set("state", text); +} + +bool apply_random(record const &Entry) +{ + std::istringstream state{Entry.text("state")}; + auto engine{Global.random_engine}; + state >> engine; + if (state.fail()) + return false; + Global.random_engine = engine; + return true; +} + +void capture_memcells(document &Document) +{ + auto const &cells{Memory.sequence()}; + for (std::size_t index{0}; index < cells.size(); ++index) + { + auto const *cell{cells[index]}; + if (cell == nullptr || cell->name().starts_with(scripting_cells)) + continue; + auto &entry{Document.add("memcell", reference(cell->name(), index, Memory.find(cell->name()) == cell))}; + entry.set("text", cell->Text()).set("value1", cell->Value1()).set("value2", cell->Value2()); + if (false == cell->StopCommand()) + { + // the command of the cell isn't waiting to be sent to a train: it's not a command, or it was sent already + entry.set("sent", true); + } + } +} + +bool apply_memcell(record const &Entry) +{ + auto *cell{find_in(Memory, Entry.name)}; + if (cell == nullptr) + return false; + cell->UpdateValues(Entry.text("text", cell->Text()), Entry.value("value1", cell->Value1()), Entry.value("value2", cell->Value2()), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2); + if (Entry.value("sent", false)) + cell->StopCommandSent(); + return true; +} + +void capture_tracks(document &Document) +{ + // what an event can change of a track: bit 0x100 of iAction marks the damage, 0x200 the speed limit + constexpr int changedbyevents{0x100 | 0x200}; + for (auto *track : Paths.sequence()) + { + if (track != nullptr && track->eType == tt_Switch) + Document.add("switch", track_reference(track)).set("state", track->GetSwitchState()).set("velocity", track->velocity_limit()); + } + for (auto const *track : Paths.sequence()) + { + if (track != nullptr && track->eType != tt_Switch && (track->iAction & changedbyevents) != 0) + Document.add("track", track_reference(track)).set("velocity", track->velocity_limit()).set("damage", track->iDamageFlag); + } +} + +// the crossings of roads: which of the ways through was taken last. the crossing has it as its current segment, by +// which a driver looking ahead measures it +void capture_crossings(document &Document) +{ + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) + continue; + auto const &segments{track->SwitchExtension->Segments}; + for (auto index{0}; index < 6; ++index) + { + if (segments[index] != nullptr && segments[index] == track->Segment) + { + Document.add("crossing", track_reference(track)).set("segment", index); + break; + } + } + } +} + +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) + return false; + track->Segment = track->SwitchExtension->Segments[index]; + return true; +} + +// the tracks made on the run, each by the track of the scenery it was made at and the end of it. they come back in +// the order they were made in, which gives them their places in the table again +void capture_made_tracks(document &Document) +{ + for (auto const *made : Paths.sequence()) + { + if (made == nullptr || false == made_on_the_run(*made)) + continue; + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || made_on_the_run(*track) || (track->trPrev != made && track->trNext != made)) + continue; + Document.add("madetrack", track_reference(track)).set("end", track->trPrev == made ? 0 : 1); + break; + } + } +} + +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)}; + // made anew unless the scenery has something there by now + if ((end == 0 ? track->trPrev : track->trNext) == nullptr) + track->NullCreate(end); + return true; +} + +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()) + track->Switch(state); + if (auto velocity{0.0}; Entry.get("velocity", velocity)) + track->velocity_limit(velocity); + return true; +} + +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)) + track->velocity_limit(velocity); + Entry.get("damage", track->iDamageFlag); + return true; +} + +void capture_events(document &Document) +{ + auto const now{Timer::GetTime()}; + for (auto const *event{Events.begin()}; event != nullptr; event = event->m_next) + { + auto &entry{Document.add("event", event->m_name)}; + if (auto const sibling{event_sibling(event)}; sibling != 0) + entry.set("sibling", sibling); + // when it runs, by the clock of the simulation; the seconds left are for the reader of the file + entry.set("at", event->m_launchtime).set("left", event->m_launchtime - now); + if (event->m_activator != nullptr) + entry.set("activator", vehicle_reference(event->m_activator)); + } +} + +bool apply_event(record const &Entry) +{ + auto *event{find_event(Entry.name, Entry.value("sibling", 0))}; + 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))}; + auto const *activator{Entry.has("activator") ? find_vehicle(Entry.text("activator")) : nullptr}; + return Events.restore_queued(event, activator, launchtime); +} + +void capture_launchers(document &Document) +{ + auto const launchers{Events.launchers()}; + std::map> named; + for (auto const *launcher : launchers) + { + if (launcher != nullptr) + ++named[launcher->name()]; + } + for (std::size_t index{0}; index < launchers.size(); ++index) + { + auto const *launcher{launchers[index]}; + // a launcher which hasn't counted any time yet is as the scenery makes it + if (launcher == nullptr || launcher->timer() == 0.0) + continue; + Document.add("launcher", reference(launcher->name(), index, named[launcher->name()] == 1 && launcher->name() != "none")).set("timer", launcher->timer()); + } +} + +bool apply_launcher(record const &Entry, std::vector const &Launchers) +{ + TEventLauncher *launcher{nullptr}; + if (auto const index{reference_index(Entry.name)}; index.has_value()) + launcher = (*index < Launchers.size() ? Launchers[*index] : nullptr); + else if (auto const lookup{std::ranges::find_if(Launchers, [&](TEventLauncher const *Item) { return Item != nullptr && Item->name() == Entry.name; })}; + lookup != Launchers.end()) + launcher = *lookup; + if (launcher == nullptr) + return false; + launcher->timer(Entry.value("timer", launcher->timer())); + return true; +} + +// the models whose lights the events of the scenery switch: the signals, mostly +std::vector switched_models() +{ + std::vector models; + std::unordered_set seen; + for (auto const *event : Events.sequence()) + { + if (dynamic_cast(event) == nullptr) + continue; + for (auto *node : event->target_nodes()) + { + if (seen.emplace(node).second) + models.emplace_back(static_cast(node)); + } + } + return models; +} + +void capture_lights(document &Document) +{ + for (auto *model : switched_models()) + { + auto const name{reference_in(Instances, model_index(), static_cast(model))}; + if (name.empty()) + continue; + record entry{"model", name}; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto const state{model->LightGet(light)}; state.has_value()) + entry.set(std::format("light{}", light), std::get<0>(*state)); + } + if (false == entry.fields.empty()) + Document.records.emplace_back(std::move(entry)); + } +} + +bool apply_lights(record const &Entry) +{ + auto *model{find_in(Instances, Entry.name)}; + if (model == nullptr) + return false; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto state{0.f}; Entry.get(std::format("light{}", light), state)) + model->LightSet(light, state); + } + return true; +} + +// tells whether the snapshot was taken in the scenery it's being put over +void check_scenery(record const &Header, apply_summary &Summary) +{ + if (auto const scenery{Header.text("scenery")}; scenery != Global.SceneryFile) + Summary.notes.emplace_back(std::format("the snapshot was taken in scenery \"{}\", this one is \"{}\"", scenery, Global.SceneryFile)); + record now; + capture_fingerprint(now); + std::string changed; + for (auto const &[key, value] : now.fields) + { + if (auto const saved{Header.text(key, value)}; saved != value) + changed += std::format("{}{} {} (snapshot {})", changed.empty() ? "" : ", ", key, value, saved); + } + if (false == changed.empty()) + { + Summary.notes.emplace_back(std::format("the scenery isn't what it was when the snapshot was taken: {}. things named by their place in the scenery " + "(\"#12\") may be other ones now", + changed)); + } + if (auto const seed{Header.value("seed", Global.random_seed)}; seed != Global.random_seed) + { + Summary.notes.emplace_back( + std::format("the snapshot was taken with random seed {}, the scenery was loaded with {}: what it draws at random while it loads may differ", seed, + Global.random_seed)); + } +} + +// applies the entries of a type, each by the function given, and counts how it went +template void apply_each(document const &Document, std::string_view const Type, apply_summary &Summary, Function_ const Function) +{ + auto missing{0}; + std::string example; + for (auto const *entry : Document.of(Type)) + { + if (Function(*entry)) + { + ++Summary.entries; + continue; + } + ++Summary.skipped; + if (missing++ == 0) + example = entry->name; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} {} entries of the snapshot have nothing in the scenery to go to, the first one is {}", missing, Type, example)); +} + +// the snapshots asked for on the command line +struct schedule { + command_line requests; + std::optional pending; // the one to load, read ahead for its header + std::size_t written{0}; // how many of the saves are done +}; + +schedule &requested() +{ + static schedule instance; + return instance; +} + +} // namespace + +std::string track_reference(TTrack const *Track) +{ + return reference_in(Paths, track_index(), Track); +} + +TTrack *find_track(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Paths, Reference); +} + +std::string vehicle_reference(TDynamicObject const *Vehicle) +{ + return reference_in(Vehicles, vehicle_index(), Vehicle); +} + +TDynamicObject *find_vehicle(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Vehicles, Reference); +} + +int event_sibling(basic_event const *Event) +{ + auto index{0}; + for (auto const *sibling{Events.FindEvent(Event->m_name)}; sibling != nullptr && sibling != Event; sibling = sibling->m_sibling) + ++index; + return index; +} + +basic_event *find_event(std::string const &Name, int const Sibling) +{ + auto *event{Events.FindEvent(Name)}; + for (auto index{0}; index < Sibling && event != nullptr; ++index) + event = event->m_sibling; + return event; +} + +document capture() +{ + document result; + capture_header(result); + capture_time(result); + capture_weather(result); + capture_memcells(result); + capture_tracks(result); + capture_crossings(result); + capture_made_tracks(result); + capture_power(result); + capture_events(result); + capture_launchers(result); + capture_lights(result); + // the long one last, out of the way of whoever reads the file + capture_random(result); + return result; +} + +apply_summary apply(document const &Document) +{ + apply_summary summary; + auto const *header{Document.header()}; + if (header == nullptr) + { + summary.refused = true; + summary.notes.emplace_back("not a snapshot, nothing was loaded from it"); + return summary; + } + check_scenery(*header, summary); + + // nothing in the scenery reacts to the saved state being put back: the vehicles moved to their places don't + // 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)) + Timer::set_time(timer); + apply_each(Document, "time", summary, [](record const &Entry) { + apply_time(Entry); + return true; + }); + apply_each(Document, "weather", summary, [](record const &Entry) { + apply_weather(Entry); + return true; + }); + // the switches first: a vehicle is put on the path a switch is set to + apply_each(Document, "switch", summary, apply_switch); + apply_each(Document, "track", summary, apply_track); + apply_each(Document, "crossing", summary, apply_crossing); + apply_each(Document, "madetrack", summary, apply_made_track); + apply_each(Document, "powersource", summary, apply_power); + // the cells after the vehicles, whose sections write to their cells as they're taken and freed + apply_each(Document, "memcell", summary, apply_memcell); + auto const launchers{Events.launchers()}; + apply_each(Document, "launcher", summary, [&launchers](record const &Entry) { return apply_launcher(Entry, launchers); }); + apply_each(Document, "model", summary, apply_lights); + + Events.suspend(false); + // the queue of the scenery just loaded gives way to the saved one + if (false == Document.of("event").empty() || header->has("timer")) + { + Events.clear_queue(); + apply_each(Document, "event", summary, apply_event); + } + // last, whatever was drawn at random on the way here doesn't count + apply_each(Document, "random", summary, apply_random); + 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()) + { + 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)); + return false; + } + WriteLog(std::format("snapshot: the simulation at {:.2f} s saved to \"{}\", {} entries", Timer::GetTime(), File, document.records.size())); + return true; +} + +void request(command_line const &Requests) +{ + auto &schedule{requested()}; + schedule.requests = Requests; + // the earliest first + std::ranges::stable_sort(schedule.requests.saves, {}, &command_line::save_request::time); + schedule.written = 0; + schedule.pending.reset(); + if (false == Requests.load.empty()) + schedule.pending = load(Requests.load); +} + +std::optional requested_seed() +{ + auto const &pending{requested().pending}; + auto const *header{pending.has_value() ? pending->header() : nullptr}; + if (std::uint32_t seed{0}; header != nullptr && header->get("seed", seed)) + return seed; + return std::nullopt; +} + +std::string requested_player_vehicle() +{ + auto const &pending{requested().pending}; + if (false == pending.has_value()) + return {}; + auto const players{pending->of("player")}; + return players.empty() ? std::string{} : players.front()->name; +} + +void start() +{ + auto &schedule{requested()}; + auto const loaded{schedule.pending.has_value()}; + if (loaded) + { + 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 ¬e : summary.notes) + ErrorLog(std::format("snapshot: {}", note)); + for (auto const &remark : summary.remarks) + WriteLog(std::format("snapshot: {}", remark)); + if (false == summary.refused) + { + // 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 + if (Global.local_start_vehicle == "ghostview") + { + // the cells the scripts read the weather and the time from are made by the first, not yet ready, pass. + // the run the snapshot comes from made them in its first frame; made here, the numbers their making + // draws at random don't count + auto const engine{Global.random_engine}; + State.update_scripting_interface(); + Global.random_engine = engine; + is_ready = true; + } + WriteLog(std::format("snapshot: \"{}\" loaded, the simulation goes on from {:.2f} s: {} entries put in place, {} left out", schedule.requests.load, + Timer::GetTime(), summary.entries, summary.skipped)); + } + } + // a snapshot asked for at the very time the simulation starts from + update(); + if (loaded && Timer::GetDeltaTime() == 0.0) + { + // the main loop draws a number after every frame of the simulation (eu07_application::generate_sync()), but + // not after this start. the snapshot was taken at the end of a frame, before that draw: it's made up for here + Random(1.0, 100.0); + } +} + +void update() +{ + auto &schedule{requested()}; + auto const &saves{schedule.requests.saves}; + // a frame is never short of the time asked for by the rounding of its steps alone + constexpr double margin{1e-6}; + while (schedule.written < saves.size() && Timer::GetTime() >= saves[schedule.written].time - margin) + { + save(saves[schedule.written].file); + ++schedule.written; + } +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotworld.h b/simulation/simulationsnapshotworld.h new file mode 100644 index 000000000..6402d7990 --- /dev/null +++ b/simulation/simulationsnapshotworld.h @@ -0,0 +1,67 @@ +/* +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 "simulation/simulationsnapshot.h" + +#include +#include + +class TDynamicObject; +class TTrack; +class basic_event; + +// the simulation snapshot of the running game: taken from the scenery as it is, and put over a scenery just loaded. +// the text of the file is in simulationsnapshot.h; the parts kept by a vehicle and by its driver are with those classes +// (TDynamicObject::snapshot_save() and the like, defined in simulationsnapshotvehicle.cpp and simulationsnapshotdriver.cpp) +namespace simulation::snapshot { + +// the state of the simulation as a document +document capture(); + +// how putting a snapshot over the scenery went +struct apply_summary { + int entries{0}; // put in place + int skipped{0}; // of the snapshot, with nothing in the scenery to put them on + std::vector notes; // what went other than the snapshot has it, for the user to know of + std::vector remarks; // what was done on the way, for the log + bool refused{false}; // the snapshot wasn't used at all +}; + +// puts the state of the document over the scenery, which is expected to be loaded and initialized, with the simulation +// not yet running. what the snapshot doesn't hold stays as the scenery made it +apply_summary apply(document const &Document); + +// writes a snapshot of the simulation to the file. returns: true on success +bool save(std::string const &File); + +// the snapshots asked for on the command line (parse_command_line()): one to load when the simulation starts, and the +// ones to write when its time comes +void request(command_line const &Requests); +// the seed the snapshot to be loaded was taken with, if there's one to load and it tells: the scenery loads the same +// way again only with the seed it was loaded with then +std::optional requested_seed(); +// the vehicle the player was in when the snapshot to be loaded was taken, if it tells +std::string requested_player_vehicle(); +// called when the simulation is about to start: loads the snapshot asked for +void start(); +// called at the end of each frame of the simulation: writes the snapshots due +void update(); + +// names of the things of the scenery, as the entries of a snapshot give them (reference()) +std::string track_reference(TTrack const *Track); +TTrack *find_track(std::string const &Reference); +std::string vehicle_reference(TDynamicObject const *Vehicle); +TDynamicObject *find_vehicle(std::string const &Reference); +// an event is named by its name and, among the events sharing that name, its place +int event_sibling(basic_event const *Event); +basic_event *find_event(std::string const &Name, int Sibling); + +} // namespace simulation::snapshot diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp index 6f9f87a5f..14099b714 100644 --- a/simulation/simulationtime.cpp +++ b/simulation/simulationtime.cpp @@ -193,6 +193,13 @@ void scenario_time::set_time(int yearday, int minute) { m_time.wMinute = minute % 60; } +void scenario_time::restore( SYSTEMTIME const &Time, double const Milliseconds ) { + m_time = Time; + m_milliseconds = Milliseconds; + m_time.wMilliseconds = static_cast( std::floor( m_milliseconds ) ); + m_yearday = year_day( m_time.wDay, m_time.wMonth, m_time.wYear ); +} + // calculates day of week for provided date int scenario_time::day_of_week( int const Day, int const Month, int const Year ) const { diff --git a/simulation/simulationtime.h b/simulation/simulationtime.h index aae98ee82..eec227e99 100644 --- a/simulation/simulationtime.h +++ b/simulation/simulationtime.h @@ -47,6 +47,14 @@ public: return m_timezonebias; } void set_time(int yearday, int minute); + // the part of the running second gone by [ms], with its fraction + inline + double + milliseconds() const { + return m_milliseconds; } + // sets the clock to a saved moment: the date and time of Time, Milliseconds into its second (simulation snapshot) + void + restore( SYSTEMTIME const &Time, double const Milliseconds ); /** Returns std::string in format: `"mm:ss"`. */ operator std::string(); diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp index eacd2ba0a..e8438fdca 100644 --- a/utilities/Timer.cpp +++ b/utilities/Timer.cpp @@ -69,6 +69,11 @@ void set_fixed_step(double t) fixed_step() = t; } +void set_time(double t) +{ + fSimulationTime = t; +} + void ResetTimers() { UpdateTimers( Global.iPause != 0 ); diff --git a/utilities/Timer.h b/utilities/Timer.h index 38a5d101e..240c32ee5 100644 --- a/utilities/Timer.h +++ b/utilities/Timer.h @@ -24,6 +24,9 @@ void set_fixed_step(double v); void ResetTimers(); +// sets the time of the simulation GetTime() goes on from: the one a loaded simulation snapshot was taken at +void set_time(double v); + void UpdateTimers(bool pause); class stopwatch { diff --git a/world/EvLaunch.h b/world/EvLaunch.h index e06b98ad4..29ba3dfce 100644 --- a/world/EvLaunch.h +++ b/world/EvLaunch.h @@ -39,6 +39,11 @@ public: return iKey; } bool IsGlobal() const; bool IsRadioActivated() const; + // what check_activation() counts the time with, kept and put back by a simulation snapshot + double timer() const { + return UpdatedTime; } + void timer( double const Time ) { + UpdatedTime = Time; } // members std::string asEvent1Name; std::string asEvent2Name; diff --git a/world/Event.cpp b/world/Event.cpp index 2452b7881..09cd00a3c 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -2540,6 +2540,7 @@ event_manager::FindEvent( std::string const &Name ) bool event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, double delay ) { + if( m_suspended ) { return false; } // a saved state is being put back, see suspend() if( Event->m_passive ) { return false; } // jeśli może być dodany do kolejki (nie używany w skanowaniu) if( Event->m_inqueue > 0 ) { return false; } // jeśli nie dodany jeszcze do kolejki @@ -2621,6 +2622,37 @@ event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, doub return true; } +// takes every event out of the queue +void +event_manager::clear_queue() { + + while( QueryRootEvent != nullptr ) { + auto *event { QueryRootEvent }; + QueryRootEvent = event->m_next; + event->m_next = nullptr; + event->m_inqueue = 0; + } +} + +// puts the event in the queue to run at the given time, with none of its delays added +bool +event_manager::restore_queued( basic_event *Event, TDynamicObject const *Activator, double const Launchtime ) { + + if( Event == nullptr || Event->m_inqueue > 0 ) { return false; } + + Event->m_activator = Activator; + Event->m_launchtime = Launchtime; + Event->m_inqueue = 1; + // behind the events which run no later than it does, the way AddToQuery() keeps the queue + auto **link { &QueryRootEvent }; + while( *link != nullptr && ( *link )->m_launchtime <= Launchtime ) { + link = &( *link )->m_next; + } + Event->m_next = *link; + *link = Event; + return true; +} + // legacy method, executes queued events bool event_manager::CheckQuery() { diff --git a/world/Event.h b/world/Event.h index 090d165d6..b45252e80 100644 --- a/world/Event.h +++ b/world/Event.h @@ -742,6 +742,18 @@ public: std::vector result( input.begin(), input.end() ); result.insert( result.end(), radio.begin(), radio.end() ); return result; } + // while suspended no event gets queued nor run, whoever asks for it: a simulation snapshot puts the vehicles and + // the rest of a saved state back without the scenery reacting to that + void + suspend( bool const Suspended ) { + m_suspended = Suspended; } + // takes every event out of the queue + void + clear_queue(); + // puts the event in the queue to run at the given time (Timer::GetTime()), with none of its delays added: + // for an event taken from a saved queue. returns: false if the event is in the queue already + bool + restore_queued( basic_event *Event, TDynamicObject const *Activator, double const Launchtime ); private: // types @@ -762,6 +774,7 @@ private: basic_table m_radiodrivenlaunchers; eventlauncher_sequence m_launcherqueue; command_relay m_relay; + bool m_suspended { false }; // see suspend() }; diff --git a/world/Track.h b/world/Track.h index 906cbb944..9c427891a 100644 --- a/world/Track.h +++ b/world/Track.h @@ -401,6 +401,12 @@ public: void MovedUp1(float const dh); void VelocitySet(float v); double VelocityGet(); + // the speed limit as the track keeps it, which VelocityGet() doesn't give for a damaged track, and setting it + // past what VelocitySet() makes of it on a switch: for a simulation snapshot, which puts back what it read + double velocity_limit() const { + return fVelocity; } + void velocity_limit( double const Velocity ) { + fVelocity = Velocity; } float Friction() const; // a switch has two paths, any other track the one int path_count() const; diff --git a/world/TractionPower.cpp b/world/TractionPower.cpp index 540c32fc6..01c776bb4 100644 --- a/world/TractionPower.cpp +++ b/world/TractionPower.cpp @@ -114,6 +114,27 @@ bool TTractionPowerSource::Update(double dt) return true; }; +std::vector TTractionPowerSource::state() const { + + return { NominalVoltage, TotalCurrent, TotalAdmitance, TotalPreviousAdmitance, OutputVoltage, + FastFuse ? 1.0 : 0.0, SlowFuse ? 1.0 : 0.0, FuseTimer, static_cast( FuseCounter ) }; +} + +void TTractionPowerSource::state( std::vector const &State ) { + + // a list of another length comes from a build which keeps other things + if( State.size() != 9 ) { return; } + NominalVoltage = State[ 0 ]; + TotalCurrent = State[ 1 ]; + TotalAdmitance = State[ 2 ]; + TotalPreviousAdmitance = State[ 3 ]; + OutputVoltage = State[ 4 ]; + FastFuse = State[ 5 ] != 0.0; + SlowFuse = State[ 6 ] != 0.0; + FuseTimer = State[ 7 ]; + FuseCounter = static_cast( State[ 8 ] ); +} + double TTractionPowerSource::CurrentGet(double res) { // pobranie wartości prądu przypadającego na rezystancję (res) // niech pamięta poprzednią admitancję i wg niej przydziela prąd diff --git a/world/TractionPower.h b/world/TractionPower.h index 61127ae06..30e4e7c14 100644 --- a/world/TractionPower.h +++ b/world/TractionPower.h @@ -13,6 +13,8 @@ http://mozilla.org/MPL/2.0/. #include "scene/scenenode.h" #include "utilities/Names.h" +#include + class TTractionPowerSource : public scene::basic_node { friend class debug_panel; @@ -30,6 +32,9 @@ public: void PowerSet(TTractionPowerSource *ps); bool Fuse() const { return FastFuse || SlowFuse; } + // what the source keeps from one step to the next (its voltage, load and fuses), read and put back by a snapshot of the simulation + std::vector state() const; + void state( std::vector const &State ); // members TTractionPowerSource *psNode[ 2 ] = { nullptr, nullptr }; // zasilanie na końcach dla sekcji bool bSection = false; // czy jest sekcją