18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 06:35:21 +01:00
Files
maszyna/simulation/simulationsnapshotworld.cpp
jerrrrycho ed8708c5e2 feat(simulation): snapshots, save the state of a running scenery and load it back (stage A) (#420)
* feat(simulation): text format of simulation snapshots

A snapshot of a running simulation is a text file in the syntax of the scenery
files: entries of the form <type> <name> <key> <value> ... end<type>, the first
one a header which names the scenery. This is the text alone: entries, writer,
reader, the names of the things of a scenery, the plan of coupling changes and
the command line switches (--load-snapshot, --snapshot-at), in the core library
with unit tests. Nothing reads or writes a snapshot yet.

* feat(simulation): snapshot of time, weather, cells, switches and events (L1)

--snapshot-at <seconds> <file> writes a snapshot when the simulation has run
that long, --load-snapshot <file> puts one over the scenery once it has loaded,
before the first frame. This layer keeps the clock and the simulation timer,
the weather with the wind, the random engine, the memory cells, the switches,
the tracks an event can change and the ones made on the run, the traction
power sources, the event queue, the timers of the launchers and the lamps of
the signals.

While a snapshot is put back the event manager is suspended, so nothing in the
scenery reacts to it. Existing classes only get accessors for what was private
(the fraction of the second, launcher timers, the speed limit of a track, the
wind, the state of a power source, the event queue). Without the switches
nothing changes.

* feat(simulation): state of a vehicle's physics for snapshots (L3, core)

What TMoverParameters holds of a running vehicle, to and from an entry of a
snapshot: speed, load, controls, switches and relays, pantographs, doors,
engine and its cooling, the air of the pipes, of every reservoir of the brake
valve (with the flow it has yet to take in) and of the chambers of the driver's
valves, the vigilance device, the power circuits. In the core library, tested
on the real vehicle definitions: a
vehicle restored on a fresh one saves the same, and runs on next to the one it
was saved from.

The brake valves, the driver's valves and the vigilance device get accessors
for their private state (reservoirs(), latches(), pressures(), state()), a
reservoir one for the flow it has yet to take in; nothing else in the physics
changes. This comes before the vehicles of the scenery (L2), whose
speed and load are kept by it.

* feat(simulation): snapshot of vehicles and consists (L2)

Every vehicle is kept with the place of both its axles (track, distance,
direction, path of a switch, events still to set off), the way it faces, its
couplings with their flags, destination and, through its physics, speed and
load. Loaded, the vehicles are put straight where they were
(TTrackFollower::Place(), which trails no switch and fires no event), then
parted and joined until they are coupled as saved, whatever trainsets the
scenery made of them.

A vehicle of the snapshot the scenery does not have is skipped and reported,
one the snapshot does not know stays as the scenery made it, one which had left
the simulation is taken out again.

* feat(simulation): pantographs and passenger exchange in snapshots (L3)

What a vehicle keeps of its machinery beside its physics: the arms of the
pantographs as they stand under the wire, the time without voltage, the
passengers getting on and off, the lighting of the compartments, the headlight
toggles, the last force asked of the electrodynamic brake.

* feat(simulation): snapshot of the drivers and of the player's vehicle (L4)

A driver is kept with its orders and the one it is on, the name of its
timetable and its place in it, the consist it has, what it holds to (speeds of
signals and limits, the reason it stands, its timers and flags), its table of
what is ahead on the track with the point limits it has latched, its tables of
what the brake of the consist gives, and whether the AI drives. A driver who
had moved to another vehicle of its train is moved there.

A run loaded in ghost view (the test mode) is ready before its first frame, as
the run it goes on from was.

The snapshot also names the vehicle the player was in, which --load-snapshot
starts in unless -v says otherwise.

* feat(simulation): snapshotsave command, on [Ctrl]+[Shift]+[F9]

Writes a snapshot of the simulation to snapshots/<scenery>_<date>_<time>.snapshot
in the game folder. The command is the last one of the list, so the numbers of
the others stay.

* test: scenario cases which load a simulation snapshot and compare the run

A case with a "snapshot" section runs its scenery to a time, taking snapshots
on the way and at the end, then again from the first snapshot, and compares the
two ends: positions, speeds, pressures, couplings, cells, switches, drivers.
The snapshot saved right after loading has to be the one loaded.
tests/scenarios/snapshots.py reads the format and tells two snapshots apart.
The switches and the format are described in tests/scenarios/README.md.

* fix(simulation): a vehicle gone in the snapshot leaves its isolated sections

The scenery counts the axles of every vehicle in the isolated sections of
the tracks it puts it on. A vehicle the snapshot has as removed was only
taken off the list of its track, so its two axles stayed counted there and
the section never went free again: the next train on it went 4-6-4 axles
instead of 0-2-0, and its busy and free events never fired.

- A removed vehicle counts both axles out of the sections of their tracks,
  is taken off the list of its track only if it's on it, and has no owner.
- The drivers a snapshot doesn't have are deleted as before, and no
  vehicle keeps its owner pointing at one of them.
- The snapshot keeps the count of every isolated section and sets it after
  the vehicles are placed: the vehicles a consist leaves behind as it goes
  through a portal stay counted where they were, in the game too. A count
  the placing gives other than the snapshot has is told in the log.
- A vehicle with two entries is placed once.
- TIsolated::axles() reads and sets the count.
- The harness compares the counts of the sections; a new case,
  snapshot_td_portal_isolated, has a train leave through a portal from the
  track of a section before the snapshot.

* 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 <file>.tmp and renamed over the file only when
  the stream didn't fail.
- Unit tests of the reader on damaged input.

* feat(simulation): the pullee mode and the holding brake timer in snapshots

Of what #419 and #424 added to TMoverParameters, two are state: PulleeMode
(prepared for being hauled dead; the scenery sets it, PulleeModeSwitch()
can change it) and StopBrakeReleaseTimer (how long power has been asked
for, which lets the holding brake of a unit go after its delay). Both are
kept now, as "pulleemode" and "stopbrakereleasetimer". The others
(PressureSwitchBrakeCylinder, EmergencyBrakeMainOffPressure,
StopBrakeReleaseDelay) come from the vehicle definition and aren't.

* fix(simulation): the snapshot code without Sonar issues

No declaration shadows an enumerator, the variables used only by a
condition are declared in it, write_file takes its writer as a template,
the temporary file is a std::filesystem::path, the isolated sections are
looked up by a transparent hash, apply_couplings is split into helpers,
and the copies of the simulation's random engine are marked NOSONAR.
The test data has no http:// in it. No snapshot key or format changes.

* fix(brakes): TSt113 lists the control pressure once

TSt113::pressures() added CP on top of TH14K1::pressures(), which
already has it since #366 removed the CP of TSt113 that hid it. A
snapshot held the St113's control chamber twice. The second entry is
removed.

Tests: every driver's handle lists each pressure once, and the St113
pressures of an EN57 saved through a snapshot come back on a fresh one.

* fix(simulation): snapshots skip road traffic, refuse changed sceneries, keep misplaced vehicles apart

Cars of the road spawn points which a snapshot has on the road are no longer put back: the spawn point owns
them and the snapshot would leave them frozen on the track. They're counted in the log. The pooled cars keep
their AI drivers, which the snapshot used to delete.

A snapshot whose scenery fingerprint differs is refused unless --load-snapshot-force is given: tracks named
"#N" shift when a track is added. Each vehicle is checked against the x/y/z of its entry after placing. One
more than 1 m off, or one which can't be placed, goes back where the scenery put it, isn't coupled to the
placed vehicles, and keeps its scenery state and driver.

Couplings set from a snapshot keep to CompatibleCoupling, so no MU control between an electric and a diesel
loco (#520).

The snapshotsave key writes to snapshotsdir of eu07.ini (snapshots by default, ini only like screenshotsdir),
adds _2, _3... to a name that is taken, and shows where the file went.

* refactor(simulation): the snapshot reads and writes the private state of the vehicles through their own members

Since #552 the state of physics::Vehicle and of its parts is private, and since #531 the vehicle, the AI
and the cab live in other files under other names. The snapshot code is ported to that:

- the state of a vehicle's physics is saved and loaded by physics::Vehicle::SnapshotSave() and
  SnapshotLoad() (physics/components/snapshot.cpp), with the tables of the variables in a nested
  snapshot_members; capture_mover() and apply_mover() only hand it the entry. The parts with private
  state (low voltage, line breaker, line contactors, protective relays, converter, air of the
  pantographs, compressor, air supply) give a plain Snapshot of it and take it back
  (TakeSnapshot(), RestoreSnapshot()); the rest goes through their queries and setters
- the keys, their order and the numbers in them are unchanged, so the snapshots written before load:
  the fields that moved into the parts are mapped there (Mains to lineBreaker, PipePress to brakePipe,
  BrakeCtrlPos to brakes, dizel_* to diesel, hydro_* to torqueConverter and retarder, eimv to
  inductionMotor.state in the order of the old table, EngDmgFlag to equipmentFaults, ...)
- TDynamicObject: the machinery of a vehicle (sections, rail joints, the passenger exchange) is saved
  by members of its own, as these are private now; MED_oldFED is the last ED demand of the consist's
  brake blending (ConsistBrakeBlending::LastElectrodynamicDemand())
- TController: the driving flags are saved as the bits of iDrivigFlags they were, the running brake
  test as the number of its stage, the uphill start and the braking shortfall from their structs;
  StaticBrakeTest, which is gone, is written as 0 and not read
- the couplings take Coupling, CouplingSet and VehicleEnd; orders are DriverOrders
- the unit tests of the snapshot of a vehicle use the queries and the parts

* fix(simulation): carry the driver's coupling set in the snapshot as the bits of the set

iCoupler is a CouplingSet since 2098614f, which record::set()/get() can't take. It goes
through the converted values as a whole number, as the driving flags do: Bits() on save,
CouplingSet::FromBits() on load. The key and its values are the same as before.

* fix(simulation): a loaded snapshot counts the vehicles it left where they stand

apply_isolated() set every isolated section to the count of the snapshot, also where a
vehicle the load left at its scenery place (misplaced, forced load, road traffic not put
back) stands, or where the snapshot had it. The axles of those vehicles are now counted in
the sections they stand in and out of the ones the snapshot has them in, and the memory
cells of those sections say whether they are taken by that count.

An AI consist doesn't end on a vehicle the load left: the ends are then found along what is
coupled now, as CheckVehicles() finds them.

The player entry no longer writes the cab, which nothing read: the cab is the one the
vehicle has occupied (caboccupied of its entry).

* feat(simulation): the snapshot keeps a derailment and the brakes of a sleeping vehicle

A derailed vehicle came back on the rails. Its entry now keeps what derailed it (outcome,
cause, speed, the cause and side of the motion off the track, the acceleration, the
collision derailment) and the distance its criteria were last checked over; the
derailment the scenery and the test mode were told of (new_derailment()), so it isn't told
again; and with physics.derailment new the motion of the body off the track
(derail_motion::body::state()) with the timers of the vehicle off the track. The terrain
under it is gathered anew around it when it loads.

sleep_brakes, what a sleeping vehicle's brake force came from, is kept too.

All keys are new: an entry without them leaves the vehicle as the scenery made it, so files
written before still load. New scenario case snapshot_td_off_track.

* fix(simulation): the snapshot keeps the sanded start of an AI driver

#494 (in staging since the last runs of the snapshot cases) made a driver whose start
slipped keep sanding under power until the train is under way, and take the power down a
step at a time. Neither the flag nor the time of the last step down was kept, so on
linia61 the loaded run sanded one frame later than the run which went on and parted from
it 0.06 s after loading (suwnica2, 9 mm and 0.08 km/h at 600 s). Both are kept now
(sandedstart, sandedstarttime); an entry without them leaves the driver as it is.

* fix(simulation): the snapshot keeps a train running forked on a switch thrown under it

Staging's switch fork running (#496) gave the axles and the vehicles state of their own: the way of a
switch an axle ran onto (TTrackFollower::iPath, which it leaves the switch by after a throw), the ways it
remembers of the switches behind it (path_memory, read when the axle behind it comes onto one of them),
and per vehicle the switch its bogies or its coupled ends run forked on with whether that was told
(m_forkbogies, m_forkends). None of it was in a snapshot: a loaded train on a switch thrown under it
would have left it by the way it is set now and never derailed running forked.

- Place() sets the way of the switch from the path the axle is put on, as SetCurrentTrack() does, and
  clears the facing entry the vehicle hasn't looked at (there is none between frames).
- A vehicle entry has the remembered ways of each axle, oldest first (axle0switch0, axle0way0...),
  recorded again into an empty memory on load (path_memory::entries()), and the forked watches
  (forkbogies, fork0, fork1 with their "told"). A name which isn't a switch is refused.
- New case snapshot_td_switch_thrown: the snapshot is taken while the second coach of
  eu07_td_switch_thrown_facing_behind_derails runs forked and hasn't derailed yet; the loaded run derails
  it the same way and the two files at 150 s are identical.
2026-12-02 15:40:25 +01:00

1417 lines
52 KiB
C++

/*
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 "physics/vehicle.h"
#include "application/uitranscripts.h"
#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"
#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 <algorithm>
#include <filesystem>
#include <format>
#include <fstream>
#include <functional>
#include <iterator>
#include <map>
#include <sstream>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
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."};
// 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 <typename Item_> 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 <typename Sequence_> 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 <typename Sequence_> 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<Item_ const *, std::size_t> m_places;
};
// a thing of a table by its reference: its name, or its place
template <typename Table_> 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 <typename Table_, typename Item_> std::string reference_in(Table_ const &Table, table_index<Item_> &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<TTrack> &track_index()
{
static table_index<TTrack> index;
return index;
}
table_index<TDynamicObject> &vehicle_index()
{
static table_index<TDynamicObject> index;
return index;
}
table_index<TTractionPowerSource> &powersource_index()
{
static table_index<TTractionPowerSource> index;
return index;
}
table_index<TAnimModel> &model_index()
{
static table_index<TAnimModel> 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 *scenery_event : Events.sequence())
names.add(scenery_event != nullptr ? scenery_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());
}
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()};
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;
if (constexpr std::array<WORD, 13> days{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
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)
{
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<double> wind;
for (auto const value : Environment.wind_state())
wind.emplace_back(value);
entry.set("wind", numbers_text(wind));
}
void apply_weather(record const &Entry)
{
// 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())
{
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<float>(Value); });
Environment.wind_state(state);
}
else
Entry.refuse("wind", "a number of it isn't finite");
}
}
// 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;
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<int>::max()).has_value())
{
Entry.refuse("state", "the count of its fuse isn't a whole number");
return true;
}
source->state(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}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses
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, 0, 5)};
if (index < 0 || 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 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);
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, 0, 1) && state != track->GetSwitchState())
track->Switch(state);
if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_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, -big_velocity, big_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 *queued{Events.begin()}; queued != nullptr; queued = queued->m_next)
{
auto &entry{Document.add("event", queued->m_name)};
if (auto const sibling{event_sibling(queued)}; 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", queued->m_launchtime).set("left", queued->m_launchtime - now);
if (queued->m_activator != nullptr)
entry.set("activator", vehicle_reference(queued->m_activator));
}
}
bool apply_event(record const &Entry)
{
auto sibling{0};
if (false == Entry.get("sibling", sibling, 0, most_siblings) && Entry.has("sibling"))
return false;
auto *found{find_event(Entry.name, sibling)};
if (found == nullptr)
return false;
// 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(found, activator, launchtime);
}
void capture_launchers(document &Document)
{
auto const launchers{Events.launchers()};
std::map<std::string, int, std::less<>> 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<TEventLauncher *> 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(), 0.0, longest_wait));
return true;
}
// the models whose lights the events of the scenery switch: the signals, mostly
std::vector<TAnimModel *> switched_models()
{
std::vector<TAnimModel *> models;
std::unordered_set<scene::basic_node const *> seen;
for (auto const *scenery_event : Events.sequence())
{
if (dynamic_cast<lights_event const *>(scenery_event) == nullptr)
continue;
for (auto *node : scenery_event->target_nodes())
{
if (seen.emplace(node).second)
models.emplace_back(static_cast<TAnimModel *>(node));
}
}
return models;
}
void capture_lights(document &Document)
{
for (auto *model : switched_models())
{
auto const name{reference_in(Instances, model_index(), static_cast<TAnimModel const *>(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, -1e6f, 1e6f))
model->LightSet(light, state);
}
return true;
}
void capture_vehicles(document &Document)
{
for (auto const *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->physics == nullptr)
continue;
vehicle->snapshot_save(Document.add("vehicle", vehicle_reference(vehicle)));
}
}
// the couplings as the vehicles have them now
std::vector<coupling_link> current_couplings(std::unordered_map<physics::Vehicle const *, TDynamicObject *> const &Owners)
{
std::vector<coupling_link> links;
for (auto const *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->physics == nullptr)
continue;
for (auto const side : VehicleEnds)
{
auto const &joint{vehicle->physics->Couplers[side]};
auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()};
if (owner == Owners.end() || joint.CouplingFlag.Empty())
continue;
links.emplace_back(vehicle_reference(vehicle), NumberOf(side), vehicle_reference(owner->second), joint.ConnectedNr, joint.CouplingFlag.Bits());
}
}
return links;
}
static_assert(coupling_flags_mask == (static_cast<int>(Coupling::power3x400v) << 1) - 1, "the flags a snapshot takes are every bit of the coupling enum");
void part(TDynamicObject &Vehicle, int const End)
{
auto &joint{Vehicle.physics->Couplers[End]};
if (joint.Connected != nullptr && joint.ConnectedNr >= 0 && joint.ConnectedNr < 2)
{
auto &other{joint.Connected->Couplers[joint.ConnectedNr]};
other.Connected = nullptr;
other.ConnectedNr = -1;
other.CouplingFlag = CouplingSet{};
}
joint.Connected = nullptr;
joint.ConnectedNr = -1;
joint.CouplingFlag = CouplingSet{};
}
// whether the vehicle is there, with its physics
bool with_physics(TDynamicObject const *Vehicle)
{
return Vehicle != nullptr && Vehicle->physics != nullptr;
}
// the flags of the link as the two vehicles can have them now: no control between an electric and a diesel locomotive
// (eu07/maszyna#520), whatever an edited file or a vehicle definition changed since the snapshot says
int compatible_flags(TDynamicObject const &Vehicle, TDynamicObject const &Other, coupling_link const &Link)
{
return Vehicle.physics->CompatibleCoupling(EndOf(Link.end), *Other.physics, EndOf(Link.otherend), CouplingSet::FromBits(Link.flags)).Bits();
}
// the links of the plan which change the kind of a coupling the vehicles keep
void change_couplings(std::vector<coupling_link> const &Links)
{
for (auto const &link : Links)
{
auto const *vehicle{find_vehicle(link.vehicle)};
auto const *other{find_vehicle(link.other)};
if (false == with_physics(vehicle) || false == with_physics(other))
continue;
auto const flags{compatible_flags(*vehicle, *other, link)};
if (flags == 0)
continue;
vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags);
other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags);
}
}
// the links of the plan to make. returns: how many couldn't be made
int join_couplings(std::vector<coupling_link> const &Links)
{
auto failed{0};
for (auto const &link : Links)
{
auto *vehicle{find_vehicle(link.vehicle)};
auto *other{find_vehicle(link.other)};
if (false == with_physics(vehicle) || false == with_physics(other) ||
false == vehicle->physics->Attach(link.end, link.otherend, other->physics, CouplingSet::FromBits(link.flags), true, false))
{
++failed;
continue;
}
// the vehicles joined in the snapshot, whatever the scenery made of their couplers, as far as they can be
auto const flags{compatible_flags(*vehicle, *other, link)};
vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags);
other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags);
}
return failed;
}
void report_couplings(coupling_plan const &Plan, int const Failed, apply_summary &Summary)
{
if (false == Plan.part.empty() || false == Plan.join.empty() || false == Plan.change.empty())
Summary.remarks.emplace_back(std::format("couplings: {} parted, {} joined, {} changed", Plan.part.size(), static_cast<int>(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 or which stay where it put them",
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
void find_neighbours(std::unordered_map<physics::Vehicle const *, TDynamicObject *> const &Owners)
{
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->physics == nullptr)
continue;
for (auto const side : VehicleEnds)
{
auto const &joint{vehicle->physics->Couplers[side]};
auto &neighbour{vehicle->physics->Neighbours[side]};
neighbour = neighbour_data();
if (auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()}; owner != Owners.end())
{
neighbour.vehicle = owner->second;
neighbour.vehicle_end = joint.ConnectedNr;
}
}
}
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle != nullptr && vehicle->physics != nullptr && vehicle->bEnabled)
vehicle->update_neighbours();
}
}
// the vehicles of the snapshot which stay as the scenery made them: the ones it couldn't put where the snapshot has
// them, and the road traffic waiting at its spawn point
using vehicle_set = std::unordered_set<TDynamicObject const *>;
// parts and joins the vehicles of the scenery until they're coupled the way the snapshot has them. the vehicles Left
// aren't coupled to the ones put where the snapshot has them: the links to them are missing
void apply_couplings(std::vector<record const *> const &Entries, vehicle_set const &Left, apply_summary &Summary)
{
std::unordered_map<physics::Vehicle const *, TDynamicObject *> owners;
std::vector<std::string> present;
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->physics == nullptr)
continue;
owners.emplace(vehicle->physics, vehicle);
if (false == Left.contains(vehicle))
present.emplace_back(vehicle_reference(vehicle));
}
std::vector<record const *> entries;
std::ranges::copy_if(Entries, std::back_inserter(entries), [&Left](record const *Entry) { return false == Left.contains(find_vehicle(Entry->name)); });
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
for (auto const &link : plan.part)
{
if (auto *vehicle{find_vehicle(link.vehicle)}; with_physics(vehicle))
part(*vehicle, link.end);
}
change_couplings(plan.change);
auto const failed{join_couplings(plan.join)};
report_couplings(plan, failed, Summary);
find_neighbours(owners);
}
// a vehicle the scenery keeps out of the simulation until its time comes: a car a road spawn point (roadpoint_node) made
// as the scenery loaded, which waits off the road to be put on it. the snapshot doesn't bring one which was on the
// road back: the spawn point puts its cars on the road and takes them back to its set, and a car put there by the
// snapshot would be one the point doesn't know is out
bool waits_off_the_road(TDynamicObject const &Vehicle)
{
return false == Vehicle.bEnabled && Vehicle.MyTrack == nullptr;
}
// the vehicles of the snapshot's entries
struct vehicle_entries {
std::vector<std::pair<TDynamicObject *, record const *>> known; // to put where the snapshot has them
vehicle_set listed; // every vehicle of the scenery the snapshot has
vehicle_set left; // the ones of them left as the scenery made them
};
vehicle_entries read_vehicles(std::vector<record const *> const &Entries, apply_summary &Summary)
{
vehicle_entries result;
auto traffic{0};
for (auto const *entry : Entries)
{
auto *vehicle{find_vehicle(entry->name)};
if (vehicle == nullptr || vehicle->physics == nullptr)
{
++Summary.skipped;
Summary.notes.emplace_back(std::format("vehicle {} of the snapshot isn't in the scenery", entry->name));
continue;
}
// a vehicle placed twice would have its axles counted out of their sections twice
if (false == result.listed.emplace(vehicle).second)
{
++Summary.skipped;
Summary.notes.emplace_back(std::format("vehicle {} has more than one entry in the snapshot, the first one is taken", entry->name));
continue;
}
if (false == waits_off_the_road(*vehicle))
{
result.known.emplace_back(vehicle, entry);
continue;
}
// off the road in the snapshot too, or a car of the road traffic which isn't brought back
result.left.emplace(vehicle);
if (entry->value("removed", false))
{
++Summary.entries;
continue;
}
++Summary.skipped;
++traffic;
}
if (traffic != 0)
Summary.notes.emplace_back(std::format("{} cars of the road traffic of the snapshot aren't put back, their spawn points send cars anew", traffic));
return result;
}
// puts the vehicles of the snapshot in place. returns: the vehicles of the snapshot left as the scenery made them
vehicle_set apply_vehicles(document const &Document, apply_summary &Summary)
{
auto const entries{Document.of("vehicle")};
auto vehicles{read_vehicles(entries, Summary)};
auto const &known{vehicles.known};
auto const &listed{vehicles.listed};
auto &left{vehicles.left};
// where the vehicles are, then what they're coupled to, then what they're doing. a vehicle which can't be put where
// the snapshot has it is left out of the rest: coupled to vehicles put elsewhere, it'd be torn off them
auto misplaced{0};
for (auto const &[vehicle, entry] : known)
{
if (false == vehicle->snapshot_place(*entry))
{
++misplaced;
left.emplace(vehicle);
}
}
if (misplaced != 0)
Summary.notes.emplace_back(std::format("{} vehicles of the snapshot couldn't be put where it has them, they stay as the scenery made them", misplaced));
apply_couplings(entries, left, Summary);
for (auto const &[vehicle, entry] : known)
{
if (left.contains(vehicle))
{
++Summary.skipped;
continue;
}
vehicle->snapshot_load(*entry);
++Summary.entries;
}
// the vehicles the snapshot doesn't know stay as the scenery made them
if (auto const unknown{std::ranges::count_if(Vehicles.sequence(), [&](TDynamicObject const *Vehicle) { return Vehicle != nullptr && false == listed.contains(Vehicle); })};
unknown != 0)
Summary.notes.emplace_back(std::format("{} vehicles of the scenery aren't in the snapshot, they stay as the scenery made them", unknown));
return std::move(left);
}
// a hash of the text of a name, which finds a string key by any kind of string
struct name_hash {
using is_transparent = void;
std::size_t operator()(std::string_view const Name) const noexcept { return std::hash<std::string_view>{}(Name); }
};
using isolated_map = std::unordered_map<std::string, TIsolated *, name_hash, std::equal_to<>>;
// the isolated sections, by their names: the scenery makes one for each name (TIsolated::Find())
isolated_map isolated_sections()
{
isolated_map sections;
for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next())
sections.try_emplace(section->asName, section);
return sections;
}
// how many axles each isolated section counts. in a running simulation it's the vehicles on its tracks, but not only:
// the vehicles of a consist which follow its first one out through a portal leave the simulation where they are, and
// stay counted there. a snapshot keeps the counts as they are
void capture_isolated(document &Document)
{
for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next())
Document.add("isolated", section->asName).set("axles", section->axles());
}
// how many axles more or fewer each isolated section counts than the snapshot has, for the axles of the vehicles left as
// the scenery made them: they stand where the scenery put them, not where the snapshot has them
using section_counts = std::unordered_map<TIsolated *, int>;
// counts Axles in every section of the Track and in the sections those pass their counts to (TIsolated::Modify())
void count_axles(TTrack const *Track, int const Axles, section_counts &Counts)
{
if (Track == nullptr)
return;
for (auto *section : Track->Isolated)
{
for (; section != nullptr; section = section->parent())
Counts[section] += Axles;
}
}
// the axles of the Left vehicles: counted in the sections they stand in now, and out of the ones the snapshot has them in
section_counts left_axles(document const &Document, vehicle_set const &Left)
{
section_counts counts;
if (Left.empty())
return counts;
vehicle_set seen;
for (auto const *entry : Document.of("vehicle"))
{
// the first entry of a vehicle is the one taken (read_vehicles())
auto const *vehicle{find_vehicle(entry->name)};
if (vehicle == nullptr || false == Left.contains(vehicle) || false == seen.emplace(vehicle).second)
continue;
// a car off the road waits in its spawn point's set, on no track
if (vehicle->MyTrack != nullptr)
{
count_axles(vehicle->Axle0.GetTrack(), 1, counts);
count_axles(vehicle->Axle1.GetTrack(), 1, counts);
}
if (false == entry->value("removed", false))
{
count_axles(find_track(entry->text("track0")), -1, counts);
count_axles(find_track(entry->text("track1")), -1, counts);
}
}
std::erase_if(counts, [](auto const &Count) { return Count.second == 0; });
return counts;
}
// sets the counts of the isolated sections to those of the snapshot, after the vehicles are put on their tracks: which
// counts them anew. a section whose count comes out other than the snapshot has is told of. the axles of the vehicles
// left as the scenery made them (Left) are counted where they stand instead of where the snapshot has them. returns:
// the sections whose counts that changed
std::vector<TIsolated *> apply_isolated(document const &Document, section_counts const &Left, apply_summary &Summary)
{
std::vector<TIsolated *> moved;
auto const entries{Document.of("isolated")};
if (entries.empty())
return moved;
auto const sections{isolated_sections()};
auto missing{0};
auto differing{0};
std::string example;
for (auto const *entry : entries)
{
auto const lookup{sections.find(entry->name)};
if (lookup == sections.end())
{
++Summary.skipped;
++missing;
continue;
}
// a count beyond any the vehicles of a scenery make
auto axles{0};
if (false == entry->get("axles", axles, -1000000, 1000000))
{
++Summary.skipped;
continue;
}
auto *section{lookup->second};
if (auto const left{Left.find(section)}; left != Left.end())
{
// no fewer than none: a snapshot taken in another scenery can name a track the vehicle wasn't on
axles = std::max(axles + left->second, 0);
moved.emplace_back(section);
}
if (section->axles() != axles)
{
if (differing++ == 0)
example = std::format("{}: {} axles, the snapshot has {}", section->asName, section->axles(), axles);
section->axles(axles);
}
++Summary.entries;
}
if (missing != 0)
Summary.notes.emplace_back(std::format("{} isolated sections of the snapshot aren't in the scenery", missing));
if (false == moved.empty())
Summary.notes.emplace_back(std::format("{} isolated sections count the axles of vehicles left where the scenery put them instead of where the snapshot has them; the first one {}",
moved.size(), moved.front()->asName));
// not a fault as such: the vehicles a consist leaves behind as it goes through a portal stay counted where they were
if (differing != 0)
Summary.remarks.emplace_back(std::format("{} isolated sections counted other axles with the vehicles placed than the snapshot has, set to its counts; the first one {}",
differing, example));
return moved;
}
// the cells of the sections whose counts the left vehicles changed say whether they're taken by the count, not by the
// snapshot: as TIsolated::Modify() writes them, the lowest bits of the second value
void apply_isolated_cells(std::vector<TIsolated *> const &Sections)
{
for (auto const *section : Sections)
{
if (section->pMemCell == nullptr)
continue;
auto const value{static_cast<int>(section->pMemCell->Value2())};
auto const busy{section->axles() > 0};
if (busy != ((value & 1) != 0))
section->pMemCell->UpdateValues("", 0, busy ? value | 1 : value & ~0xFF, basic_event::flags::value2);
}
}
void capture_drivers(document &Document)
{
for (auto const *vehicle : Vehicles.sequence())
{
if (vehicle != nullptr && vehicle->bEnabled && vehicle->Mechanik != nullptr)
vehicle->Mechanik->snapshot_save(Document.add("driver", vehicle_reference(vehicle)));
}
}
// a driver of the consist of the vehicle whom the snapshot doesn't have where the scenery put them: the one to move
// to the vehicle, where the snapshot has a driver and the scenery none (a driver changes ends of a train)
TController *spare_driver(TDynamicObject *Vehicle, std::unordered_set<TDynamicObject const *> const &Taken)
{
TController *found{nullptr};
Vehicle->for_each(Coupling::coupler, [&found, &Taken](TDynamicObject const *Coupled) {
if (found == nullptr && Coupled->Mechanik != nullptr && false == Taken.contains(Coupled))
found = Coupled->Mechanik;
});
return found;
}
// the drivers of the snapshot, in the vehicles it has them in. the vehicles Left keep the drivers the scenery gave them
void apply_drivers(document const &Document, vehicle_set const &Left, apply_summary &Summary)
{
auto const entries{Document.of("driver")};
if (entries.empty())
return;
// the vehicles the snapshot has drivers in
std::unordered_set<TDynamicObject const *> taken;
for (auto const *entry : entries)
taken.emplace(find_vehicle(entry->name));
auto missing{0};
for (auto const *entry : entries)
{
auto *vehicle{find_vehicle(entry->name)};
if (Left.contains(vehicle))
{
++Summary.skipped;
continue;
}
if (vehicle == nullptr)
{
++Summary.skipped;
++missing;
continue;
}
if (vehicle->Mechanik == nullptr)
{
if (auto *spare{spare_driver(vehicle, taken)}; spare != nullptr)
spare->MoveTo(vehicle);
}
if (vehicle->Mechanik == nullptr)
{
++Summary.skipped;
++missing;
continue;
}
vehicle->Mechanik->snapshot_load(*entry, [&Left](TDynamicObject const *Vehicle) { return Left.contains(Vehicle); });
++Summary.entries;
}
if (missing != 0)
Summary.notes.emplace_back(std::format("{} drivers of the snapshot have no driver in the scenery to become", missing));
// the drivers of the scenery the snapshot has no word of, in vehicles it does know, were gone when it was taken
std::unordered_set<TDynamicObject const *> known;
for (auto const *entry : Document.of("vehicle"))
known.emplace(find_vehicle(entry->name));
std::unordered_set<TController const *> deleted;
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->Mechanik == nullptr || taken.contains(vehicle) || false == known.contains(vehicle) || Left.contains(vehicle))
continue;
if (vehicle->Mechanik->AIControllFlag())
{
deleted.emplace(vehicle->Mechanik);
SafeDelete(vehicle->Mechanik);
}
}
// the other vehicles of their consists had them in charge: those the snapshot has get their owners anew
// (apply_owners()), but no vehicle is left pointing at a driver who's no more
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle != nullptr && deleted.contains(vehicle->ctOwner))
vehicle->ctOwner = nullptr;
}
}
// the driver in charge of each vehicle; after the drivers are where the snapshot has them. the vehicles Left keep
// theirs
void apply_owners(document const &Document, vehicle_set const &Left)
{
for (auto const *entry : Document.of("vehicle"))
{
auto *vehicle{find_vehicle(entry->name)};
if (vehicle == nullptr || Left.contains(vehicle))
continue;
// a vehicle gone from the simulation has nobody in charge
if (entry->value("removed", false))
{
vehicle->ctOwner = nullptr;
continue;
}
if (false == entry->has("first"))
continue;
auto const *owner{find_vehicle(entry->text("owner"))};
vehicle->ctOwner = (owner != nullptr ? owner->Mechanik : nullptr);
}
}
void capture_player(document &Document)
{
if (Train == nullptr || Train->Dynamic() == nullptr)
return;
auto const *vehicle{Train->Dynamic()};
// by its name, which is what the simulator is started in a vehicle with. the cab the player is in is the one the
// vehicle has occupied, which its entry keeps (caboccupied); a file written before has it here too, as cab, unread
Document.add("player", vehicle->name());
}
// tells whether the snapshot was taken in the scenery it's being put over. returns: false if the scenery isn't what it
// was then, which the snapshot isn't put over unless that's forced
bool check_scenery(record const &Header, bool const Force, apply_summary &Summary)
{
if (auto const scenery{Header.text("scenery")}; scenery != Global.SceneryFile)
Summary.notes.emplace_back(std::format(R"(the snapshot was taken in scenery "{}", this one is "{}")", scenery, Global.SceneryFile));
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));
}
record now;
capture_fingerprint(now);
auto const changed{fingerprint_changes(Header, now)};
if (changed.empty())
return true;
// most tracks have no name and are named by their place: a track added early in a file of the scenery moves the
// places of all after it, and the vehicles would be put on other tracks than they were on
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 (Force)
return true;
Summary.notes.emplace_back("the snapshot isn't loaded (--load-snapshot-force loads it all the same)");
return false;
}
// applies the entries of a type, each by the function given, and counts how it went
template <typename Function_> 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<document> 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 *found{Events.FindEvent(Name)};
auto index{0};
while (index < Sibling && found != nullptr)
{
found = found->m_sibling;
++index;
}
return found;
}
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);
capture_vehicles(result);
capture_isolated(result);
capture_drivers(result);
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;
}
apply_summary apply(document const &Document, bool const Force)
{
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;
}
if (false == check_scenery(*header, Force, summary))
{
summary.refused = true;
return 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, 0.0, longest_wait))
Timer::set_time(timer);
apply_each(Document, "time", summary, apply_time);
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);
auto const left{apply_vehicles(Document, summary)};
// the sections the vehicles were counted in and out of as they were put on their tracks
auto const moved{apply_isolated(Document, left_axles(Document, left), summary)};
apply_drivers(Document, left, summary);
apply_owners(Document, left);
// the cells after the vehicles, whose sections write to their cells as they're taken and freed
apply_each(Document, "memcell", summary, apply_memcell);
apply_isolated_cells(moved);
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);
// 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()};
// 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: {}", error));
return false;
}
WriteLog(std::format("snapshot: the simulation at {:.2f} s saved to \"{}\", {} entries", Timer::GetTime(), File, document.records.size()));
return true;
}
std::string save_now()
{
auto const &time{Time.data()};
auto scenery{Global.SceneryFile};
if (auto const extension{scenery.rfind('.')}; extension != std::string::npos)
scenery.erase(extension);
std::ranges::replace_if(scenery, [](char const Character) { return Character == '/' || Character == '\\' || Character == ':'; }, '_');
// the folder eu07.ini names; the game folder may be one the game can't write to
auto const folder{Global.snapshot_dir.empty() ? std::string{"snapshots"} : Global.snapshot_dir};
std::error_code error;
std::filesystem::create_directories(folder, error);
// two saves in the same second of the simulation (while it's paused, say) don't write over each other
auto const file{free_file(std::format("{}/{}_{:04}-{:02}-{:02}_{:02}-{:02}-{:02}.snapshot", folder, scenery, time.wYear, time.wMonth, time.wDay, time.wHour,
time.wMinute, time.wSecond))};
auto const saved{save(file)};
ui::Transcripts.AddLine(saved ? std::format("Snapshot saved: {}", file) : std::format("Snapshot not saved, {} can't be written (see errors.txt)", file), 0.f, 10.f,
false);
return saved ? file : std::string{};
}
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);
}
// 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<std::uint32_t> requested_seed()
{
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;
}
std::string requested_player_vehicle()
{
auto const *pending{accepted_pending()};
if (pending == nullptr)
return {};
auto const players{pending->of("player")};
return players.empty() ? std::string{} : players.front()->name;
}
void start()
{
auto &schedule{requested()};
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));
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, schedule.requests.force);
}
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 &note : summary.notes)
ErrorLog(std::format("snapshot: {}", note));
for (auto const &remark : summary.remarks)
WriteLog(std::format("snapshot: {}", remark));
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, missing or of another scenery");
}
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
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}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses
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