18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-05 00:55:17 +01:00
Files
maszyna/physics/components/snapshot.cpp
T

1131 lines
48 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/.
*/
// the state of a running vehicle in a snapshot of the simulation (simulation/simulationsnapshot.h): what it carries, how it
// moves, what its machinery is set to and the air in its brakes. the list of what's kept is here; it's what a train needs
// to carry on as it was, not every variable of the physics. the keys and their order are those of the snapshots written
// before the state of the vehicle went private, so those still load
#include "stdafx.h"
#include "physics/vehicle.h"
#include "physics/brakes.h"
#include "simulation/simulationsnapshot.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <format>
#include <iterator>
#include <limits>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace snap = simulation::snapshot;
namespace
{
// keys of the parts a vehicle has two of, or a few: "pant0valve", "door1open"
std::string indexed(std::string_view const Part, int const Index, std::string_view const Key)
{
return std::format("{}{}{}", Part, Index, Key);
}
// the pressures a valve of the driver keeps, under the keys "<name>0", "<name>1"...
void capture_handle(snap::record &Entry, std::string_view const Name, TDriverHandle &Handle)
{
std::vector<double> values;
for (auto const *pressure : Handle.pressures())
values.emplace_back(*pressure);
Entry.set(Name, snap::numbers_text(values));
Entry.set(std::format("{}time", Name), (Handle.Time ? 1 : 0) | (Handle.TimeEP ? 2 : 0));
}
void apply_handle(snap::record const &Entry, std::string_view const Name, TDriverHandle &Handle)
{
auto const pressures{Handle.pressures()};
// the pressures of another kind of valve mean nothing to this one
if (auto const values{snap::text_numbers(Entry.text(Name))}; values.size() == pressures.size())
{
for (std::size_t index{0}; index < values.size(); ++index)
*pressures[index] = values[index];
}
if (auto time{0}; Entry.get(std::format("{}time", Name), time))
{
Handle.Time = (time & 1) != 0;
Handle.TimeEP = (time & 2) != 0;
}
}
// the three states of a device as one number: 1 allowed to run, 2 told to stop, 4 running
template <typename Device_> int device_state(Device_ const &Device)
{
return (Device.is_enabled ? 1 : 0) | (Device.is_disabled ? 2 : 0) | (Device.is_active ? 4 : 0);
}
template <typename Device_> void device_state(Device_ &Device, int const State)
{
Device.is_enabled = (State & 1) != 0;
Device.is_disabled = (State & 2) != 0;
Device.is_active = (State & 4) != 0;
}
template <typename Device_> void capture_device(snap::record &Entry, std::string_view const Key, Device_ const &Device)
{
Entry.set(Key, device_state(Device));
}
template <typename Device_> void apply_device(snap::record const &Entry, std::string_view const Key, Device_ &Device)
{
if (auto state{0}; Entry.get(Key, state))
device_state(Device, state);
}
// what a door is told to do, as one number: 1 permit, 2 local open, 4 local close, 8 remote open, 16 remote close
int door_inputs(physics::basic_door const &Door)
{
return (Door.open_permit ? 1 : 0) | (Door.local_open ? 2 : 0) | (Door.local_close ? 4 : 0) | (Door.remote_open ? 8 : 0) | (Door.remote_close ? 16 : 0);
}
// what a door does, as one number: 1 closed with its step, 2 the door itself closed, 4 closing, 8 opening, 16 open,
// 32 step folding, 64 step unfolding
int door_outputs(physics::basic_door const &Door)
{
return (Door.is_closed ? 1 : 0) | (Door.is_door_closed ? 2 : 0) | (Door.is_closing ? 4 : 0) | (Door.is_opening ? 8 : 0) | (Door.is_open ? 16 : 0) |
(Door.step_folding ? 32 : 0) | (Door.step_unfolding ? 64 : 0);
}
void apply_door(physics::basic_door &Door, snap::record const &Entry, int const Index)
{
if (auto inputs{0}; Entry.get(indexed("door", Index, "in"), inputs))
{
Door.open_permit = (inputs & 1) != 0;
Door.local_open = (inputs & 2) != 0;
Door.local_close = (inputs & 4) != 0;
Door.remote_open = (inputs & 8) != 0;
Door.remote_close = (inputs & 16) != 0;
}
if (auto outputs{0}; Entry.get(indexed("door", Index, "out"), outputs))
{
Door.is_closed = (outputs & 1) != 0;
Door.is_door_closed = (outputs & 2) != 0;
Door.is_closing = (outputs & 4) != 0;
Door.is_opening = (outputs & 8) != 0;
Door.is_open = (outputs & 16) != 0;
Door.step_folding = (outputs & 32) != 0;
Door.step_unfolding = (outputs & 64) != 0;
}
Entry.get(indexed("door", Index, "position"), Door.position);
Entry.get(indexed("door", Index, "step"), Door.step_position);
Entry.get(indexed("door", Index, "timer"), Door.auto_timer);
Entry.get(indexed("door", Index, "closedelay"), Door.close_delay);
Entry.get(indexed("door", Index, "opendelay"), Door.open_delay);
}
// the air of a reservoir: what it holds and, when there's any, the flow it has taken since it last acted. a flow
// added late in a step (the feed of the brake reservoir from the main pipe) waits there for the next one
void capture_reservoir(snap::record &Entry, std::string const &Key, TReservoir const &Reservoir)
{
Entry.set(Key, Reservoir.GetVol());
if (Reservoir.GetPendingFlow() != 0.0)
Entry.set(Key + "flow", Reservoir.GetPendingFlow());
}
bool apply_reservoir(TReservoir &Reservoir, snap::record const &Entry, std::string const &Key)
{
auto volume{0.0};
if (false == Entry.get(Key, volume))
return false;
Reservoir.SetVol(volume, Entry.value(Key + "flow", 0.0));
return true;
}
// the figures of an induction motor drive, which each step goes on from, in the order of the eimv table they were kept
// in before (eimv_FMAXMAX .. eimv_Fful), which is the order of the snapshot
template <typename State_> auto induction_motor_figures(State_ &State)
{
return std::array{&State.absoluteMaxForce, &State.maxForce, &State.slipShare, &State.slipFrequency, &State.supplyFrequency, &State.voltage,
&State.flux, &State.torqueCurrent, &State.fieldCurrent, &State.torque, &State.force, &State.lineCurrent,
&State.mechanicalPower, &State.electricalPower, &State.efficiency, &State.criticalFrequency, &State.linkVoltage,
&State.powerLimit, &State.forceDemand, &State.currentLimit, &State.fullForce};
}
} // namespace
struct physics::Vehicle::snapshot_members
{
// the state of the parts of the vehicle the snapshot keeps, as plain values: taken from the parts for a save and
// for a load, and put back into them once the load has set what the entry has
struct parts
{
LowVoltageSupply::Snapshot lowVoltage;
bool heating{false};
bool heatingAllow{false};
LineBreaker::Snapshot lineBreaker;
LineContactors::Snapshot lineContactors;
ProtectionRelays::Snapshot protection;
PowerConverter::Snapshot converter;
double pantographFrontVoltage{0.0};
double pantographRearVoltage{0.0};
double pantographSupplyVoltage{0.0};
bool pantographsAllDown{false};
PantographAir::Snapshot pantographAir;
AirCompressor::Snapshot compressor;
AirSupply::Snapshot air;
double brakePipePressure{0.0};
double mainPipePressure{0.0};
int handlePosition{0};
double handlePositionReal{0.0};
double handleCapPosition{0.0};
double handlePositionSmooth{0.0};
double independentPosition{0.0};
double independentPositionEim{0.0};
int handBrakePosition{0};
// the sets of flags, by their numbers
int damage{0};
int equipmentFaults{0};
};
static parts take(Vehicle const &V)
{
parts P;
P.lowVoltage = V.lowVoltage.TakeSnapshot();
P.heating = V.trainHeating.IsOn();
P.heatingAllow = V.trainHeating.IsAllowed();
P.lineBreaker = V.lineBreaker.TakeSnapshot();
P.lineContactors = V.lineContactors.TakeSnapshot();
P.protection = V.protection.TakeSnapshot();
P.converter = V.converter.TakeSnapshot();
P.pantographFrontVoltage = V.pantographCircuit.FrontVoltage();
P.pantographRearVoltage = V.pantographCircuit.RearVoltage();
P.pantographSupplyVoltage = V.pantographCircuit.SupplyVoltage();
P.pantographsAllDown = V.pantographCircuit.AllDown();
P.pantographAir = V.pantographAir.TakeSnapshot();
P.compressor = V.air.compressor.TakeSnapshot();
P.air = V.air.TakeSnapshot();
P.brakePipePressure = V.brakePipe.Pressure();
P.mainPipePressure = V.mainPipe.Pressure();
P.handlePosition = V.brakes.HandlePosition();
P.handlePositionReal = V.brakes.HandlePositionReal();
P.handleCapPosition = V.brakes.HandleCapPosition();
P.handlePositionSmooth = V.brakes.HandlePositionSmooth();
P.independentPosition = V.brakes.IndependentPosition();
P.independentPositionEim = V.brakes.IndependentPositionEim();
P.handBrakePosition = V.brakes.HandBrakePosition();
P.damage = V.DamageFlag.Bits();
P.equipmentFaults = V.equipmentFaults.Bits();
return P;
}
static void put(Vehicle &V, parts const &P)
{
V.lowVoltage.RestoreSnapshot(P.lowVoltage);
V.trainHeating.SetOn(P.heating);
V.trainHeating.Allow(P.heatingAllow);
V.lineBreaker.RestoreSnapshot(P.lineBreaker);
V.lineContactors.RestoreSnapshot(P.lineContactors);
V.protection.RestoreSnapshot(P.protection);
V.converter.RestoreSnapshot(P.converter);
V.pantographCircuit.SetFrontVoltage(P.pantographFrontVoltage);
V.pantographCircuit.SetRearVoltage(P.pantographRearVoltage);
V.pantographCircuit.SetSupplyVoltage(P.pantographSupplyVoltage);
V.pantographCircuit.SetAllDown(P.pantographsAllDown);
V.pantographAir.RestoreSnapshot(P.pantographAir);
V.air.compressor.RestoreSnapshot(P.compressor);
V.air.RestoreSnapshot(P.air);
V.brakePipe.SetPressure(P.brakePipePressure);
V.mainPipe.SetPressure(P.mainPipePressure);
V.brakes.SetHandlePosition(P.handlePosition);
V.brakes.SetHandlePositionReal(P.handlePositionReal);
V.brakes.SetHandleCapPosition(P.handleCapPosition);
V.brakes.SetHandlePositionSmooth(P.handlePositionSmooth);
V.brakes.SetIndependentPosition(P.independentPosition);
V.brakes.SetIndependentPositionEim(P.independentPositionEim);
V.brakes.SetHandBrakePosition(P.handBrakePosition);
// as the snapshot had them, without what setting them anew sets going (SetEquipmentFaults())
V.DamageFlag = DamageSet::FromBits(P.damage);
V.equipmentFaults = EquipmentFaultSet::FromBits(P.equipmentFaults);
}
// the plain values the snapshot keeps under a key each, by groups in the order of the entry. Vehicle_ and Parts_ are
// const for a save; Visit takes the key and the variable
// what the vehicle does: its movement, as the physics left it at the end of the step
template <typename Vehicle_, typename Parts_, typename Visit_> static void motion(Vehicle_ &V, Parts_ &, Visit_ const &Visit)
{
Visit("v", V.travelSpeed);
Visit("vel", V.Vel);
Visit("acc", V.accS);
Visit("accv", V.accSVBased);
Visit("nrot", V.nrotValue);
Visit("distance", V.distCounter);
Visit("movelen", V.moveLength);
}
// forces, moments and powers a step reads before it works them out anew, as it left them
template <typename Vehicle_, typename Parts_, typename Visit_> static void forces(Vehicle_ &V, Parts_ &, Visit_ const &Visit)
{
Visit("enginepower", V.EnginePower);
Visit("ft", V.ft);
Visit("fw", V.Fw);
Visit("mm", V.motorMoment);
Visit("mw", V.Mw);
Visit("fb", V.brakingForce);
Visit("ff", V.Ff);
Visit("ftrain", V.FTrain);
Visit("fstand", V.FStand);
Visit("ftotal", V.FTotal);
Visit("unitbrakeforce", V.brakes.unitForce);
Visit("ntotal", V.Ntotal);
Visit("totalcurrent", V.TotalCurrent);
Visit("dl", V.dL);
Visit("nroteps", V.nrot_eps);
Visit("accn", V.accN);
Visit("accvert", V.accVert);
Visit("dizeltorque", V.diesel.torque);
Visit("dizelpower", V.diesel.power);
Visit("dizeldeltaomega", V.diesel.clutchSlip);
Visit("dizelnold", V.diesel.previousRevolutions);
Visit("dizelnregmin", V.diesel.governorMinRevolutions);
Visit("dizelnregmax", V.diesel.governorMaxRevolutions);
Visit("hydrotorquein", V.torqueConverter.torqueIn);
Visit("hydrotorqueout", V.torqueConverter.torqueOut);
Visit("hydrotmratio", V.torqueConverter.torqueRatio);
Visit("hydrorequest", V.torqueConverter.request);
Visit("retarderfill", V.retarder.fill);
Visit("retardertorque", V.retarder.torque);
Visit("retarderrequest", V.retarder.request);
Visit("retardern", V.retarder.revolutions);
Visit("eimvpr", V.inductionMotor.forceShare);
Visit("eimicstep", V.eimic_step_progress);
Visit("eimicspeedctrl", V.eimicSpeedCtrlValue);
Visit("eimicspeedctrlintegral", V.eimicSpeedCtrlIntegral);
Visit("newspeed", V.newSpeed);
Visit("speedctrltimer", V.SpeedCtrlTimer);
Visit("vadd", V.Vadd);
Visit("medepvctime", V.brakes.blending.epCorrectionTimer);
Visit("mededdelay", V.brakes.blending.edDelayTimer);
// how long power has been asked for, which lets the holding brake of a unit go after its delay
Visit("stopbrakereleasetimer", V.brakes.holding.releaseTimer);
}
// positions of the controllers
template <typename Vehicle_, typename Parts_, typename Visit_> static void positions(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("mainctrl", V.mainCtrlPos);
Visit("scndctrl", V.scndCtrlPos);
Visit("mainctrlactual", V.MainCtrlActualPos);
Visit("scndctrlactual", V.ScndCtrlActualPos);
Visit("diractive", V.DirActive);
Visit("dirabsolute", V.DirAbsolute);
Visit("cabactive", V.CabActive);
Visit("caboccupied", V.cabOccupied);
Visit("lightspos", V.lightsPos);
Visit("compressorlistpos", P.compressor.listPosition);
Visit("wiperswitchpos", V.wiperSwitchPos);
Visit("pulseforcecount", V.PulseForceCount);
Visit("loadstatus", V.loadStatus);
Visit("brakectrl", P.handlePosition);
Visit("manualbrake", P.handBrakePosition);
Visit("brakedelay", V.brakes.delaySetting);
Visit("brakeopmode", V.brakes.operatingMode);
Visit("doubletr", V.DoubleTr);
Visit("damage", P.damage);
Visit("enginedamage", P.equipmentFaults);
Visit("warningsignal", V.warningSignal);
Visit("dimmer", V.modernDimmerPosition);
Visit("tuhexstage", V.TUHEX_StageActual);
}
// continuous settings, timers of the devices and the state of the engine
template <typename Vehicle_, typename Parts_, typename Visit_> static void levels(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("brakectrlr", P.handlePositionReal);
Visit("brakectrl2", P.handleCapPosition);
Visit("brakectrlf", P.handlePositionSmooth);
Visit("localbrake", P.independentPosition);
Visit("localbrakeeim", P.independentPositionEim);
Visit("dynamicbrakectrl", V.brakes.electrodynamic.controllerPosition);
Visit("eimic", V.eimic);
Visit("eimicanalog", V.eimicAnalog);
Visit("eimicreal", V.eimicReal);
Visit("eimlocalbrake", V.eim_localbrake);
Visit("anpos", V.anPos);
Visit("speedctrl", V.SpeedCtrlValue);
Visit("mainsinit", P.lineBreaker.initCountdown);
Visit("converterdelay", P.converter.startDelayTimer);
Visit("compressorpowertime", P.compressor.powerTime);
Visit("wheelflat", V.wheelFlat);
Visit("brakeslippingtimer", V.brakes.antiSlipTimer);
Visit("pulseforce", V.PulseForce);
Visit("pulseforcetimer", V.PulseForceTimer);
Visit("lastloadchangetime", V.LastLoadChangeTime);
Visit("brvtimer", V.brakes.electrodynamic.resistorFansTimer);
Visit("epforce", V.EpForce);
Visit("lastrelaytime", P.lineContactors.lastSwitchTime);
Visit("lastswitchingtime", V.LastSwitchingTime);
Visit("batteryvoltage", P.lowVoltage.batteryVoltage);
Visit("power24vvoltage", P.lowVoltage.power24vVoltage);
Visit("enginevoltage", V.EngineVoltage);
Visit("enrot", V.enrot);
Visit("im", V.Im);
Visit("itot", V.Itot);
Visit("rventrot", V.RventRot);
Visit("sand", V.Sand);
Visit("dizelfill", V.diesel.fill);
Visit("dizelengage", V.diesel.clutchPressure);
Visit("dizelengagestate", V.diesel.clutchState);
Visit("dizelgear", V.diesel.automaticGearShift);
Visit("dizelfiring", V.diesel.firingCountdown);
Visit("hydrofill", V.torqueConverter.fill);
Visit("hydronin", V.torqueConverter.revolutionsIn);
Visit("hydronout", V.torqueConverter.revolutionsOut);
Visit("hydrolockuprate", V.torqueConverter.lockupRate);
Visit("eangle", V.eAngleValue);
Visit("fuelrate", V.diesel.fuelConsumptionActual);
Visit("fuelused", V.diesel.fuelConsumedTotal);
}
// switches, levers and what they've set going
template <typename Vehicle_, typename Parts_, typename Visit_> static void switches(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("battery", P.lowVoltage.batteryOn);
Visit("mains", P.lineBreaker.closed);
Visit("converterallow", P.converter.allow);
Visit("converterallowlocal", P.converter.allowLocal);
Visit("converter", P.converter.running);
Visit("compressorallow", P.compressor.allow);
Visit("compressorallowlocal", P.compressor.allowLocal);
Visit("compressor", P.compressor.running);
Visit("compressorlock", P.compressor.governorLock);
Visit("pantcompressor", P.pantographAir.compressorRunning);
Visit("heatingallow", P.heatingAllow);
Visit("heating", P.heating);
Visit("cabmaster", V.cabMaster);
Visit("alarmchain", V.brakes.alarmChain);
Visit("radiostop", V.radioStopFlag);
Visit("radio", V.radio);
Visit("radiofuse", V.radioFuse);
Visit("signalling", V.signalling);
Visit("emergencyvalveopen", V.brakes.emergencyValve.open);
Visit("lockpipe", V.brakes.pipeLock.locked);
Visit("unlockpipe", V.brakes.pipeLock.unlockPressed);
Visit("departuresignal", V.departureSignalOn);
Visit("sanddoseauto", V.SandDoseAuto);
Visit("sanddoseautoallow", V.SandDoseAutoAllow);
Visit("inspectorcutout", V.brakes.cutOutByInspector);
Visit("physicactivation", V.physicActivation);
Visit("epfuse", V.epFuse);
Visit("shuntmode", V.ShuntMode);
Visit("pantkurek3", P.pantographAir.connectedToMainReservoir);
Visit("pantswitch", P.pantographAir.pressureSwitchActive);
Visit("pantlock", P.pantographAir.pressureLockActive);
Visit("pantalldown", P.pantographsAllDown);
Visit("sanddose", V.sandDose);
Visit("sanddosemanual", V.SandDoseManual);
Visit("dynamicbrake", V.brakes.electrodynamic.on);
Visit("stlinswitchoff", P.lineContactors.forcedOpen);
Visit("power110v", P.lowVoltage.power110vAvailable);
Visit("power24v", P.lowVoltage.power24vAvailable);
// prepared for being hauled dead: the scenery sets it, a switch of the physics can change it
Visit("pulleemode", V.pulleeMode);
}
// relays and contactors
template <typename Vehicle_, typename Parts_, typename Visit_> static void relays(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("fuse", V.FuseFlag);
Visit("convovld", P.converter.overloaded);
Visit("groundrelay", P.protection.ground);
Visit("stlin", P.lineContactors.closed);
Visit("resistors", V.ResistorsFlag);
Visit("novoltrelay", P.protection.noVoltage);
Visit("overvoltrelay", P.protection.overvoltage);
Visit("pressureswitch", P.protection.pressureSwitch);
Visit("delayctrl", V.delayCtrlFlag);
Visit("autorelay", V.autoRelayFlag);
Visit("slipping", V.slippingWheels);
Visit("dizelstartup", V.diesel.startupRequested);
Visit("dizelignition", V.diesel.ignitionRequested);
Visit("dizelspinup", V.diesel.spinningUp);
Visit("hydrolockup", V.torqueConverter.lockedUp);
Visit("retarderclutch", V.retarder.clutchActive);
Visit("dynamicbrakeemu", V.brakes.electrodynamic.emuWorking);
Visit("tuhexreschange", V.TUHEX_ResChange);
Visit("tuhexactive", V.TUHEX_Active);
}
// the air: pressures and volumes the physics keeps itself. the reservoirs of the brake valve come apart from these
template <typename Vehicle_, typename Parts_, typename Visit_> static void air(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("pipe", P.brakePipePressure);
Visit("pipeeqvt", V.brakes.equivalentPipePressure);
Visit("cntrlpipe", V.brakes.controlReservoirPressure);
Visit("scndpipe", P.mainPipePressure);
Visit("brakepress", V.brakes.cylinderPressure);
Visit("locbrakepress", V.brakes.independentCylinderPressure);
Visit("pipebrakepress", V.brakes.pipeCylinderPressure);
Visit("volume", V.brakes.reservoirAir);
Visit("compressedvolume", P.air.compressedVolume);
Visit("compressorpress", P.air.mainReservoirPressure);
Visit("limpipe", V.brakes.pipeLimiterPressure);
Visit("actflowspeed", V.actFlowSpeed);
Visit("pantvolume", P.pantographAir.volume);
Visit("pantpress", P.pantographAir.pressure);
}
// the positions a controller or a switch of the vehicle can take. they index tables of the vehicle (the resistors of
// the start by the master controller, the settings of the compressor, the lights, the wipers), so a position of the
// file past them is brought within them: a file edited by hand, or a vehicle definition with fewer positions since
static std::pair<int, int> position_range(Vehicle const &V, std::string_view const Key)
{
if (Key == "mainctrl")
return {0, std::clamp(V.MainCtrlPosNo, 0, ResArraySize)};
if (Key == "mainctrlactual")
return {0, std::clamp(std::max(V.MainCtrlPosNo, V.RlistSize), 0, ResArraySize - 1)};
if (Key == "scndctrl" || Key == "scndctrlactual")
return {0, std::max(V.scndCtrlPosNo, 0)};
if (Key == "diractive" || Key == "dirabsolute" || Key == "cabactive" || Key == "caboccupied")
return {-1, 1};
if (Key == "lightspos")
return {0, std::clamp(V.LightsPosNo, 0, static_cast<int>(std::size(V.Lights[0])))};
if (Key == "compressorlistpos")
return {0, std::clamp(V.air.compressor.config.listPositions, 0, static_cast<int>(std::size(V.air.compressor.config.list[0])) - 1)};
if (Key == "wiperswitchpos")
return {0, static_cast<int>(std::size(V.WiperList)) - 1};
if (Key == "brakectrl")
return {-2, std::max(V.brakes.config.handlePositions, 0)};
if (Key == "manualbrake")
return {0, ManualBrakePosNo};
if (Key == "dimmer")
return {0, std::max(static_cast<int>(V.dimPositions.size()) - 1, 0)};
return {std::numeric_limits<int>::min(), std::numeric_limits<int>::max()};
}
// the electric circuits of the vehicle, and what it gives and takes through its power couplings: each step starts
// from what the one before left there
static void capture_power(snap::record &Entry, Vehicle const &V)
{
std::vector<double> circuits;
for (auto const &[voltage, current] : V.PowerCircuits)
{
circuits.emplace_back(voltage);
circuits.emplace_back(current);
}
Entry.set("circuits", snap::numbers_text(circuits));
for (auto side{0}; side < 2; ++side)
{
auto const &joint{V.Couplers[side]};
std::vector<double> values;
for (auto const *power : {&joint.power_high, &joint.power_110v, &joint.power_24v})
{
values.emplace_back(power->current);
values.emplace_back(power->voltage);
values.emplace_back(power->is_local ? 1.0 : 0.0);
values.emplace_back(power->is_live ? 1.0 : 0.0);
}
Entry.set(indexed("couplerpower", side, ""), snap::numbers_text(values));
}
Entry.set("security", snap::numbers_text(V.SecuritySystem.state()));
// the figures of an induction motor drive, which each step goes on from
std::vector<double> drive;
for (auto const *figure : induction_motor_figures(V.inductionMotor.state))
drive.emplace_back(*figure);
Entry.set("eimv", snap::numbers_text(drive));
// the speed control: 1 active, 2 starting, 4 set by hand, 8 braking in, 16 braking, 32 releasing, 64 standby, 128 parking
auto const &speedctrl{V.SpeedCtrlUnit};
Entry.set("speedctrlstate", (speedctrl.IsActive ? 1 : 0) | (speedctrl.Start ? 2 : 0) | (speedctrl.ManualStateOverride ? 4 : 0) |
(speedctrl.BrakeIntervention ? 8 : 0) | (speedctrl.BrakeInterventionBraking ? 16 : 0) |
(speedctrl.BrakeInterventionUnbraking ? 32 : 0) | (speedctrl.Standby ? 64 : 0) | (speedctrl.Parking ? 128 : 0));
Entry.set("speedctrlvelocity", speedctrl.DesiredVelocity).set("speedctrlpower", speedctrl.DesiredPower);
}
static void apply_power(Vehicle &V, snap::record const &Entry)
{
if (auto const circuits{snap::text_numbers(Entry.text("circuits"))}; circuits.size() == 2 * V.PowerCircuits.size())
{
for (std::size_t index{0}; index < V.PowerCircuits.size(); ++index)
V.PowerCircuits[index] = {circuits[2 * index], circuits[2 * index + 1]};
}
for (auto side{0}; side < 2; ++side)
{
auto &joint{V.Couplers[side]};
auto const values{snap::text_numbers(Entry.text(indexed("couplerpower", side, "")))};
if (values.size() != 12)
continue;
std::size_t index{0};
for (auto *power : {&joint.power_high, &joint.power_110v, &joint.power_24v})
{
power->current = values[index];
power->voltage = values[index + 1];
power->is_local = values[index + 2] != 0.0;
power->is_live = values[index + 3] != 0.0;
index += 4;
}
}
if (Entry.has("security"))
{
// the last one is the cab it watches
if (auto const state{snap::text_numbers(Entry.text("security"))}; false == state.empty() && snap::whole_number(state.back(), -1, 1).has_value())
V.SecuritySystem.state(state);
else
Entry.refuse("security", "its cab isn't -1, 0 or 1");
}
if (auto const drive{snap::text_numbers(Entry.text("eimv"))}; drive.size() == induction_motor_figures(V.inductionMotor.state).size())
{
auto const figures{induction_motor_figures(V.inductionMotor.state)};
for (std::size_t index{0}; index < figures.size(); ++index)
*figures[index] = drive[index];
}
auto &speedctrl{V.SpeedCtrlUnit};
if (auto state{0}; Entry.get("speedctrlstate", state))
{
speedctrl.IsActive = (state & 1) != 0;
speedctrl.Start = (state & 2) != 0;
speedctrl.ManualStateOverride = (state & 4) != 0;
speedctrl.BrakeIntervention = (state & 8) != 0;
speedctrl.BrakeInterventionBraking = (state & 16) != 0;
speedctrl.BrakeInterventionUnbraking = (state & 32) != 0;
speedctrl.Standby = (state & 64) != 0;
speedctrl.Parking = (state & 128) != 0;
}
Entry.get("speedctrlvelocity", speedctrl.DesiredVelocity);
Entry.get("speedctrlpower", speedctrl.DesiredPower);
}
static void capture_devices(snap::record &Entry, Vehicle const &V, parts const &P)
{
capture_device(Entry, "pantsvalve", V.pantographAir.valve);
for (auto index{0}; index < static_cast<int>(V.pantographs.size()); ++index)
{
auto const &pantograph{V.pantographs[index]};
capture_device(Entry, indexed("pant", index, "valve"), pantograph.valve);
Entry.set(indexed("pant", index, "up"), pantograph.is_active);
Entry.set(indexed("pant", index, "voltage"), pantograph.voltage);
}
Entry.set("pantfrontvolt", P.pantographFrontVoltage);
Entry.set("pantrearvolt", P.pantographRearVoltage);
Entry.set("pantvoltage", P.pantographSupplyVoltage);
capture_device(Entry, "fuelpump", V.FuelPump);
capture_device(Entry, "oilpump", V.OilPump);
Entry.set("oilpressure", V.OilPump.pressure);
capture_device(Entry, "waterpump", V.WaterPump);
Entry.set("waterpumpbreaker", V.WaterPump.breaker);
Entry.set("waterheater", (V.WaterHeater.is_enabled ? 1 : 0) | (V.WaterHeater.is_active ? 4 : 0));
Entry.set("waterheaterbreaker", V.WaterHeater.breaker);
for (auto index{0}; index < static_cast<int>(V.MotorBlowers.size()); ++index)
{
capture_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]);
Entry.set(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions);
}
capture_device(Entry, "compartmentlights", V.CompartmentLights);
Entry.set("lights0", V.litLights[VehicleEnd::front]);
Entry.set("lights1", V.litLights[VehicleEnd::rear]);
}
static void apply_devices(Vehicle &V, parts &P, snap::record const &Entry)
{
apply_device(Entry, "pantsvalve", V.pantographAir.valve);
for (auto index{0}; index < static_cast<int>(V.pantographs.size()); ++index)
{
auto &pantograph{V.pantographs[index]};
apply_device(Entry, indexed("pant", index, "valve"), pantograph.valve);
Entry.get(indexed("pant", index, "up"), pantograph.is_active);
Entry.get(indexed("pant", index, "voltage"), pantograph.voltage);
}
Entry.get("pantfrontvolt", P.pantographFrontVoltage);
Entry.get("pantrearvolt", P.pantographRearVoltage);
Entry.get("pantvoltage", P.pantographSupplyVoltage);
apply_device(Entry, "fuelpump", V.FuelPump);
apply_device(Entry, "oilpump", V.OilPump);
Entry.get("oilpressure", V.OilPump.pressure);
apply_device(Entry, "waterpump", V.WaterPump);
Entry.get("waterpumpbreaker", V.WaterPump.breaker);
if (auto state{0}; Entry.get("waterheater", state))
{
V.WaterHeater.is_enabled = (state & 1) != 0;
V.WaterHeater.is_active = (state & 4) != 0;
}
Entry.get("waterheaterbreaker", V.WaterHeater.breaker);
for (auto index{0}; index < static_cast<int>(V.MotorBlowers.size()); ++index)
{
apply_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]);
Entry.get(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions);
}
apply_device(Entry, "compartmentlights", V.CompartmentLights);
Entry.get("lights0", V.litLights[VehicleEnd::front]);
Entry.get("lights1", V.litLights[VehicleEnd::rear]);
}
static void capture_doors(snap::record &Entry, Vehicle const &V)
{
Entry.set("doorlock", V.Doors.lock_enabled);
Entry.set("doorlocked", V.Doors.is_locked);
Entry.set("doorstep", V.Doors.step_enabled);
Entry.set("doorremoteonly", V.Doors.remote_only);
Entry.set("doorpreset", V.Doors.permit_preset);
for (auto index{0}; index < static_cast<int>(V.Doors.instances.size()); ++index)
{
auto const &door{V.Doors.instances[index]};
Entry.set(indexed("door", index, "in"), door_inputs(door));
Entry.set(indexed("door", index, "out"), door_outputs(door));
Entry.set(indexed("door", index, "position"), door.position);
Entry.set(indexed("door", index, "step"), door.step_position);
Entry.set(indexed("door", index, "timer"), door.auto_timer);
Entry.set(indexed("door", index, "closedelay"), door.close_delay);
Entry.set(indexed("door", index, "opendelay"), door.open_delay);
}
}
static void apply_doors(Vehicle &V, snap::record const &Entry)
{
Entry.get("doorlock", V.Doors.lock_enabled);
Entry.get("doorlocked", V.Doors.is_locked);
Entry.get("doorstep", V.Doors.step_enabled);
Entry.get("doorremoteonly", V.Doors.remote_only);
Entry.get("doorpreset", V.Doors.permit_preset);
for (auto index{0}; index < static_cast<int>(V.Doors.instances.size()); ++index)
apply_door(V.Doors.instances[index], Entry, index);
}
// the temperatures of a combustion engine and what its cooling is doing
static void capture_heat(snap::record &Entry, Vehicle const &V)
{
auto const &heat{V.diesel.heat};
Entry.set("heatts", heat.Ts).set("heatto", heat.To).set("heattsr", heat.Tsr).set("heattwy", heat.Twy).set("heattsr2", heat.Tsr2).set("heattwy2", heat.Twy2);
Entry.set("heatt1", heat.temperatura1).set("heatt2", heat.temperatura2).set("heatrpmw", heat.rpmw).set("heatrpmw2", heat.rpmw2);
Entry.set("heatshutters1", heat.zaluzje1).set("heatshutters2", heat.zaluzje2).set("heatfault", heat.PA);
Entry.set("heatrpmwz", heat.rpmwz).set("heatrpmwz2", heat.rpmwz2).set("heatenginehot", heat.engine_is_hot);
// what each circuit of the cooling tells of its fluid: 1 too cold, 2 too hot, 4 past the cooling point, 8 flowing
auto index{0};
for (auto const *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine})
{
Entry.set(indexed("heatcircuit", index++, ""),
(circuit->is_cold ? 1 : 0) | (circuit->is_warm ? 2 : 0) | (circuit->is_hot ? 4 : 0) | (circuit->is_flowing ? 8 : 0));
}
}
static void apply_heat(Vehicle &V, snap::record const &Entry)
{
auto &heat{V.diesel.heat};
Entry.get("heatts", heat.Ts);
Entry.get("heatto", heat.To);
Entry.get("heattsr", heat.Tsr);
Entry.get("heattwy", heat.Twy);
Entry.get("heattsr2", heat.Tsr2);
Entry.get("heattwy2", heat.Twy2);
Entry.get("heatt1", heat.temperatura1);
Entry.get("heatt2", heat.temperatura2);
Entry.get("heatrpmw", heat.rpmw);
Entry.get("heatrpmw2", heat.rpmw2);
Entry.get("heatshutters1", heat.zaluzje1);
Entry.get("heatshutters2", heat.zaluzje2);
Entry.get("heatfault", heat.PA);
Entry.get("heatrpmwz", heat.rpmwz);
Entry.get("heatrpmwz2", heat.rpmwz2);
Entry.get("heatenginehot", heat.engine_is_hot);
auto index{0};
for (auto *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine})
{
if (auto state{0}; Entry.get(indexed("heatcircuit", index++, ""), state))
{
circuit->is_cold = (state & 1) != 0;
circuit->is_warm = (state & 2) != 0;
circuit->is_hot = (state & 4) != 0;
circuit->is_flowing = (state & 8) != 0;
}
}
}
// the air of the brake: the pipes of the vehicle, the reservoirs of its valve, the valve of the driver, the spring brake
static void capture_brake(snap::record &Entry, Vehicle const &V)
{
if (V.brakePipe.reservoir != nullptr)
capture_reservoir(Entry, "pipeair", *V.brakePipe.reservoir);
if (V.mainPipe.reservoir != nullptr)
capture_reservoir(Entry, "scndpipeair", *V.mainPipe.reservoir);
// the brake set for an empty, a part loaded or a loaded vehicle
Entry.set("brakeload", V.brakes.loadSetting);
if (auto const *valve{V.brakes.distributor.get()}; valve != nullptr)
{
Entry.set("brakestatus", valve->GetBrakeStatus());
Entry.set("releaser", valve->Releaser());
// the latches of its inner valves, the step of its rapid relay
Entry.set("brakelatches", snap::numbers_text(valve->latches()));
auto index{0};
for (auto const *reservoir : valve->reservoirs())
{
if (reservoir != nullptr)
capture_reservoir(Entry, indexed("res", index, ""), *reservoir);
else
Entry.set(indexed("res", index, ""), 0.0);
++index;
}
}
if (V.brakes.driverValve != nullptr)
capture_handle(Entry, "handle", *V.brakes.driverValve);
if (V.brakes.independentValve != nullptr)
capture_handle(Entry, "lochandle", *V.brakes.independentValve);
auto const &spring{V.brakes.spring};
Entry.set("springbrake", spring.activate);
Entry.set("springbrakeshutoff", spring.shutOff);
Entry.set("springbrakerelease", spring.release);
Entry.set("springbrakeactive", spring.isActive);
Entry.set("springbrakeready", spring.isReady);
Entry.set("springbrakepress", spring.pressure);
if (spring.cylinder != nullptr)
capture_reservoir(Entry, "springbrakevolume", *spring.cylinder);
}
static void apply_brake_valve(TBrake &Valve, Vehicle const &V, snap::record const &Entry)
{
auto const reservoirs{Valve.reservoirs()};
// the air of each reservoir, when the entry has it for the reservoirs this kind of valve has; otherwise the valve
// is set as the scenery sets it at the start, to the pressures of the pipe and of the cylinders
if (auto const complete{false == reservoirs.empty() && Entry.has(indexed("res", static_cast<int>(reservoirs.size()) - 1, "")) &&
false == Entry.has(indexed("res", static_cast<int>(reservoirs.size()), ""))};
false == complete)
{
if (Entry.has("pipe"))
Valve.Init(V.brakePipe.Pressure(), V.brakes.config.pipeHighPressure, V.brakes.config.pipeLowPressure, V.brakes.cylinderPressure, V.brakes.delaySetting);
}
else
{
auto index{0};
for (auto *reservoir : reservoirs)
{
if (reservoir != nullptr)
apply_reservoir(*reservoir, Entry, indexed("res", index, ""));
++index;
}
}
if (Entry.has("brakedelay"))
Valve.SetBDF(V.brakes.delaySetting);
if (auto status{0}; Entry.get("brakestatus", status))
Valve.SetBrakeStatus(status);
// of the same kind of valve only: another kind has other latches
if (auto const latches{snap::text_numbers(Entry.text("brakelatches"))}; latches.size() == Valve.latches().size())
Valve.latches(latches);
if (auto releaser{false}; Entry.get("releaser", releaser) && releaser != Valve.Releaser())
Valve.Releaser(releaser ? 1 : 0);
}
static void apply_brake(Vehicle &V, snap::record const &Entry)
{
// the pipes of the vehicle hold the pressures the physics reads them from: by their air, or, for an entry which
// only gives the pressures, filled to those
if (V.brakePipe.reservoir != nullptr && false == apply_reservoir(*V.brakePipe.reservoir, Entry, "pipeair") && Entry.has("pipe"))
{
V.brakePipe.reservoir->CreatePress(V.brakePipe.Pressure());
V.brakePipe.reservoir->Act();
}
if (V.mainPipe.reservoir != nullptr && false == apply_reservoir(*V.mainPipe.reservoir, Entry, "scndpipeair") && Entry.has("scndpipe"))
{
V.mainPipe.reservoir->CreatePress(V.mainPipe.Pressure());
V.mainPipe.reservoir->Act();
}
if (auto setting{V.brakes.loadSetting}; Entry.get("brakeload", setting, 0, 3))
{
// by the steps of the lever, which change the ratio of the rigging with it
auto moved{true};
while (moved && V.brakes.loadSetting != setting)
moved = V.brakes.loadSetting < setting ? V.IncBrakeMult() : V.DecBrakeMult();
}
if (V.brakes.distributor != nullptr)
apply_brake_valve(*V.brakes.distributor, V, Entry);
if (V.brakes.driverValve != nullptr)
apply_handle(Entry, "handle", *V.brakes.driverValve);
if (V.brakes.independentValve != nullptr)
apply_handle(Entry, "lochandle", *V.brakes.independentValve);
auto &spring{V.brakes.spring};
Entry.get("springbrake", spring.activate);
Entry.get("springbrakeshutoff", spring.shutOff);
Entry.get("springbrakerelease", spring.release);
Entry.get("springbrakeactive", spring.isActive);
Entry.get("springbrakeready", spring.isReady);
Entry.get("springbrakepress", spring.pressure);
if (spring.cylinder != nullptr)
apply_reservoir(*spring.cylinder, Entry, "springbrakevolume");
}
// the load changes the mass, and with it what the brakes are set for
static void apply_load(Vehicle &V, snap::record const &Entry)
{
auto amount{V.loadAmount};
auto name{V.LoadType.name};
// the share of the load shown is worked out from it: what can be read as a load, up to a thousand times what the
// vehicle is rated for
auto const most{1000.f * std::max(V.maxLoad, 1.f)};
auto const given{Entry.get("load", amount, 0.f, most)};
if (Entry.has("load") && false == given)
return;
// the name of the load is that of its model, looked up in the folder of the vehicle
if (auto const *text{Entry.find("loadtype")};
text != nullptr && (text->find_first_of("/\\:") != std::string::npos || text->find("..") != std::string::npos))
{
Entry.refuse("loadtype", "a load is named by a name, not by a path");
return;
}
if (false == Entry.get("loadtype", name) && false == given)
return;
if (amount == V.loadAmount && name == V.LoadType.name)
return;
if (name == V.LoadType.name)
{
// more or less of what it carries
V.loadAmount = amount;
V.ComputeMass();
return;
}
// the vehicle is emptied first: it doesn't take a load of another kind on top of the one it has
V.AssignLoad("");
if (false == name.empty())
{
V.AssignLoad(name, amount);
// a load the vehicle isn't made for, as the scenery can give it one all the same, or one with nothing left of it
if (V.LoadType.name != name)
V.LoadType.name = name;
// AssignLoad() keeps the amount within what the vehicle is rated for, a vehicle loaded over that keeps what it had
V.loadAmount = amount;
}
V.ComputeMass();
}
// the track under the vehicle as the last step was given it. the next step works its constants out from this one
// (the resistance of a curve in ComputeConstans()) before it's given the track anew
static void capture_running(snap::record &Entry, Vehicle const &V)
{
auto const &shape{V.RunningShape};
Entry.set("runningshape", snap::numbers_text(std::array{shape.R, shape.Len, shape.dHtrack, shape.dHrail, shape.uneven_curvature, shape.uneven_cross,
shape.buckle_curvature}));
auto const &track{V.RunningTrack};
Entry.set("runningtrack", snap::numbers_text(std::array{track.Width, track.friction, static_cast<double>(track.CategoryFlag),
static_cast<double>(track.QualityFlag), static_cast<double>(track.DamageFlag),
std::isfinite(track.Velmax) ? track.Velmax : 0.0}));
auto const &traction{V.RunningTraction};
Entry.set("runningtraction",
snap::numbers_text(std::array{traction.TractionVoltage, traction.TractionFreq, traction.TractionMaxCurrent, traction.TractionResistivity}));
// where the physics has the vehicle: at the place it started the last step from, a frame behind its body. the gaps
// between the couplers are measured between these
auto const &location{V.location};
if (std::isfinite(location.X) && std::isfinite(location.Y) && std::isfinite(location.Z))
Entry.set("loc", snap::numbers_text(std::array{location.X, location.Y, location.Z}));
}
static void apply_running(Vehicle &V, snap::record const &Entry)
{
if (auto const numbers{snap::text_numbers(Entry.text("runningshape"))}; numbers.size() == 7)
{
auto &shape{V.RunningShape};
shape.R = numbers[0];
shape.Len = numbers[1];
shape.dHtrack = numbers[2];
shape.dHrail = numbers[3];
shape.uneven_curvature = numbers[4];
shape.uneven_cross = numbers[5];
shape.buckle_curvature = numbers[6];
}
if (auto const numbers{snap::text_numbers(Entry.text("runningtrack"))}; numbers.size() == 6)
{
constexpr auto lowest{std::numeric_limits<int>::min()};
constexpr auto highest{std::numeric_limits<int>::max()};
auto const category{snap::whole_number(numbers[2], lowest, highest)};
auto const quality{snap::whole_number(numbers[3], lowest, highest)};
auto const damage{snap::whole_number(numbers[4], lowest, highest)};
if (category.has_value() && quality.has_value() && damage.has_value())
{
auto &track{V.RunningTrack};
track.Width = numbers[0];
track.friction = numbers[1];
track.CategoryFlag = *category;
track.QualityFlag = *quality;
track.DamageFlag = *damage;
track.Velmax = numbers[5];
}
else
Entry.refuse("runningtrack", "its flags aren't whole numbers");
}
if (auto const numbers{snap::text_numbers(Entry.text("loc"))}; numbers.size() == 3)
V.location = {numbers[0], numbers[1], numbers[2]};
if (auto const numbers{snap::text_numbers(Entry.text("runningtraction"))}; numbers.size() == 4)
{
auto &traction{V.RunningTraction};
traction.TractionVoltage = numbers[0];
traction.TractionFreq = numbers[1];
traction.TractionMaxCurrent = numbers[2];
traction.TractionResistivity = numbers[3];
}
}
// how the vehicle left the rails, by any model of the derailment, written for a vehicle that did; and for every vehicle
// the distance its criteria of derailment were last checked over. an entry without them, written before they were
// kept, leaves the vehicle on the rails as the scenery put it
static void capture_derailment(snap::record &Entry, Vehicle const &V)
{
Entry.set("derailmentdistance", V.derailmentDistance);
if (V.derailOutcome == derailment::outcome::none && V.derailedBy == derailment::reason::none && V.collisionDerail == NONE)
return;
Entry.set("derailed", static_cast<int>(V.derailOutcome));
Entry.set("derailedby", static_cast<int>(V.derailedBy));
Entry.set("derailvelocity", V.derailVelocity);
Entry.set("derailcause", static_cast<int>(V.derailCause));
Entry.set("derailacceleration", V.derailAcceleration);
Entry.set("derailside", V.derailSide);
Entry.set("collisionderail", static_cast<int>(V.collisionDerail));
}
static void apply_derailment(Vehicle &V, snap::record const &Entry)
{
Entry.get("derailmentdistance", V.derailmentDistance);
if (auto outcome{0}; Entry.get("derailed", outcome, 0, static_cast<int>(derailment::outcome::overturned)))
V.derailOutcome = static_cast<derailment::outcome>(outcome);
if (auto reason{0}; Entry.get("derailedby", reason, 0, static_cast<int>(derailment::reason::flank_collision)))
V.derailedBy = static_cast<derailment::reason>(reason);
Entry.get("derailvelocity", V.derailVelocity);
if (auto cause{0}; Entry.get("derailcause", cause, 0, static_cast<int>(derail_motion::cause::collision)))
V.derailCause = static_cast<derail_motion::cause>(cause);
Entry.get("derailacceleration", V.derailAcceleration);
Entry.get("derailside", V.derailSide, -1, 1);
if (auto reason{0}; Entry.get("collisionderail", reason, 0, static_cast<int>(COLLISION_PUSHED_OFF)))
V.collisionDerail = static_cast<DerailReason>(reason);
}
// what the brake force came from when the physics fell asleep (physics.sleepheld): a change of it wakes the vehicle
static void capture_asleep(snap::record &Entry, Vehicle const &V)
{
auto const &brakes{V.sleep_brakes};
Entry.set("sleepbrakes", snap::numbers_text(std::array{brakes.cylinder, brakes.spring, static_cast<double>(brakes.manual), brakes.local}));
}
static void apply_asleep(Vehicle &V, snap::record const &Entry)
{
auto const numbers{snap::text_numbers(Entry.text("sleepbrakes"))};
if (numbers.size() != 4)
return;
auto const manual{snap::whole_number(numbers[2], 0, ManualBrakePosNo)};
if (false == manual.has_value())
{
Entry.refuse("sleepbrakes", "its hand brake position isn't one the vehicle has");
return;
}
auto &brakes{V.sleep_brakes};
brakes.cylinder = numbers[0];
brakes.spring = numbers[1];
brakes.manual = *manual;
brakes.local = numbers[3];
}
// what each coupler keeps from the step before: its force and the deflection of the buffers, how long it has been
// overstretched, the collision it's in, and the springs of the physical model of the pair, which give by where they were
static void capture_couplers(snap::record &Entry, Vehicle const &V)
{
for (auto side{0}; side < 2; ++side)
{
auto const &joint{V.Couplers[side]};
auto const &pair{joint.physics_state};
Entry.set(indexed("couplerstate", side, ""),
snap::numbers_text(std::array{joint.CForce, joint.Dist, static_cast<double>(joint.stretch_duration), joint.CheckCollision ? 1.0 : 0.0,
joint.crush, joint.closing, joint.hit_handled ? 1.0 : 0.0, joint.hit_force, joint.hit_duration,
pair.draw_gear.force, pair.draw_gear.deflection, pair.buffers.force, pair.buffers.deflection,
pair.elongation, pair.gap, static_cast<double>(pair.stop), pair.stop_force}));
}
}
static void apply_couplers(Vehicle &V, snap::record const &Entry)
{
for (auto side{0}; side < 2; ++side)
{
auto const values{snap::text_numbers(Entry.text(indexed("couplerstate", side, "")))};
if (values.size() != 17)
continue;
auto const stop{snap::whole_number(values[15], std::numeric_limits<int>::min(), std::numeric_limits<int>::max())};
if (false == stop.has_value())
{
Entry.refuse(indexed("couplerstate", side, ""), "the stop of the pair isn't a whole number");
continue;
}
auto &joint{V.Couplers[side]};
auto &pair{joint.physics_state};
joint.CForce = values[0];
joint.Dist = values[1];
joint.stretch_duration = static_cast<float>(values[2]);
joint.CheckCollision = values[3] != 0.0;
joint.crush = values[4];
joint.closing = values[5];
joint.hit_handled = values[6] != 0.0;
joint.hit_force = values[7];
joint.hit_duration = values[8];
pair.draw_gear.force = values[9];
pair.draw_gear.deflection = values[10];
pair.buffers.force = values[11];
pair.buffers.deflection = values[12];
pair.elongation = values[13];
pair.gap = values[14];
pair.stop = *stop;
pair.stop_force = values[16];
}
}
};
void physics::Vehicle::SnapshotSave(simulation::snapshot::record &Entry) const
{
using members = snapshot_members;
auto const parts{members::take(*this)};
auto const save{[&Entry](std::string_view const Key, auto const &Value) { Entry.set(Key, Value); }};
Entry.set("load", loadAmount);
Entry.set("loadtype", LoadType.name);
members::motion(*this, parts, save);
members::forces(*this, parts, save);
members::positions(*this, parts, save);
members::levels(*this, parts, save);
members::switches(*this, parts, save);
members::relays(*this, parts, save);
members::capture_devices(Entry, *this, parts);
members::capture_doors(Entry, *this);
members::capture_heat(Entry, *this);
members::air(*this, parts, save);
members::capture_brake(Entry, *this);
members::capture_power(Entry, *this);
members::capture_running(Entry, *this);
members::capture_couplers(Entry, *this);
members::capture_derailment(Entry, *this);
members::capture_asleep(Entry, *this);
}
void physics::Vehicle::SnapshotLoad(simulation::snapshot::record const &Entry)
{
using members = snapshot_members;
members::apply_load(*this, Entry);
// the parts as they are; what the entry has goes over it, and they get it back before the brake, which reads the pipes
auto parts{members::take(*this)};
auto const load{[&Entry](std::string_view const Key, auto &Value) { Entry.get(Key, Value); }};
members::motion(*this, parts, load);
members::forces(*this, parts, load);
members::positions(*this, parts, [this, &Entry](std::string_view const Key, int &Value) {
auto const [lowest, highest]{members::position_range(*this, Key)};
Entry.get_clamped(Key, Value, lowest, highest);
});
members::levels(*this, parts, load);
members::switches(*this, parts, load);
members::relays(*this, parts, load);
members::apply_devices(*this, parts, Entry);
members::apply_doors(*this, Entry);
members::apply_heat(*this, Entry);
members::air(*this, parts, load);
members::put(*this, parts);
members::apply_brake(*this, Entry);
members::apply_power(*this, Entry);
members::apply_running(*this, Entry);
members::apply_couplers(*this, Entry);
members::apply_derailment(*this, Entry);
members::apply_asleep(*this, Entry);
}