diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 2f1781ed8..d37817d5c 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -45,6 +45,15 @@ jobs: python-version: "3.14" architecture: "x64" + # the cab screens are drawn with Pillow; CMake copies this Python's Lib, site-packages included, next to the + # executable as python64\Lib, so Pillow has to be installed here to come with the build (as on Linux) + - name: Install Pillow for the screens + shell: pwsh + run: | + $pythonExe = "${{ steps.python.outputs.python-path }}" + & $pythonExe -m pip install --no-cache-dir Pillow + & $pythonExe -c "from PIL import Image; print('Pillow:', Image.__version__)" + - name: Show environment shell: pwsh run: | @@ -114,6 +123,18 @@ jobs: -Recurse ` -Force + # the Python 3 version of the module every cab screen builds on; the game data still has the Python 2 one + New-Item ` + -ItemType Directory ` + -Force ` + -Path "$output/python/local" | Out-Null + + Copy-Item ` + -Path "staticFiles/python/local/*" ` + -Destination "$output/python/local" ` + -Recurse ` + -Force + - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: @@ -251,9 +272,11 @@ jobs: - name: Copy shaders and translations run: | - mkdir -p build/bin/shaders build/bin/lang + mkdir -p build/bin/shaders build/bin/lang build/bin/python/local cp -R shaders/. build/bin/shaders/ cp -R lang/. build/bin/lang/ + # the Python 3 version of the module every cab screen builds on; the game data still has the Python 2 one + cp -R staticFiles/python/local/. build/bin/python/local/ - name: Upload Linux build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/CLAUDE.md b/CLAUDE.md index c1709be8d..283058cbe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,11 +27,16 @@ Where no GCC is at hand, read the new code for what MSVC lets through and GCC do The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of `wchar_t`, or on `long` being 32 bits. -## SonarCloud: every remark on the changed code gets fixed +## SonarCloud: the PR passes the quality gate -SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR counts as finished only when every remark Sonar raises on -the code it changes is fixed. That means the code smells too, not just the bugs, the vulnerabilities and the quality gate. The analysis -runs on the GCC build, so a PR that fails to build with GCC gets no analysis at all. +SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new +code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed. +Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false +positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a +large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to +rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a +remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that +fails to build with GCC gets no analysis at all, and so it doesn't pass the gate. Fixing a remark must not change what the code does: @@ -41,7 +46,7 @@ Fixing a remark must not change what the code does: - `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the reason. -Write new code so that it doesn't raise the rules that keep coming up: +To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up: - **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25): - use early `continue` / `return`; diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f34ad61f..7137ab39a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -160,6 +160,7 @@ set(SOURCES "world/station.cpp" "application/application.cpp" "simulation/simulationtime.cpp" +"simulation/simulationtest.cpp" "scene/sceneeditor.cpp" "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" @@ -453,7 +454,7 @@ endif() add_library(eu07_settings INTERFACE) # the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle -# definition parser and the helpers they use. built once, and tested as the game uses them +# definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them set(CORE_SOURCES "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" @@ -462,8 +463,11 @@ set(CORE_SOURCES "utilities/parser.cpp" "utilities/utilities.cpp" "scripting/ladderlogic.cpp" +"simulation/simulationtestrules.cpp" +"vehicle/enginestart.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" +"vehicle/linebreaker.cpp" "vehicle/smoke.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) @@ -738,4 +742,4 @@ if(WITH_TESTS) # Visual Studio builds rerun them with the next change of the game) set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY LINK_DEPENDS $ ${UNIT_TEST_DATA} "${CMAKE_CURRENT_SOURCE_DIR}/tests/unit/run_tests.cmake") -endif() \ No newline at end of file +endif() diff --git a/EU07.cpp b/EU07.cpp index e03618297..20f24aa5a 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -19,8 +19,14 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "stdafx.h" #include "application/application.h" +#include "simulation/simulationtest.h" +#include "utilities/Globals.h" #include "utilities/Logs.h" #include +#include +#include +#include +#include #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -70,7 +76,9 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); - MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR); + // in test mode nobody is there to close the box, and the run would wait for it until killed + if (false == Global.test.enabled) + MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR); MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dumpType, &dumpInfo, nullptr, nullptr); CloseHandle(hFile); @@ -81,6 +89,55 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) #endif +namespace +{ + +// the log is written by a thread of its own, which the closing of the application stops and waits for. on the ways +// out that skip the closing (a failed start, an exception) what was logged last would be lost with the process +void finish_log() +{ + StopLogService(); + if (auto const logservice{Global.threads.find("LogService")}; + logservice != Global.threads.end() && logservice->second.joinable() && logservice->second.get_id() != std::this_thread::get_id()) + logservice->second.join(); +} + +// ends a test run with its verdict on the standard output and in the exit code. a test the simulator didn't end +// (a failed start, an exception) ends with the error and Reason +[[noreturn]] void end_test_run(std::string_view const Reason) +{ + simulation::test().conclude(simulation::test_result::error, Reason); + finish_log(); + fflush(stdout); + fflush(stderr); + // skip destructors, there are ordering errors which causes segfaults + std::_Exit(simulation::test().exit_code()); +} + +// a test run (--test): whatever stops it, it ends with its verdict. any other run never gets here and ends as +// it always has +[[noreturn]] void run_test(int argc, char *argv[]) +{ + // for what doesn't reach the catch below: an exception leaving a noexcept function, or on Linux one leaving + // a thread (on Windows the handler is the main thread's only) + std::set_terminate([] { end_test_run(simulation::describe_exception(std::current_exception())); }); + try + { + if (Application.init(argc, argv) == 0) + { + Application.run(); + Application.exit(); + } + } + catch (...) + { + end_test_run(simulation::describe_exception(std::current_exception())); + } + end_test_run("the simulator stopped before the test ended"); +} + +} // namespace + int main(int argc, char *argv[]) { #ifdef WITHDUMPGEN @@ -130,6 +187,11 @@ int main(int argc, char *argv[]) fflush(stderr); std::_Exit(result); } + // unattended test run of a scenery, which says its result in the exit code (eu07/maszyna#541) + else if (simulation::parse_test_command_line(std::vector(argv, argv + argc)).enabled) + { + run_test(argc, argv); + } else { try diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 21c9ba7e4..9502de95a 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -10,7 +10,9 @@ http://mozilla.org/MPL/2.0/. #pragma once //--------------------------------------------------------------------------- // Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji +#include #include +#include #include "hamulce.h" #include "scripting/ladderlogic.h" @@ -261,6 +263,22 @@ enum class range_t /// Affects the entire consist. consist }; +/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most +/// severe: the state of a consist is the most severe state of its vehicles. +enum class door_closure_t +{ + /// No doors worked by the crew: the vehicle doesn't take part in the signalling. + none, + /// All doors closed and locked: they can't be opened. + locked, + /// All doors closed, but released: a permit is given, or no lock holds them shut. + released, + /// A door is open, or not fully closed yet. + open +}; +/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the +/// blinking for released ones, never with a door open or with no doors signalled. +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit); /// Possible settings for an enable/disable input pair (mutually exclusive). enum class operation_t { @@ -324,6 +342,21 @@ enum light highbeamlight_right = 1 << 10 }; +/// The cab interior light a position of the light preset selector sets (eu07/maszyna#529). +struct lights_preset_cablight +{ + /// Bits of the optional third column of a LightsList row. + enum flag + { + /// The cab light is on. + light_on = 1 << 0, + /// The cab light is dimmed. + light_dimmed = 1 << 1 + }; + bool light{false}; + bool dim{false}; +}; + /// Door operation method (who controls them and how) — mutually exclusive. enum control_t { @@ -1131,6 +1164,7 @@ class TSecuritySystem bool is_sifa = false; // Sifa-like pedal device, with inverted input for convenient keyboard usage bool separate_acknowledge = false; // cabsignal reset button is separate from vigilance bool cabsignal_lock = false; + bool vigilance_suspended = false; // the vigilance device switched off by the shunt mode of the vehicle, see AwareOffInShuntMode double vigilance_timer = 0.0; double alert_timer = 0.0; @@ -1146,6 +1180,7 @@ class TSecuritySystem double EmergencyBrakeDelay = 5.0; double MaxHoldTime = 1.5; bool CabDependent = false; + bool AwareOffInShuntMode = false; // the shunt mode of the vehicle switches the vigilance device off, as on the SM42 public: void set_enabled(bool e); @@ -1155,6 +1190,7 @@ class TSecuritySystem void update(double dt, double Vel, bool pwr, int cab); void set_cabsignal(); void set_cabsignal_lock(bool); + void set_shunt_mode(bool State); bool is_blinking() const; bool is_vigilance_blinking() const; bool is_cabsignal_blinking() const; @@ -1439,6 +1475,7 @@ class TMoverParameters float auto_velocity{-1.f}; // automatic door closure velocity threshold bool auto_include_remote{false}; // automatic door closure applies also to remote control bool permit_needed{false}; + bool closure_signal{false}; // the door closure lamp (SOD) of the cab signals the doors of the whole consist in three states std::vector permit_presets; // permit presets selectable with preset switch float voltage{0.f}; // power type required for door movement // ld inputs @@ -1590,6 +1627,9 @@ class TMoverParameters double EpForce = 0.0; /*Poziom zadanej sily EP*/ bool Signalling = false; /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ bool Radio = false; /*Czy jest zalaczony radiotelefon*/ + // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power + // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before + bool RadioFuse = true; float NominalBatteryVoltage = 0.f; /*Winger - baterie w elektrykach*/ TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ @@ -1703,6 +1743,13 @@ class TMoverParameters int LightsDefPos = 1; bool LightsWrap = false; int Lights[2][18]; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) + // the cab interior light each light preset sets, from the optional third column of LightsList (bits of + // lights_preset_cablight::flag); -1: the preset leaves the cab light as it is (eu07/maszyna#529) + std::array LightsCabLight{[] { + std::array positions; + positions.fill(-1); + return positions; + }()}; int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ bool MBrake = false; /*Czy jest hamulec reczny*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego @@ -1727,6 +1774,10 @@ class TMoverParameters bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/ bool UniCtrlIntegratedLocalBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force + // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the + // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown + // covers a step; 0 (the default) changes it continuously + double UniCtrlValStep{0.0}; std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab /*-sekcja parametrow dla lokomotywy elektrycznej*/ @@ -1943,6 +1994,7 @@ class TMoverParameters double MirrorVelClose{5.0}; bool MirrorForbidden{false}; /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/ bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/ + bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) bool SpeedCtrl = false; /*czy jest tempomat*/ speed_control SpeedCtrlUnit; /*parametry tempomatu*/ double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ @@ -2093,6 +2145,9 @@ class TMoverParameters double MainsInitTime{0.0}; // config, initialization time (in seconds) of the main circuit after it receives power, before it can be closed double MainsInitTimeCountdown{0.0}; // current state of main circuit initialization, remaining time (in seconds) until it's ready start_t MainsStart{start_t::manual}; + // config, Engine:JointEngineStart. whether the cab's line breaker / engine start switch works the vehicles in multiple + // too; when it doesn't, the cab has separate switches for them (mainb_*, mainc_*) + bool JointEngineStart{true}; bool LineBreakerClosesOnlyAtNoPowerPos{false}; bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels bool HasControlPressureSwitch{true}; @@ -2171,6 +2226,10 @@ class TMoverParameters bool dizel_startup{false}; // engine startup procedure request indicator bool dizel_ignition{false}; // engine ignition request indicator bool dizel_spinup{false}; // engine spin up to idle speed flag + // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the vehicle's + // .fiz, seconds from the start of the spin up) has passed. 0, the default, lets it out as soon as the starter turns, as before eu07/maszyna#523 + double dizel_SmokeDelay{0.0}; + double dizel_FiringCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own double dizel_engagedeltaomega = 0.0; /*roznica predkosci katowych tarcz sprzegla*/ double dizel_n_old = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/ double dizel_Torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/ @@ -2199,6 +2258,7 @@ class TMoverParameters double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ double eimic_analog = 0; /*pozycja zadajnika analogowa*/ double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ + double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ bool SpeedCtrlTypeTime = false; /*czy tempomat sterowany czasowo*/ @@ -2287,6 +2347,14 @@ class TMoverParameters // bool modernContainOffPos{true}; bool enableModernDimmer{false}; bool modernDimmerCanCycle{false}; + // the given dimmer position brought into the DimmerList, to its first or last entry; 0 for an empty list + int clampDimmerPosition(int Position) const; + // the entry of the current dimmer position, or a plain one (not off, not dimmed, no high beam) when the + // position is outside the DimmerList: the .fiz can give a short or an empty list, or a DefaultPos past its end + dimPosition currentDimPosition() const; + // moves the dimmer by Step positions within the DimmerList, around to its other end when it can cycle; + // a position outside the list is brought into it first. false when the dimmer doesn't move + bool stepDimmerPosition(int Step); // Barwa reflektora int refR{255}; // Czerwony @@ -2301,6 +2369,9 @@ class TMoverParameters plc::basic_controller m_plc; int AIHintPantstate{0}; // suggested pantograph setup + // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front, + // 2 rear, 3 both; 0 (the default) shunts with the pantographs handled as in train mode + int AIHintShuntPantstate{0}; bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation @@ -2382,6 +2453,11 @@ class TMoverParameters bool IncScndCtrl(int CtrlSpeed); bool DecScndCtrl(int CtrlSpeed); int GetVirtualScndPos() const; + // whether ScndCtrlResistiveLock keeps the shunt controller from being moved at the current master controller position + bool IsScndCtrlLockedByMainCtrl() const; + // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it + // can't stay engaged there, locked in place (eu07/maszyna#402) + void ScndCtrlResistiveLockCheck(); bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2423,6 +2499,8 @@ class TMoverParameters bool BrakeReleaser(int state); bool UniversalBrakeButton(int button, int state); /*uniwersalny przycisk hamulca*/ bool SwitchEPBrake(int state); + // whether the EP brake control of the cab has power: battery, the reverser out of neutral and the EP fuse on + bool EPBrakeControlPowered() const; bool AntiSlippingButton(void); /*! reczny wlacznik urzadzen antyposlizgowych*/ /*funkcje dla ukladow pneumatycznych*/ @@ -2463,6 +2541,14 @@ class TMoverParameters // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) bool AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other + // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system + // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check + // off allows it always (eu07/maszyna#520) + bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling + // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole + int CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const; // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound int SoundingHorns(int const Signal) const; // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: @@ -2471,11 +2557,30 @@ class TMoverParameters { return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); } - // whether the lamp of the open line contactors is lit, telling the start can be made + // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so + // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the + // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) bool LineContactorsLampLit() const { + if (EngineType == TEngineType::DieselElectric) + { + return false == StLinFlag; + } return false == StLinFlag && MainCircuitLampsEnabled(); } + // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own + // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) + range_t MainSwitchRange() const + { + return JointEngineStart ? range_t::consist : range_t::local; + } + // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button + // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump + // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command + bool MainCircuitOpensWithStarterOnly() const + { + return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric; + } // whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on bool OilFuelPumpsEnabled() const { @@ -2483,10 +2588,10 @@ class TMoverParameters auto const oilmanual{OilPump.start_type != start_t::automatic}; return (fuelmanual || oilmanual) && (false == fuelmanual || FuelPump.is_enabled) && (false == oilmanual || OilPump.is_enabled); } - // whether the radio is switched on and has the low voltage to work + // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work bool RadioPowered() const { - return Radio && (Power24vIsAvailable || Power110vIsAvailable); + return Radio && RadioFuse && (Power24vIsAvailable || Power110vIsAvailable); } /*obrot kol uwzgledniajacy poslizg*/ double ComputeRotatingWheel(double WForce, double dt, double n) const; @@ -2590,6 +2695,10 @@ class TMoverParameters bool LockDoors(bool const State, range_t const Notify = range_t::consist); bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning void update_doors(double const Deltatime); // door controller update + door_closure_t door_closure() const; // state of the door closure signalling of this vehicle + // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the + // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked + bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; /* funkcje dla samochodow*/ bool ChangeOffsetH(double DeltaOffset); @@ -2599,6 +2708,8 @@ class TMoverParameters bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); std::string EngineDescription(int what) const; + // the cab interior light the light preset at given position (1-based, as LightsPos) sets, if it sets one + std::optional LightsPresetCabLight(int Position) const; private: bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index cd4573ca0..1ad97530e 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include "simulation/simulation.h" +#include #include #include //--------------------------------------------------------------------------- @@ -152,11 +153,23 @@ void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) velocity = vel; cabactive = cab; - if (vigilance_enabled && velocity > AwareMinSpeed) - vigilance_timer += dt; + if (vigilance_suspended) + { + // the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held + // too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual + if (vigilance_timer <= AwareDelay) + vigilance_timer = 0.0; + if (press_timer <= MaxHoldTime) + press_timer = 0.0; + } + else + { + if (vigilance_enabled && velocity > AwareMinSpeed) + vigilance_timer += dt; - if (pressed && (!is_sifa || velocity > AwareMinSpeed)) - press_timer += dt; + if (pressed && (!is_sifa || velocity > AwareMinSpeed)) + press_timer += dt; + } if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) alert_timer += dt; @@ -231,6 +244,11 @@ void TSecuritySystem::set_cabsignal_lock(bool v) cabsignal_lock = v; } +void TSecuritySystem::set_shunt_mode(bool const State) +{ + vigilance_suspended = State && AwareOffInShuntMode; +} + bool TSecuritySystem::is_engine_blocked() const { if (!is_sifa) @@ -260,6 +278,7 @@ void TSecuritySystem::load(std::string const &line, double Vmax) extract_value(radiostop_enabled, "RadioStop", line, ""); extract_value(MagnetLocation, "MagnetLocation", line, ""); extract_value(CabDependent, "CabDependent", line, ""); + extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, ""); } double TableInterpolation(std::map &Map, double Parameter) @@ -599,7 +618,8 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * } auto &thiscoupler{Couplers[ConnectNo]}; - auto &othercoupler = ConnectTo->Couplers[ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr]; + auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr}; + auto &othercoupler = ConnectTo->Couplers[otherend]; auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; @@ -608,6 +628,18 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * return false; } + // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI + // or the player (eu07/maszyna#520) + if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType) + { + WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); + CouplingType = compatible; + if (CouplingType == coupling::faux) + { + return false; + } + } + // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie if (thiscoupler.CouplingFlag == coupling::faux) { @@ -809,6 +841,19 @@ bool TMoverParameters::ChangeCab(int direction) // rozruch wysoki (true) albo niski (false) bool TMoverParameters::CurrentSwitch(bool const State) { + // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that + // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. + // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497) + if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + { + // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position + if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos()) + { + return false; + } + ShuntMode = State; + return true; + } if (MaxCurrentSwitch(State)) { @@ -818,20 +863,6 @@ bool TMoverParameters::CurrentSwitch(bool const State) } return true; } - // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that - // dla 2Ls150 - if (EngineType == TEngineType::DieselEngine && true == ShuntModeAllow && DirActive == 0) - { - // przed ustawieniem kierunku - ShuntMode = State; - return true; - } - // for SM42/SP42 - if (EngineType == TEngineType::DieselElectric && true == ShuntModeAllow && IsMainCtrlNoPowerPos()) - { - ShuntMode = State; - return true; - } return false; }; @@ -1206,6 +1237,59 @@ bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters con return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; } +namespace +{ + +// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes +enum class traction_kind +{ + none, + electric, + diesel +}; + +traction_kind traction_of(TEngineType const Engine) +{ + switch (Engine) + { + case TEngineType::ElectricSeriesMotor: + case TEngineType::ElectricInductionMotor: + return traction_kind::electric; + case TEngineType::DieselEngine: + case TEngineType::DieselElectric: + return traction_kind::diesel; + default: + return traction_kind::none; + } +} + +} // namespace + +bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const +{ + if (false == Global.control_coupling_engine_check) + { + return true; + } + // the same control system named on both couplers is the vehicle authors' word that they work together + if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type) + { + return true; + } + auto const traction{traction_of(EngineType)}; + auto const othertraction{traction_of(Other.EngineType)}; + return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; +} + +int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const +{ + if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd)) + { + return CouplingType; + } + return CouplingType & ~coupling::control; +} + int TMoverParameters::SoundingHorns(int const Signal) const { auto const supplied{[this](horn_supply const Supply) { @@ -1631,6 +1715,8 @@ void TMoverParameters::compute_movement_(double const Deltatime) BRVentilators = false; } + // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well + ScndCtrlResistiveLockCheck(); // automatyczny rozruch if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) { @@ -2537,6 +2623,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (true == OK) { + ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } @@ -2662,6 +2749,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) if (OK) { + ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } @@ -2772,7 +2860,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) { // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos 0 && CabActive != 0) { - if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag)) + if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) { if (CtrlSpeed == 1) { @@ -2893,6 +2981,22 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) return OK; } +bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const +{ + // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) + return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); +} + +void TMoverParameters::ScndCtrlResistiveLockCheck() +{ + // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the + // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on + if (ScndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) + { + ScndCtrlPos = 0; + } +} + int TMoverParameters::GetVirtualScndPos() const { if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos) @@ -3164,9 +3268,11 @@ void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP void TMoverParameters::SecuritySystemCheck(double dt) { bool isPower = Power24vIsAvailable || Power110vIsAvailable; + // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) + SecuritySystem.set_shunt_mode(ShuntMode); SecuritySystem.update(dt, Vel, isPower, CabActive); - if (!Battery || !Radio) + if (!Battery || !Radio || !RadioFuse) { // wyłączenie baterii deaktywuje sprzęt RadiostopSwitch(false); } @@ -4182,7 +4288,8 @@ bool TMoverParameters::SwitchEPBrake(int state) OK = false; if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) { - if (state > 0) + // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is + if (state > 0 && EPBrakeControlPowered()) EpForce = Handle->GetEP(); // TODO: przetlumaczyc else EpForce = 0; @@ -4194,6 +4301,11 @@ bool TMoverParameters::SwitchEPBrake(int state) return OK; } +bool TMoverParameters::EPBrakeControlPowered() const +{ + return Power24vIsAvailable && DirActive != 0 && EpFuse; +} + // ************************************************************************************************* // Q: 20160711 // zwiększenie ciśnienia hamowania @@ -4728,7 +4840,7 @@ void TMoverParameters::UpdatePipePressure(double dt) if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) { - if (Power24vIsAvailable && DirActive != 0 && EpFuse) // tu powinien byc jeszcze bezpiecznik EP i baterie - + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - // temp = (Handle as TFVel6).GetCP EpForce = Handle->GetEP(); else @@ -4747,6 +4859,11 @@ void TMoverParameters::UpdatePipePressure(double dt) // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach SendCtrlToNext("Brake", EpForce, CabActive); } + else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } Pipe->Act(); PipePress = Pipe->P(); @@ -5169,6 +5286,7 @@ void TMoverParameters::ComputeTotalForce(double dt) double TMoverParameters::BrakeForceR(double ratio, double velocity) const { double press = 0; + ratio = Hamulec->GetBrakeRatio(ratio); if (MBPM > 2) { press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass)); @@ -5184,8 +5302,8 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) const press = MaxBrakePress[3]; if (DynamicBrakeType == dbrake_automatic) ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); - if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1 && velocity < 40) - ratio = ratio / 2; + if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) + ratio *= Hamulec->GetRapidRatio(velocity); if (TrainType == dt_DMU && velocity < 30.0) { ratio -= 0.3; @@ -5476,6 +5594,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) { couplingtype &= ~coupling::control; } + couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype); // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)}; @@ -7312,6 +7431,60 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify return State != initialstate; } +namespace +{ +// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it +double next_uc_step(double const Value, double const Limit, double const Step) +{ + constexpr double epsilon{1e-6}; + if (Limit > Value) + { + return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit); + } + return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit); +} + +// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps. +// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each +// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go) +double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress) +{ + if (Moved) + { + Progress = 0.0; + } + double const delta{Ramped - Current}; + if (std::abs(delta) < 1e-9) + { + Progress = 0.0; + return Ramped; + } + double limit{0.0}; + if (delta > 0.0) + { + limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal; + } + else + { + limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal; + } + Progress = Moved ? Step : Progress + std::abs(delta); + double value{Current}; + bool reached{std::abs(value - limit) < 1e-9}; + while (!reached && Progress >= Step - 1e-9) + { + value = next_uc_step(value, limit, Step); + Progress -= Step; + reached = std::abs(value - limit) < 1e-9; + } + if (reached) + { + Progress = 0.0; + } + return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); +} +} // namespace + void TMoverParameters::CheckEIMIC(double dt) { double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; @@ -7442,11 +7615,14 @@ void TMoverParameters::CheckEIMIC(double dt) if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) { - eimic -= safe_clamp(-UniCtrlList[MainCtrlPos].SetCtrlVal + eimic, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedDown : sign(UniCtrlList[MainCtrlPos].SpeedDown) * 0.01); // odejmuj do X - eimic += safe_clamp(UniCtrlList[MainCtrlPos].SetCtrlVal - eimic, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedUp : sign(UniCtrlList[MainCtrlPos].SpeedUp) * 0.01); // dodawaj do X - eimic = safe_clamp(eimic, UniCtrlList[MainCtrlPos].MinCtrlVal, UniCtrlList[MainCtrlPos].MaxCtrlVal); + auto const &position{UniCtrlList[MainCtrlPos]}; + double ramped{eimic}; + ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X + ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X + ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); + eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; } if (MainCtrlActualPos == MainCtrlPos) LastRelayTime += dt; @@ -7871,6 +8047,9 @@ bool TMoverParameters::dizel_Update(double dt) WaterHeaterCheck(dt); OilPumpCheck(dt); FuelPumpCheck(dt); + // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over + dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0); + if (true == dizel_startup && true == dizel_StartupCheck()) { dizel_ignition = true; @@ -7885,6 +8064,7 @@ bool TMoverParameters::dizel_Update(double dt) LastSwitchingTime = 0; Mains = true; dizel_spinup = true; + dizel_FiringCountdown = dizel_SmokeDelay; enrot = std::max(enrot, 0.35 * ( // TODO: dac zaleznie od temperatury i baterii EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0)); @@ -7896,7 +8076,8 @@ bool TMoverParameters::dizel_Update(double dt) { // knock out the engine if the fuel pump isn't feeding it // TBD, TODO: grace period before the engine is starved for fuel and knocked out - MainSwitch(false); + // an engine started on its own stops on its own + MainSwitch(false, MainSwitchRange()); } bool DU{false}; @@ -8187,7 +8368,13 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) if (enrot <= 0 && false == dizel_spinup) { - MainSwitch(false); + // an engine stalling stops those started together with it, once. one already stopped, from its own switch or + // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame + // the engines started on their own or from the separate switches (eu07/maszyna#80) + if (true == Mains) + { + MainSwitch(false, MainSwitchRange()); + } enrot = 0; } @@ -8726,6 +8913,48 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify) return true; } +// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while +// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. +// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist +door_closure_t TMoverParameters::door_closure() const +{ + if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) + { + return door_closure_t::none; + } + if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; })) + { + return door_closure_t::open; + } + if (Doors.is_locked) + { + return door_closure_t::locked; + } + if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; })) + { + return door_closure_t::locked; + } + return door_closure_t::released; +} + +bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const +{ + return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; +} + +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) +{ + switch (State) + { + case door_closure_t::locked: + return true; + case door_closure_t::released: + return BlinkLit; + default: + return false; + } +} + // automatic door controller update void TMoverParameters::update_doors(double const Deltatime) { @@ -9475,6 +9704,52 @@ bool TMoverParameters::readDimmerList(std::string const &line) return true; } +int TMoverParameters::clampDimmerPosition(int const Position) const +{ + if (dimPositions.empty()) + { + return 0; + } + return std::clamp(Position, 0, static_cast(dimPositions.size()) - 1); +} + +TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const +{ + if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) + { + return {}; + } + return dimPositions[modernDimmerPosition]; +} + +bool TMoverParameters::stepDimmerPosition(int const Step) +{ + if (dimPositions.empty()) + { + return false; + } + auto const last{static_cast(dimPositions.size()) - 1}; + auto const current{clampDimmerPosition(modernDimmerPosition)}; + auto next{current + Step}; + if (next < 0 || next > last) + { + if (false == modernDimmerCanCycle) + { + next = current; + } + else + { + next = (next < 0 ? last : 0); + } + } + if (next == modernDimmerPosition) + { + return false; + } + modernDimmerPosition = next; + return true; +} + // parsowanie WWList bool TMoverParameters::readWWList(std::string const &line) { @@ -9520,10 +9795,38 @@ bool TMoverParameters::readLightsList(std::string const &Input) return false; } parser >> Lights[0][idx] >> Lights[1][idx]; + // optional third column: the cab interior light the preset sets (eu07/maszyna#529). anything but a whole number + // (some rows carry stray notes after the two columns) leaves the cab light to its own switch + LightsCabLight[idx] = -1; + if (true == parser.getTokens(1, false)) + { + std::string cablight; + parser >> cablight; + int flags{-1}; + auto const [end, error]{std::from_chars(cablight.data(), cablight.data() + cablight.size(), flags)}; + if (error == std::errc{} && end == cablight.data() + cablight.size() && flags >= 0) + { + LightsCabLight[idx] = flags; + } + } return true; } +std::optional TMoverParameters::LightsPresetCabLight(int const Position) const +{ + if (Position < 1 || Position > static_cast(LightsCabLight.size())) + { + return std::nullopt; + } + auto const flags{LightsCabLight[Position - 1]}; + if (flags < 0) + { + return std::nullopt; + } + return lights_preset_cablight{(flags & lights_preset_cablight::light_on) != 0, (flags & lights_preset_cablight::light_dimmed) != 0}; +} + bool TMoverParameters::readCompressorList(std::string const &Input) { @@ -10276,6 +10579,9 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b result = false; // ustawiamy domyslna pozycje dimmera + // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it + modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); + modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); if (!enableModernDimmer) { modernDimmerPosition = modernDimmerDefaultPosition; @@ -10603,6 +10909,8 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(Doors.auto_include_remote, "DoorAutoCloseRemote", line, ""); // operation permit extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); + // the door closure lamp (SOD) of the cab signals the doors of the whole consist + extract_value(Doors.closure_signal, "DoorClosureSignal", line, ""); { auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); for (auto const &permit : permitpresets) @@ -10935,6 +11243,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR + extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych extract_value(InitialCtrlDelay, "IniCDelay", line, ""); extract_value(CtrlDelay, "SCDelay", line, ""); @@ -11195,6 +11504,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) { EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); + extract_value(JointEngineStart, "JointEngineStart", Input, ""); if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) { @@ -11403,6 +11713,9 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // oil pump extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); + // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) + extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); + dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); // engine cooling factore extract_value(dizel_heat.kw, "HeatKW", Input, ""); extract_value(dizel_heat.kv, "HeatKV", Input, ""); @@ -11428,7 +11741,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // water heater extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf; + float pf{ 1235.f }; extract_value(pf, "NominalCoolingPower", Input, "1235"); dizel_heat.powerfactor = 1235 / pf; } @@ -11512,6 +11825,7 @@ void TMoverParameters::LoadFIZ_AI(std::string const &Input) { extract_value(AIHintPantstate, "Pantstate", Input, ""); + extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, ""); extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); } @@ -11553,6 +11867,8 @@ void TMoverParameters::LoadFIZ_UCList(std::string const &Input) extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); + extract_value(UniCtrlValStep, "CtrlValStep", Input, ""); + UniCtrlValStep = std::max(UniCtrlValStep, 0.0); } void TMoverParameters::LoadFIZ_DList(std::string const &Input) diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp index 17fa79ee7..0717eff5d 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/McZapkie/Oerlikon_ESt.cpp @@ -16,6 +16,11 @@ Copyright (C) 2007-2014 Maciej Cierniak #include "Oerlikon_ESt.h" #include "utilities/utilities.h" +// wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar] +static double const dPSprezyny = 0.21; +// najmniejszy stopien hamowania w cylindrze [bar] (tablica 3-9, proby 12 i 22: 0,25-0,30) +static double const pStopnia = 0.28; + double d2A( double const d ) { return d * d * 0.7854 / 1000.0; @@ -218,10 +223,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr CheckReleaser(dt); // luzowanie + double const cel{ CelBCP( CVP, VVP ) }; if ((BrakeStatus & b_hld) == b_off) dV = PF(0.0, BCP, Nozzles[dTO] * nastG + (1.0 - nastG) * Nozzles[dOO]) - * dt * (0.1 + 4.9 * std::min(0.2, BCP - ((CVP - 0.05 - VVP) * BVM + 0.1))); + * dt * (0.1 + 4.9 * std::min(0.2, BCP - (cel > 0.0 ? cel + 0.1 : 0.0))); // bez stopnia luzuje do zera else dV = 0.0; // BrakeCyl.Flow(-dV); @@ -229,7 +235,7 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP ) dV = PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) ) - * dt * (0.1 + 4.9 * std::min( 0.2, (CVP - 0.05 - VVP) * BVM - BCP ) ); + * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) ); else dV = 0; // BrakeCyl.Flow(-dV); @@ -313,7 +319,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c Miedzypoj->CreateCap(5.0); Miedzypoj->CreatePress(PP); - BVM = 1.0 / (HPP - 0.05 - LPP) * MaxBP; + BVM = 1.0 / (HPP - dPSprezyny - LPP) * MaxBP; BrakeDelayFlag = BDF; @@ -327,6 +333,17 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c RapidStaly = false; } +double TNESt3::GetRapidRatio(double const Vel) const +{ + // ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds + if( ( PrzekRapid == nullptr ) || RapidStaly ) { + return 1.0; + } + // a braking vehicle comes from above, so the step is still engaged down to the speed + // at which GetPF() drops it, not the one at which it engages + return ( Vel < 50.0 ? 1.0 / PrzekRapid->GetRapidMult() : 1.0 ); +} + double TNESt3::GetCRP() { return CntrlRes->P(); @@ -334,6 +351,24 @@ double TNESt3::GetCRP() // return Miedzypoj.P; } +double TNESt3::GetBrakeRatio( double const Ratio ) const // udzial cisnienia w cylindrze dla udzialu spadku w PG +{ + if( MaxBP <= 0.0 || BVM <= 0.0 ) { + return Ratio; + } + // pelny spadek sluzbowy w PG (HPP - LPP), odtworzony z przelozenia + double const spadek{ MaxBP / BVM + dPSprezyny }; + double const cel{ ( Ratio * spadek - dPSprezyny ) * BVM }; + return ( cel > 0.0 ? std::max( cel, pStopnia ) / MaxBP : 0.0 ); +} + +double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze +{ + double const cel{ ( CVP - dPSprezyny - VVP ) * BVM }; + // gdy zawor hamuje, nie daje mniej niz najmniejszy stopien + return ( cel > 0.0 ? std::max( cel, pStopnia ) : cel ); +} + void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad rozrzadczy { double const VVP{ ValveRes->P() }; @@ -344,14 +379,13 @@ void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad r Przys_blok = false; // sprawdzanie stanu - // if ((BrakeStatus and 1)=1)and(BCP>0.25)then - if (VVP + 0.01 + BCP / BVM < CVP - 0.05 && Przys_blok) + if (double const cel{ CelBCP( CVP, VVP ) }; BCP < cel - 0.01 * BVM && Przys_blok) BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.01 + (BCP - 0.1) / BVM > CVP - 0.05) + else if (BCP - 0.1 > cel + 0.01 * BVM) BrakeStatus &= ~( b_on | b_hld ); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) + else if (BCP > cel) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + else if (BCP - 0.1 < cel && BCP > 0.25) // zatrzymanie luzowania BrakeStatus |= b_hld; if( ( BrakeStatus & b_hld ) == 0 ) @@ -380,7 +414,7 @@ void TNESt3::CheckReleaser(double const dt) // odluzniacz // odluzniacz automatyczny if ((BrakeStatus & b_rls) == b_rls) { - CntrlRes->Flow(PF(CVP, 0, 0.02) * dt); + CntrlRes->Flow(PF(CVP, 0, 0.0049) * dt); // ZS 15 l z 5,0 do 0,4 bar w 23 s (proba odbioru nr 27) if (CVP < VVP + 0.3 || false == autom) BrakeStatus &= ~b_rls; } @@ -451,6 +485,18 @@ void TNESt3::SetLBP(double const P) LBP = P; } +void TNESt3::ScaleNozzlesForAL2() // dysze cylindra przy przekladniku AL2 +{ + if( PrzekCiagly == nullptr ) { + return; + } + // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9 + Nozzles[dON] *= 0.914; + Nozzles[dTN] *= 0.885; + Nozzles[dOO] *= 0.82; + Nozzles[dTO] *= 0.8; +} + void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie dysz (rozmiaru ZR) { static double const dNO1l = 1.250; @@ -549,7 +595,7 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie { // dON,dOO,dTN,dTO,dP,dS Nozzles[dON] = 3.7; Nozzles[dOO] = 2.50; - Nozzles[dTN] = 1.65; + Nozzles[dTN] = 1.62; Nozzles[dTO] = 1.39; Nozzles[dP] = 2.65; Nozzles[dPd] = 1.80; @@ -638,6 +684,8 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie Nozzles[dSd] = 1.1; Nozzles[dSm] = 0.9; + ScaleNozzlesForAL2(); + // przeliczanie z mm^2 na l/m for (auto &nozzle : Nozzles) { @@ -646,7 +694,8 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie for (int i = 1; i < 4; ++i) { Przekladniki[i]->BrakeRes = BrakeRes; - Przekladniki[i]->CreateCap(i); + // komora impulsowa przekladnika AL2 ma 1 l + Przekladniki[i]->CreateCap( ( Przekladniki[i] == PrzekCiagly ) ? 1.0 : i ); Przekladniki[i]->CreatePress(BrakeCyl->P()); if (i < 3) Przekladniki[i]->Next = Przekladniki[i + 1]; diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h index dca531568..eaae2c032 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/McZapkie/Oerlikon_ESt.h @@ -111,6 +111,7 @@ class TRapid : public TPrzekladnik { public: void SetRapidParams(double mult, double size); void SetRapidStatus(bool rs); + double GetRapidMult() const { return RapidMult; } void Update(double dt) override; using TPrzekladnik::TPrzekladnik; }; @@ -194,9 +195,13 @@ class TNESt3 : public TBrake { double GetPF( double const PP, double const dt, double const Vel ) override; // przeplyw miedzy komora wstepna i PG void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt double GetCRP() override; + double GetRapidRatio(double const Vel) const override; + double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze + double GetBrakeRatio(double const Ratio) const override; // udzial cisnienia w cylindrze dla udzialu spadku w PG void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy void CheckReleaser(double const dt); // odluzniacz double CVs(double const BP) const; // napelniacz sterujacego + void ScaleNozzlesForAL2(); // dysze cylindra przy przekladniku AL2 double BVs(double const BCP) const; // napelniacz pomocniczego void SetSize( int const size, std::string const ¶ms ); // ustawianie dysz (rozmiaru ZR), przekladniki void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index c0a7d2a0e..9411dc425 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -968,6 +968,28 @@ double TESt::BVs(double const BCP) const return 0; } +/// +/// Refills the auxiliary reservoir (ZP) from the valve pre-chamber through the +/// check valve of the slide valve, opened as far as says for the +/// given cylinder (or impulse-chamber) pressure, while the pre-chamber is more +/// than 0.05 bar above the reservoir. The flows wait for the caller's Act(). +/// +/// Brake cylinder (or impulse-chamber) pressure. +/// Time step [s]. +/// Volume taken into the auxiliary reservoir, 0.96 of it drawn from the brake pipe. +double TESt::FillBrakeRes(double const BCP, double const dt) const +{ + double const BVP{BrakeRes->P()}; + double const VVP{ValveRes->P()}; + double const temp{BVs(BCP)}; + double dv{0.0}; + if (VVP - 0.05 > BVP) + dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; + BrakeRes->Flow(dv); + ValveRes->Flow(-0.04 * dv); + return dv; +} + /// /// One-step Oerlikon ESt distributor advance: runs CheckState/CheckReleaser, /// integrates the ZS <-> PG, ZP <-> cylinder, ZP <-> pre-chamber and @@ -1021,15 +1043,7 @@ double TESt::GetPF(double const PP, double const dt, double const Vel) BrakeCyl->Flow(-dv); // przeplyw ZP <-> rozdzielacz - temp = BVs(BCP); - // if(BrakeStatus and b_hld)=b_off then - if (VVP - 0.05 > BVP) - dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; - else - dv = 0; - BrakeRes->Flow(dv); - dV1 = dV1 + dv * 0.96; - ValveRes->Flow(-0.04 * dv); + dV1 = dV1 + FillBrakeRes(BCP, dt) * 0.96; // przeplyw PG <-> rozdzielacz dv = PF(PP, VVP, 0.01) * dt; ValveRes->Flow(-dv); @@ -1191,6 +1205,10 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) ValveRes->Flow(-0.04 * dv); dV1 = dV1 - 0.96 * dv; + // przeplyw ZP <-> rozdzielacz: as in every ESt, the auxiliary reservoir also charges from the brake pipe, + // not from the main reservoir pipe alone, so a unit hauled with the brake hose alone charges and brakes + dV1 = dV1 + FillBrakeRes(BCP, dt) * 0.96; + // hamulec EP EPCalc(dt); diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 3074a2e7e..2fb433a85 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -421,6 +421,10 @@ class TBrake double GetVRP() const; // cisnienie komory wstepnej rozdzielacza /// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS. virtual double GetCRP(); // cisnienie zbiornika sterujacego + /// Share of the full cylinder pressure the distributor settles at for the given share + /// of the full service pipe drop. Used only to predict the brake force; the default is proportional. + /// Share of the full service brake pipe drop. + virtual double GetBrakeRatio(double const Ratio) const { return Ratio; } /// /// Sets the brake delay (G/P/R/M) selector if requested mode is supported. /// @@ -443,6 +447,11 @@ class TBrake /// Sets the rapid step ratio. Default no-op; overridden where supported. /// Rapid ratio. virtual void SetRM(double const RMR) { /* no effect for this device type */ } // ustalenie przelozenia rapida + /// Share of the full cylinder pressure the distributor delivers at the given speed + /// while the vehicle is slowing down through it, for a vehicle set to R. Used only to predict + /// the brake force; the default is the approximation BrakeForceR() has always used. + /// Vehicle velocity [km/h]. + virtual double GetRapidRatio(double const Vel) const { return Vel < 40.0 ? 0.5 : 1.0; } /// Sets the velocity threshold for the rapid step. /// Velocity threshold (same unit as Vel passed to GetPF). virtual void SetRV(double const RVR) @@ -611,6 +620,15 @@ class TESt : public TBrake /// Brake cylinder pressure. /// Dimensionless opening coefficient. double BVs(double BCP) const; // napelniacz pomocniczego + /// + /// Refills the auxiliary reservoir (ZP) from the valve pre-chamber through the + /// check valve of the slide valve, opened as far as says, while + /// the pre-chamber is above the reservoir. The flows wait for the caller's Act(). + /// + /// Brake cylinder (or impulse-chamber) pressure for . + /// Time step [s]. + /// Volume taken into the auxiliary reservoir, 0.96 of it drawn from the brake pipe. + double FillBrakeRes(double BCP, double dt) const; // napelnianie pomocniczego z rozdzielacza /// Vents the valve, brake and control reservoirs to zero. void ForceEmptiness() override; // wymuszenie bycia pustym diff --git a/README.md b/README.md index 47741a511..675026ccf 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms ## Windows -Install **Python 3.14 x64** from [python.org](https://www.python.org/downloads/windows/) and include the optional **Python native development** feature (headers and `.lib` for embedding). Pass `-DPython3_ROOT_DIR="C:\Path\To\Python314"` on the `cmake` line when you want the layout under that directory used for embedding and for copying `Lib` / `DLLs` next to the executable. +Install **Python 3.14 x64** from [python.org](https://www.python.org/downloads/windows/) and include the optional **Python native development** feature (headers and `.lib` for embedding). Pass `-DPython3_ROOT_DIR="C:\Path\To\Python314"` on the `cmake` line when you want the layout under that directory used for embedding and for copying `Lib` / `DLLs` next to the executable. The cab screens are drawn with [Pillow](https://pypi.org/project/pillow/): install it into that Python (`python -m pip install Pillow`) before building, so it is copied along with `Lib`. **AppVeyor CI** builds with the worker image’s preinstalled Python at `C:/Python314-x64` (see [`appveyor.yml`](./appveyor.yml): `-DPython3_ROOT_DIR=...`). diff --git a/application/application.cpp b/application/application.cpp index 9b7b82853..a398117c7 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -28,10 +28,13 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "vehicle/Train.h" #include "utilities/Timer.h" +#include "utilities/framepacer.h" #include "utilities/dictionary.h" #include "version_info.h" +#include "simulation/simulationtest.h" #include #include +#include #include "utilities/translation.h" #if WITH_DISCORD_RPC @@ -320,6 +323,9 @@ int eu07_application::init(int Argc, char *Argv[]) { int result{0}; + // a test run is known before anything is logged: whoever started it reads its result on the standard output, + // which the log isn't written to then (eu07/maszyna#541) + Global.test.enabled = simulation::parse_test_command_line(std::vector(Argv, Argv + Argc)).enabled; // start logging service std::thread sLoggingService(LogService); Global.threads.emplace("LogService", std::move(sLoggingService)); @@ -378,7 +384,7 @@ int eu07_application::init(int Argc, char *Argv[]) return result; } - if (crashreport_is_pending()) + if (crashreport_is_pending() && false == Global.test.enabled) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { @@ -428,8 +434,12 @@ int eu07_application::init(int Argc, char *Argv[]) #if WITH_DISCORD_RPC // Run DiscordRPC service - std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this); - Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC)); + // not for a test run: it would show the test scenery as the player's presence, and hold up the closing + if (false == Global.test.enabled) + { + std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this); + Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC)); + } #endif if (!init_network()) @@ -479,9 +489,14 @@ bool eu07_application::is_client() const int eu07_application::run() { auto frame{0}; + frame_pacer framepacer; + Timer::subsystem.mainloop_period.start(); // main application loop while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty()) { + // the time from one frame's start to the next, the wait for fpslimit included + Timer::subsystem.mainloop_period.stop(); + Timer::subsystem.mainloop_period.start(); Timer::subsystem.mainloop_total.start(); glfwPollEvents(); @@ -641,10 +656,11 @@ int eu07_application::run() if (m_network) m_network->update(); - auto const frametime{Timer::subsystem.mainloop_total.stop()}; - if (Global.minframetime.count() != 0.0f && (Global.minframetime - frametime).count() > 0.0f) + Timer::subsystem.mainloop_total.stop(); + // fpslimit: wait for the next frame's slot (eu07/maszyna#416) + if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { - std::this_thread::sleep_for(Global.minframetime - frametime); + std::this_thread::sleep_until(*nextframe); } } // Handled by application.exit @@ -951,14 +967,17 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi } // for index -1 create a new child window - auto const *vmode{glfwGetVideoMode(monitor ? monitor : glfwGetPrimaryMonitor())}; - - // match requested video mode to current to allow for - // fullwindow creation when resolution is the same - glfwWindowHint(GLFW_RED_BITS, vmode->redBits); - glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits); - glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits); - glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate); + auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()}; + // a machine without a display (e.g. a test runner) has no monitor to match + if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr}) + { + // match requested video mode to current to allow for + // fullwindow creation when resolution is the same + glfwWindowHint(GLFW_RED_BITS, vmode->redBits); + glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits); + glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits); + glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate); + } glfwWindowHint(GLFW_VISIBLE, visible); @@ -1038,6 +1057,13 @@ void eu07_application::init_debug() void eu07_application::init_console() { #ifdef _WIN32 + if (Global.test.enabled) + { + // a test is started by whoever waits for its result, often reading its output: no console of its own + // (showsystemconsole) pops up and takes stdout away from them, and a console it was started from isn't hidden + return; + } + HWND consoleWnd = ::GetConsoleWindow(); const bool hadConsole = consoleWnd != nullptr; @@ -1138,9 +1164,30 @@ int eu07_application::init_settings(int Argc, char *Argv[]) { Global.asVersion = VERSION_INFO; + // a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a + // command line it can't take ends with the error code of the test, not with 0, which would pass it + auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))}; + if (false == testcommandline.error.empty()) + { + simulation::test().conclude(simulation::test_result::error, testcommandline.error); + return -1; + } + if (testcommandline.timeout.has_value()) + { + Global.test.timeout = *testcommandline.timeout; + Global.test.timeout_from_command_line = true; + } + if (testcommandline.wall_timeout.has_value()) + { + Global.test.wall_timeout = testcommandline.wall_timeout; + Global.test.wall_timeout_from_command_line = true; + } + fs::path iniPath = user_config_path("eu07.ini"); - if (!iniPath.empty() && fs::exists(iniPath)) + // a test reads the settings of the game folder only (and those given with -ini), not the player's own + // (%APPDATA%/MaSzyna, ~/.config/MaSzyna), so it runs the same for whoever runs it + if (false == Global.test.enabled && !iniPath.empty() && fs::exists(iniPath)) { Global.LoadIniFile(iniPath.string().c_str()); } @@ -1195,18 +1242,51 @@ int eu07_application::init_settings(int Argc, char *Argv[]) WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); } } + else if (token == "--test") + { + // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541), + // taken from the command line above + } + else if (token == "--test-timeout" || token == "--test-wall-timeout") + { + // taken from the command line above, with its value + ++i; + } + else if (token == "-ini") + { + // extra settings file read on top of eu07.ini, so a run can override a few keys + // (window size, physicslog...) without touching the user's own config + if (i + 1 < Argc) + { + Global.LoadIniFile(Argv[++i]); + } + } else { - std::cout << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]" + // a test's standard output carries its result only + (Global.test.enabled ? std::cerr : std::cout) << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]" << " [-v vehiclename]" << " [-edit [sceneryfilepath]]" - << " [-seed number|word]" << std::endl; + << " [-seed number|word]" + << " [-ini settingsfile]" + << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl; + simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } } if (editwithoutscenery && false == sceneryfromcommandline) Global.SceneryFile.clear(); + if (Global.test.enabled) + { + if (false == sceneryfromcommandline || Global.SceneryFile.empty()) + { + simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s"); + return -1; + } + simulation::apply_test_mode_settings(); + } + return 0; } @@ -1280,6 +1360,12 @@ int eu07_application::init_glfw() { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); } + else if (Global.test.enabled) + { + // the null renderer draws nothing, but parts of the ui make textures with gl calls of their own. + // any context will do for them, so none is asked for in particular: a machine without a graphics + // driver (a test runner) has only the basic one of the system + } else { if (!Global.LegacyRenderer) @@ -1331,7 +1417,8 @@ int eu07_application::init_glfw() Global.bFullScreen = true; } - auto *mainwindow = window(-1, true, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false); + // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it + auto *mainwindow = window(-1, false == Global.test.enabled, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false); if (mainwindow == nullptr) { @@ -1355,7 +1442,9 @@ int eu07_application::init_glfw() #ifdef _WIN32 // setup wrapper for base glfw window proc, to handle copydata messages Hwnd = glfwGetWin32Window(mainwindow); - BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); + // commands sent by other programs are input from outside, which a test doesn't take + if (false == Global.test.enabled) + BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); // switch off the topmost flag ::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); #endif @@ -1369,13 +1458,18 @@ void eu07_application::init_callbacks() auto *window{m_windows.front()}; glfwSetWindowSizeCallback(window, window_resize_callback); glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback); + glfwSetWindowFocusCallback(window, focus_callback); + glfwSetCursorEnterCallback(window, cursor_enter_callback); + if (Global.test.enabled) + { + // a test takes no input: keys and clicks sent to its hidden window would change the run + return; + } glfwSetCursorPosCallback(window, cursor_pos_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetKeyCallback(window, key_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetCharCallback(window, char_callback); - glfwSetWindowFocusCallback(window, focus_callback); - glfwSetCursorEnterCallback(window, cursor_enter_callback); } int eu07_application::init_ogl() @@ -1418,6 +1512,11 @@ int eu07_application::init_gfx() // default render path GfxRenderer = gfx_renderer_factory::get_instance()->create("modern"); } + else if (Global.GfxRenderer == "null") + { + // draws nothing and loads no textures (test mode) + GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + } else if (Global.GfxRenderer == "experimental") { GfxRenderer = gfx_renderer_factory::get_instance()->create(Global.GfxRenderer); diff --git a/application/driverhints.cpp b/application/driverhints.cpp index bcfd7dbd0..ae39ede7a 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -138,6 +138,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return mvOccupied->Radio == true; } ); break; } + case driver_hint::radiofuseon: { + if( AIControllFlag ) { + mvOccupied->RadioFuse = true; + } + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->RadioFuse == true; } ); + break; + } case driver_hint::radiochannel: { if( AIControllFlag ) { iRadioChannel = static_cast( Actionparameter ); diff --git a/application/driverhints_def.h b/application/driverhints_def.h index f59ed734c..2ce896679 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -2,6 +2,7 @@ DRIVER_HINT_DEF(batteryon, STRN("Switch on battery")) DRIVER_HINT_DEF(batteryoff, STRN("Switch off battery")) DRIVER_HINT_DEF(radioon, STRN("Switch on radio")) DRIVER_HINT_DEF(radiooff, STRN("Switch off radio")) +DRIVER_HINT_DEF(radiofuseon, STRN("Close radio fuse")) DRIVER_HINT_DEF(radiochannel, STRN("Tune into channel %.0f")) DRIVER_HINT_DEF(oilpumpon, STRN("Switch on oil pump")) DRIVER_HINT_DEF(oilpumpoff, STRN("Switch off oil pump")) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index b55d09c2b..deb906a4a 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" #include "scene/scene.h" #include "rendering/lightarray.h" #include "rendering/particles.h" @@ -305,6 +306,11 @@ bool driver_mode::update() simulation::Events.update(); simulation::Region->update_events(); simulation::Lights.update(); + + if (Global.test.enabled && simulation::is_ready) + { + simulation::test().update(deltatime); + } } // render time routines follow: @@ -478,6 +484,13 @@ void driver_mode::enter() Timer::ResetTimers(); + if (Global.test.enabled) + { + // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree + Timer::set_fixed_step(simulation::test_manager::frame_step); + simulation::test().start(); + } + set_picking(!Global.captureonstart); m_editorpending = Global.editor_session; diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index e318d3563..029b8d7f1 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -206,6 +206,24 @@ drivingaid_panel::update() { } } +void +drivingaid_panel::render_contents() { + ImGui::Checkbox(STR_C("expand"), &is_expanded); + + ImGui::SameLine(); + + auto const *driver = (simulation::Train && simulation::Train->Dynamic()) ? simulation::Train->Dynamic()->Mechanik : nullptr; + if (driver && (false == Global.RealisticControlMode || DebugModeFlag)) { + bool autopilot = driver->AIControllFlag; + if (ImGui::Checkbox(STR_C("autopilot"), &autopilot)) { + command_relay commandrelay; + commandrelay.post(autopilot ? user_command::aidriverenable : user_command::aidriverdisable, 0.0, 0.0, GLFW_PRESS, 0); + } + } + + ui_panel::render_contents(); +} + void scenario_panel::update() { @@ -810,7 +828,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.HeatingAllow ? 'h' : '.', mover.Hamulec->Releaser() ? '^' : '.', - std::string( m_input.mechanik ? STR(" R") + ( mover.Radio ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), + std::string( m_input.mechanik ? STR(" R") + ( mover.Radio && mover.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( mover.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers // 3000v diff --git a/application/driveruipanels.h b/application/driveruipanels.h index 96b9ac1c7..393d0e9a3 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -20,6 +20,7 @@ public: {} void update() override; + void render_contents() override; private: // members diff --git a/application/editormode.cpp b/application/editormode.cpp index 32f991c55..1ad3ef6ed 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -4804,8 +4804,12 @@ void editor_mode::render_gizmo() snapvalue = glm::vec3(0.1f); float const *snap = Global.ctrlState && snapvalue.x > 0.0f ? glm::value_ptr(snapvalue) : nullptr; + // the change of this frame alone: a turn is taken from it, not from the angles the whole matrix decomposes into, + // which can't tell a turn of more than 90 degrees about the vertical axis (it comes out as 180 - angle with the + // other two axes flipped, and the model turned back and forth while dragged one way) + glm::mat4 delta(1.0f); ImGuizmo::Manipulate(glm::value_ptr(view), glm::value_ptr(projection), - operation, mode, glm::value_ptr(matrix), nullptr, snap); + operation, mode, glm::value_ptr(matrix), glm::value_ptr(delta), snap); if (ImGuizmo::IsUsing()) { @@ -4822,9 +4826,11 @@ void editor_mode::render_gizmo() if (operation == ImGuizmo::ROTATE && model) { - // apply the rotation delta relative to the model's current orientation - glm::vec3 const newangles(newrotation[0], newrotation[1], newrotation[2]); - auto const turned{newangles - model->Angles()}; + // the turn of this frame, small, so its angles decompose with no ambiguity + float deltatranslation[3], deltarotation[3], deltascale[3]; + ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(delta), deltatranslation, deltarotation, deltascale); + auto const wrapped = [](float Angle) { return Angle - 360.0f * std::floor((Angle + 180.0f) / 360.0f); }; + glm::vec3 const turned{wrapped(deltarotation[0]), wrapped(deltarotation[1]), wrapped(deltarotation[2])}; m_editor.rotate(model, turned, 0.0f); selection_follow(glm::dvec3(0.0), turned, model->location()); } diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp index f8f06ac93..20fa46d3d 100644 --- a/application/scenarioloadermode.cpp +++ b/application/scenarioloadermode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" #include "application/application.h" #include "application/scenarioloaderuilayer.h" #include "rendering/renderer.h" @@ -58,6 +59,10 @@ bool scenarioloader_mode::update() { catch (std::runtime_error const &e) { ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what())); state.reset(); + if (Global.test.enabled) { + simulation::test().finish(simulation::test_result::error, "scenario couldn't be opened"); + return true; + } Global.SceneryFile.clear(); Application.pop_mode(); Application.push_mode(eu07_application::mode::launcher); @@ -73,6 +78,11 @@ bool scenarioloader_mode::update() { // back to the launcher as when the scenario can't be opened, not on to the driver mode with the scenery half loaded ErrorLog( "Bad init: scenario loading failed" ); state.reset(); + if( Global.test.enabled ) { + // there's nothing to test; the exit code says the run went wrong + simulation::test().finish( simulation::test_result::error, "scenario loading failed" ); + return true; + } Global.SceneryFile.clear(); Application.pop_mode(); Application.push_mode(eu07_application::mode::launcher); diff --git a/application/uilayer.cpp b/application/uilayer.cpp index 5443d158c..9493f77f6 100644 --- a/application/uilayer.cpp +++ b/application/uilayer.cpp @@ -288,6 +288,11 @@ bool ui_layer::init(GLFWwindow *Window) IMGUI_CHECKVERSION(); ImGui::CreateContext(); m_imguiio = &ImGui::GetIO(); + if (Global.test.enabled) + { + // a test leaves the player's window layout alone (imgui.ini in the game folder), runs in parallel included + m_imguiio->IniFilename = nullptr; + } ImGui::GetCurrentContext()->ConfigNavWindowingKeyNext = ImGuiKey_None; ImGui::GetCurrentContext()->ConfigNavWindowingKeyPrev = ImGuiKey_None; // imgui.ini is read with the first frame, which may be of another mode than the editor @@ -404,6 +409,8 @@ bool ui_layer::init(GLFWwindow *Window) if (!gamepadui) gamepadui = ""; auto const viewportsupport{(m_imguiio->BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (m_imguiio->BackendFlags & ImGuiBackendFlags_RendererHasViewports) && glfwGetPlatform() != GLFW_PLATFORM_WAYLAND && std::string_view{desktop} != "gamescope" && std::string_view{gamepadui} != "1"}; + // a tooltip as long as a paragraph is wrapped: in one line it can run past the screen + m_imguiio->ConfigTooltipsWrapWidth = std::round(Global.ui_fontsize * 40.0f); if (Global.ui_viewports && viewportsupport) { m_imguiio->ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; diff --git a/ci_shadervalidator/Globals.h b/ci_shadervalidator/Globals.h index 16f85e802..e8f548dc3 100644 --- a/ci_shadervalidator/Globals.h +++ b/ci_shadervalidator/Globals.h @@ -8,6 +8,7 @@ struct _global bool gfx_extraeffects; bool gfx_shadergamma; bool gfx_usegles; + int iMultisampling; }; extern _global Global; diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 7a4b53aa2..65ad54b2a 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -46,6 +46,8 @@ bool check_shader_allopts(std::string filename) Global.gfx_skippipeline = false; Global.gfx_extraeffects = true; Global.gfx_shadergamma = true; + // the default of the simulator, which compiles the alpha to coverage branches of the shaders + Global.iMultisampling = 2; if (!check_shader(filename)) suc = false; @@ -56,6 +58,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_skippipeline = true; Global.gfx_extraeffects = false; Global.gfx_shadergamma = false; + Global.iMultisampling = 0; if (!check_shader(filename)) suc = false; diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index 26c310000..e621fdc6b 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -11,6 +11,7 @@ void gl::glsl_common_setup() "#define MOTIONBLUR_ENABLED " + std::to_string((int)Global.gfx_postfx_motionblur_enabled) + "\n" + "#define POSTFX_ENABLED " + std::to_string((int)!Global.gfx_skippipeline) + "\n" + "#define EXTRAEFFECTS_ENABLED " + std::to_string((int)Global.gfx_extraeffects) + "\n" + + "#define ALPHA_TO_COVERAGE_ENABLED " + std::to_string((int)(Global.iMultisampling > 0)) + "\n" + "#define MAX_LIGHTS " + std::to_string(MAX_LIGHTS) + "U\n" + "#define MAX_CASCADES " + std::to_string(MAX_CASCADES) + "U\n" + "#define MAX_PARAMS " + std::to_string(MAX_PARAMS) + "U\n" + @@ -64,6 +65,7 @@ void gl::glsl_common_setup() float fog_density; float alpha_mult; float shadow_tone; + float alpha_to_coverage; }; layout (std140) uniform scene_ubo @@ -110,5 +112,41 @@ void gl::glsl_common_setup() } #endif + #ifdef STAGE_FRAGMENT + // alpha tested surfaces (positive opacity, the opaque pass) get the coverage of their alpha + // test edge from GL_SAMPLE_ALPHA_TO_COVERAGE, which the renderer turns on for them with + // multisampling; otherwise the alpha test keeps or drops whole pixels and its edges stay + // jagged whatever the multisampling. the alpha is sharpened to go from 0 to 1 over about + // a pixel around the test threshold, so the edge keeps the place and sharpness the alpha + // test gave it. computed before any discard, which leaves the derivatives undefined. + // alpha_to_coverage of model_ubo tells whether alpha to coverage is on for this draw; where + // it isn't (reflections, previews) the shaders keep the plain alpha test + float alpha_coverage(float alpha) + { + #if ALPHA_TO_COVERAGE_ENABLED + if (opacity > 0.0 && alpha_to_coverage > 0.0) + { + // a flat alpha has no edge in the pixel and gets the plain test, so an alpha equal + // to the threshold stays fully covered + float fw = fwidth(alpha); + return (fw > 0.0 ? clamp((alpha - opacity) / fw + 0.5, 0.0, 1.0) : step(opacity, alpha)); + } + #endif + return alpha; + } + + // true for the fragments the alpha test drops: below the opacity threshold in the opaque + // pass, at or above it (negative opacity) in the translucent pass. with alpha to coverage + // only the fragments which cover no sample at all + bool alpha_test_fail(float alpha, float coverage) + { + #if ALPHA_TO_COVERAGE_ENABLED + if (opacity > 0.0 && alpha_to_coverage > 0.0) + return coverage <= 0.0; + #endif + return (opacity >= 0.0 ? (alpha < opacity) : (alpha >= -opacity)); + } + #endif + )STRING"; } diff --git a/gl/shader.cpp b/gl/shader.cpp index 9160a2c97..31a3e6a87 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -175,6 +175,8 @@ std::pair gl::shader::process_source(const std::string &fil str += "vec4 FBOUT(vec4 x) { return " + (Global.gfx_shadergamma ? std::string("vec4(pow(x.rgb, vec3(1.0 / 2.2)), x.a)") : std::string("x")) + "; }\n"; str += read_file(basedir + filename); + // checked before the includes are expanded, since glsl_common defines the function + alpha_to_coverage = ( str.find( "alpha_test_fail(" ) != std::string::npos ); expand_includes(str, basedir); parse_texture_entries(str); @@ -381,6 +383,7 @@ void gl::program::attach(const gl::shader &s) texture_conf.try_emplace(texturename, std::move(textureentry)); for (auto [paramname, paramentry] : s.param_conf) param_conf.try_emplace(paramname, std::move(paramentry)); + alpha_to_coverage = alpha_to_coverage || s.alpha_to_coverage; glAttachShader(*this, *s); } diff --git a/gl/shader.h b/gl/shader.h index f1735a0e9..e46c14273 100644 --- a/gl/shader.h +++ b/gl/shader.h @@ -63,6 +63,9 @@ namespace gl std::unordered_map texture_conf; std::unordered_map param_conf; std::string name; + // the shader does its alpha test with alpha_test_fail() of glsl_common, so its alpha + // output can drive GL_SAMPLE_ALPHA_TO_COVERAGE in the opaque pass + bool alpha_to_coverage{ false }; #ifndef SHADERVALIDATOR_STANDALONE private: @@ -96,6 +99,7 @@ namespace gl std::unordered_map texture_conf; std::unordered_map param_conf; + bool alpha_to_coverage{ false }; private: void init(); diff --git a/gl/ubo.h b/gl/ubo.h index 9d2c96912..0e5901cb3 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -76,7 +76,11 @@ namespace gl float fog_density; float alpha_mult; float shadow_tone; - UBS_PAD(12); + // 1.0 while GL_SAMPLE_ALPHA_TO_COVERAGE is on, so the alpha tested shaders write the + // coverage of their test edge; 0.0 keeps their plain alpha test. set together with + // the GL state by opengl33_renderer::setup_alpha_to_coverage() + float alpha_to_coverage; + UBS_PAD(8); void set_modelview(const glm::mat4 &mv) { diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp index a9026b408..2579bf4d6 100644 --- a/imgui/imgui.cpp +++ b/imgui/imgui.cpp @@ -1508,6 +1508,7 @@ ImGuiIO::ImGuiIO() ConfigWindowsCopyContentsWithCtrlC = false; ConfigScrollbarScrollByPage = true; ConfigMemoryCompactTimer = 60.0f; + ConfigTooltipsWrapWidth = 0.0f; ConfigDebugIsDebuggerPresent = false; ConfigDebugHighlightIdConflicts = true; ConfigDebugHighlightIdConflictsShowItemPicker = true; @@ -12112,7 +12113,14 @@ void ImGui::SetTooltipV(const char* fmt, va_list args) { if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None)) return; + // MaSzyna addition: see io.ConfigTooltipsWrapWidth + ImGuiContext& g = *GImGui; + const bool wrap = g.IO.ConfigTooltipsWrapWidth > 0.0f; + if (wrap) + PushTextWrapPos(GetCursorPosX() + g.IO.ConfigTooltipsWrapWidth); TextV(fmt, args); + if (wrap) + PopTextWrapPos(); EndTooltip(); } @@ -16375,9 +16383,11 @@ static void ImGui::WindowSelectViewport(ImGuiWindow* window) } // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport + // MaSzyna addition: with io.ConfigViewportsNoAutoDetach the tooltips and popups stay in the main viewport here too if (window->Viewport == NULL) if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) - window->Viewport = WindowStaysInHostViewport(window, main_viewport) ? main_viewport : AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + window->Viewport = (WindowStaysInHostViewport(window, main_viewport) || (g.IO.ConfigViewportsNoAutoDetach && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)))) + ? main_viewport : AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); // Mark window as allowed to protrude outside of its viewport and into the current monitor if (!lock_viewport) @@ -16393,6 +16403,10 @@ static void ImGui::WindowSelectViewport(ImGuiWindow* window) window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); else window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + // MaSzyna addition: see io.ConfigViewportsNoAutoDetach. Over the main viewport they stay inside it: the late creation of a + // viewport in Begin() needs the extent of the monitor + if (g.IO.ConfigViewportsNoAutoDetach && window->Viewport == main_viewport) + window->ViewportAllowPlatformMonitorExtend = -1; } else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL) { diff --git a/imgui/imgui.h b/imgui/imgui.h index 6bbc42dec..6988a0127 100644 --- a/imgui/imgui.h +++ b/imgui/imgui.h @@ -2360,7 +2360,7 @@ struct ImGuiIO bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. - bool ConfigViewportsNoAutoDetach; // = false // MaSzyna addition: a floating window stays inside its host viewport: a resize stops at its edge, and a window left past it, or too big for it, is moved and shrunk to fit. It gets a viewport of its own only when dragged with the mouse cursor past the host viewport. Popups and tooltips are not affected. + bool ConfigViewportsNoAutoDetach; // = false // MaSzyna addition: a floating window stays inside its host viewport: a resize stops at its edge, and a window left past it, or too big for it, is moved and shrunk to fit. It gets a viewport of its own only when dragged with the mouse cursor past the host viewport. Tooltips and popups shown over the main viewport, or begun outside any window, get no viewport of their own either: they are placed inside the main viewport as with the viewports off. // Miscellaneous options // (you can visualize and interact with all options in 'Demo->Configuration') @@ -2375,6 +2375,7 @@ struct ImGuiIO bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] CTRL+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order. bool ConfigScrollbarScrollByPage; // = true // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location. float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. + float ConfigTooltipsWrapWidth; // = 0.0f // MaSzyna addition: the text of SetTooltip() and SetItemTooltip() wraps at this width, in pixels; 0: it doesn't wrap. BeginTooltip() is not affected. // Inputs Behaviors // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) diff --git a/input/command.cpp b/input/command.cpp index 0ae67cfa5..7d3fe7d1d 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -158,6 +158,9 @@ commanddescription_sequence Commands_descriptions = { {"radiovolumeincrease", command_target::vehicle, command_mode::oneoff}, {"radiovolumedecrease", command_target::vehicle, command_mode::oneoff}, {"radiovolumeset", command_target::vehicle, command_mode::oneoff}, + {"radiofusetoggle", command_target::vehicle, command_mode::oneoff}, + {"radiofuseenable", command_target::vehicle, command_mode::oneoff}, + {"radiofusedisable", command_target::vehicle, command_mode::oneoff}, {"cabchangeforward", command_target::vehicle, command_mode::oneoff}, {"cabchangebackward", command_target::vehicle, command_mode::oneoff}, {"modernlightdimmerdecrease", command_target::vehicle, command_mode::oneoff}, @@ -406,6 +409,12 @@ commanddescription_sequence Commands_descriptions = { {"wiperswitchdecrease", command_target::vehicle, command_mode::oneoff}, {"lightsset", command_target::vehicle, command_mode::oneoff}, {"oilfuelpumptoggle", command_target::vehicle, command_mode::oneoff}, + {"linebreakertoggleb", command_target::vehicle, command_mode::oneoff}, + {"linebreakeropenb", command_target::vehicle, command_mode::oneoff}, + {"linebreakercloseb", command_target::vehicle, command_mode::oneoff}, + {"linebreakertogglec", command_target::vehicle, command_mode::oneoff}, + {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, + {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -544,6 +553,9 @@ std::unordered_map const commandMap = { {"radiovolumeincrease", user_command::radiovolumeincrease}, {"radiovolumedecrease", user_command::radiovolumedecrease}, {"radiovolumeset", user_command::radiovolumeset}, + {"radiofusetoggle", user_command::radiofusetoggle}, + {"radiofuseenable", user_command::radiofuseenable}, + {"radiofusedisable", user_command::radiofusedisable}, {"cabchangeforward", user_command::cabchangeforward}, {"cabchangebackward", user_command::cabchangebackward}, {"viewturn", user_command::viewturn}, @@ -791,6 +803,12 @@ std::unordered_map const commandMap = { {"wiperswitchdecrease", user_command::wiperswitchdecrease}, {"lightsset", user_command::lightsset}, {"oilfuelpumptoggle", user_command::oilfuelpumptoggle}, + {"linebreakertoggleb", user_command::linebreakertoggleb}, + {"linebreakeropenb", user_command::linebreakeropenb}, + {"linebreakercloseb", user_command::linebreakercloseb}, + {"linebreakertogglec", user_command::linebreakertogglec}, + {"linebreakeropenc", user_command::linebreakeropenc}, + {"linebreakerclosec", user_command::linebreakerclosec}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index ddacef4a0..aaf361e25 100644 --- a/input/command.h +++ b/input/command.h @@ -151,6 +151,9 @@ enum class user_command radiovolumeincrease, radiovolumedecrease, radiovolumeset, + radiofusetoggle, + radiofuseenable, + radiofusedisable, cabchangeforward, cabchangebackward, @@ -404,6 +407,12 @@ enum class user_command wiperswitchdecrease, lightsset, oilfuelpumptoggle, + linebreakertoggleb, + linebreakeropenb, + linebreakercloseb, + linebreakertogglec, + linebreakeropenc, + linebreakerclosec, none = -1 }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index e7e636b31..047f3678c 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -160,6 +160,9 @@ driverkeyboard_input::default_bindings() { // radiovolumeincrease, // radiovolumedecrease, // radiovolumeset, + // radiofusetoggle, + // radiofuseenable, + // radiofusedisable, { cabchangeforward, {GLFW_KEY_HOME, ""} }, { cabchangebackward, {GLFW_KEY_END, ""} }, // viewturn, diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 22562b856..222c58a62 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -597,6 +597,18 @@ drivermouse_input::default_bindings() { { "main_on_bt:",{ linebreakerclose, none } }, + { "mainb_off_bt:", { + linebreakeropenb, + none } }, + { "mainb_on_bt:", { + linebreakercloseb, + none } }, + { "mainc_off_bt:", { + linebreakeropenc, + none } }, + { "mainc_on_bt:", { + linebreakerclosec, + none } }, { "security_reset_bt:", { alerteracknowledge, none } }, @@ -774,6 +786,12 @@ drivermouse_input::default_bindings() { { "main_sw:", { linebreakertoggle, none } }, + { "mainb_sw:", { + linebreakertoggleb, + none } }, + { "mainc_sw:", { + linebreakertogglec, + none } }, { "radio_sw:", { radiotoggle, none } }, @@ -783,6 +801,15 @@ drivermouse_input::default_bindings() { { "radiooff_sw:", { radiodisable, none } }, + { "radiofuse_sw:", { + radiofusetoggle, + none } }, + { "radiofuseon_sw:", { + radiofuseenable, + none } }, + { "radiofuseoff_sw:", { + radiofusedisable, + none } }, { "radiochannel_sw:", { radiochannelincrease, radiochanneldecrease } }, diff --git a/lang/editor_tutorial/camera.gif b/lang/editor_tutorial/camera.gif new file mode 100644 index 000000000..3558c0c12 Binary files /dev/null and b/lang/editor_tutorial/camera.gif differ diff --git a/lang/editor_tutorial/curves.gif b/lang/editor_tutorial/curves.gif new file mode 100644 index 000000000..2d9f93a05 Binary files /dev/null and b/lang/editor_tutorial/curves.gif differ diff --git a/lang/editor_tutorial/edit.gif b/lang/editor_tutorial/edit.gif new file mode 100644 index 000000000..e8aa5e162 Binary files /dev/null and b/lang/editor_tutorial/edit.gif differ diff --git a/lang/editor_tutorial/gizmo.gif b/lang/editor_tutorial/gizmo.gif new file mode 100644 index 000000000..c5f192c36 Binary files /dev/null and b/lang/editor_tutorial/gizmo.gif differ diff --git a/lang/editor_tutorial/join.gif b/lang/editor_tutorial/join.gif new file mode 100644 index 000000000..49c5e75e7 Binary files /dev/null and b/lang/editor_tutorial/join.gif differ diff --git a/lang/editor_tutorial/lay.gif b/lang/editor_tutorial/lay.gif new file mode 100644 index 000000000..09c9da71a Binary files /dev/null and b/lang/editor_tutorial/lay.gif differ diff --git a/lang/editor_tutorial/plan.gif b/lang/editor_tutorial/plan.gif new file mode 100644 index 000000000..03f5e7f77 Binary files /dev/null and b/lang/editor_tutorial/plan.gif differ diff --git a/lang/editor_tutorial/switch.gif b/lang/editor_tutorial/switch.gif new file mode 100644 index 000000000..56d219146 Binary files /dev/null and b/lang/editor_tutorial/switch.gif differ diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp index 332d357c7..bc466e977 100644 --- a/rendering/nullrenderer.cpp +++ b/rendering/nullrenderer.cpp @@ -1,6 +1,26 @@ #include "stdafx.h" #include "rendering/nullrenderer.h" +#include "application/application.h" + +void null_imgui_renderer::BeginFrame() +{ + auto &io { ImGui::GetIO() }; + if( false == io.Fonts->IsBuilt() ) { + unsigned char *pixels { nullptr }; + int width { 0 }; + int height { 0 }; + io.Fonts->GetTexDataAsAlpha8( &pixels, &width, &height ); + } +} + +bool null_renderer::Render() +{ + // the ui frame begun by the application has to be ended, or imgui won't start the next one + Application.render_ui(); + return true; +} + std::unique_ptr null_renderer::create_func() { return std::make_unique(); diff --git a/rendering/nullrenderer.h b/rendering/nullrenderer.h index 0b21580b9..7ecb57bf8 100644 --- a/rendering/nullrenderer.h +++ b/rendering/nullrenderer.h @@ -35,7 +35,18 @@ private: release_() override { /* null implementation, nothing to do */ } }; +// user interface backend which draws nothing: imgui still builds its frames, so the ui code runs as usual +class null_imgui_renderer final : public imgui_renderer { +public: + bool Init() override { return true; } + void Shutdown() override { /* null implementation, nothing to do */ } + // imgui wants its font atlas built before a frame starts; that's done on the cpu, no texture is made of it + void BeginFrame() override; + void Render() override { /* null implementation, nothing to do */ } +}; + // bare-bones render controller, in lack of anything better yet +// it's the renderer of the test mode (--test): models are loaded for the physics, textures aren't class null_renderer : public gfx_renderer { public: @@ -49,7 +60,7 @@ public: Init( GLFWwindow *Window ) override { return true; } // main draw call. returns false on error bool - Render() override { return true; } + Render() override; void SwapBuffers() override { /* null implementation, nothing to do */ } inline @@ -105,20 +116,22 @@ public: void Bind_Material( material_handle const Material, TSubModel const *sm = nullptr, lighting_data const *lighting = nullptr ) override { /* null implementation, nothing to do */ } IMaterial const * - Material( material_handle const Material ) const override { return m_materials.at(Material - 1).get(); } + Material( material_handle const Material ) const override { + return ( Material > 0 && static_cast( Material ) <= m_materials.size() ? m_materials[ Material - 1 ].get() : IMaterial::null_material() ); } // shader methods auto Fetch_Shader( std::string const &name ) -> std::shared_ptr override { throw std::runtime_error("not impl"); } // texture methods + // no textures are loaded; whoever asks gets the null texture texture_handle - Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { throw std::runtime_error("not impl"); } + Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { return null_handle; } void Bind_Texture( texture_handle const Texture ) override { /* null implementation, nothing to do */ } void Bind_Texture( std::size_t const Unit, texture_handle const Texture ) override { /* null implementation, nothing to do */ } - opengl_texture & - Texture( texture_handle const Texture ) override { throw std::runtime_error("not impl"); } - opengl_texture const & - Texture( texture_handle const Texture ) const override { throw std::runtime_error("not impl"); } + ITexture & + Texture( texture_handle const Texture ) override { return *ITexture::null_texture(); } + ITexture const & + Texture( texture_handle const Texture ) const override { return *ITexture::null_texture(); } // utility methods void Pick_Control_Callback( std::function Callback ) override { /* null implementation, nothing to do */ } @@ -152,11 +165,12 @@ public: imgui_renderer *GetImguiRenderer() override { - return nullptr; + return &m_imgui; } private: std::string empty_str; + null_imgui_renderer m_imgui; gfx::geometrybank_manager m_geometry; std::vector> m_materials; }; diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index c24f750c8..d96c878f4 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -1820,6 +1820,22 @@ void opengl33_renderer::setup_matrices() OpenGLMatrices.load_matrix(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); } +void opengl33_renderer::setup_alpha_to_coverage(bool const Enable) +{ + // the shaders keep the plain alpha test unless told the coverage of their alpha is used; + // uploaded with the rest of the model block at the next draw + model_ubs.alpha_to_coverage = (Enable ? 1.f : 0.f); + + if (Enable == m_alphatocoverageenabled) + return; + + if (Enable) + glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); + else + glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + m_alphatocoverageenabled = Enable; +} + void opengl33_renderer::setup_drawing(bool const Alpha) { if (Alpha) @@ -1834,6 +1850,8 @@ void opengl33_renderer::setup_drawing(bool const Alpha) glDepthMask(GL_TRUE); m_blendingenabled = false; } + // turned on again per material, by the ones which need it + setup_alpha_to_coverage(false); switch (m_renderpass.draw_mode) { @@ -2032,12 +2050,12 @@ bool opengl33_renderer::Render(world_environment *Environment) glm::vec4 color(suncolor.x, suncolor.y, suncolor.z, std::clamp(1.5f - Global.Overcast, 0.f, 1.f) * fogfactor); auto const sunvector = Environment->m_sun.getDirection(); - /*float const size = std::lerp( // TODO: expose distance/scale factor from the moon object + float const size = std::lerp( // TODO: expose distance/scale factor from the moon object 0.0325f, 0.0275f, - std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );*/ + std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f ); model_ubs.param[0] = color; - model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), 0.00463f /* size */); + model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), size); model_ubs.param[2] = glm::vec4(0.0f, 1.0f, 1.0f, 0.0f); model_ubo->update(model_ubs); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); @@ -2108,14 +2126,13 @@ bool opengl33_renderer::Render(world_environment *Environment) moonu = 0.0f; } - /* float const size = std::lerp( // TODO: expose distance/scale factor from the moon object 0.0160f, 0.0135f, - std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );*/ + std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f ); model_ubs.param[0] = color; - model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), 0.00451f /* size */); + model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), size); model_ubs.param[2] = glm::vec4(moonu, moonv, 0.333f, 0.0f); model_ubo->update(model_ubs); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); @@ -2375,6 +2392,18 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel else model_ubs.alpha_mult = 1.0f; + // the alpha test drops or keeps whole pixels, so multisampling alone leaves its edges (e.g. sides + // of the trackbed textures) jagged. the alpha tested materials of the opaque colour pass get them + // antialiased with alpha to coverage instead; their shaders give the coverage as the alpha. + // the model previews draw in colour mode too, but to a single-sampled framebuffer + setup_alpha_to_coverage( + Global.iMultisampling > 0 + && false == m_blendingenabled + && m_renderpass.draw_mode == rendermode::color + && false == m_previewing + && model_ubs.opacity > 0.f + && material.shader->alpha_to_coverage ); + // materials which declare texture variants provide a different texture set per model instance, // picked from the seed of the rendered instance and the variant group of the submodel auto const &materialtextures{ @@ -5663,12 +5692,15 @@ void opengl33_renderer::Update(double const Deltatime) } m_updateaccumulator = 0.0; - m_framerate = 1000.f / ( Timer::subsystem.mainloop_total.average() ); + // the frames actually shown, the wait for fpslimit included (eu07/maszyna#416) + m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() ); + // the frames the work alone would allow, so a frame rate held down by fpslimit doesn't cut the draw ranges + auto const workframerate{1000.f / Timer::subsystem.mainloop_total.average()}; // adjust draw ranges etc, based on recent performance if (Global.targetfps != 0.0f) { - float fps_diff = Global.targetfps - m_framerate; + float fps_diff = Global.targetfps - workframerate; if (fps_diff > 0.0f) Global.fDistanceFactor = std::max(0.5f, Global.fDistanceFactor - 0.05f); else @@ -5676,7 +5708,7 @@ void opengl33_renderer::Update(double const Deltatime) } // legacy framerate parameters else if (Global.fFpsAverage != 0.f) { - auto const fps_diff = m_framerate - Global.fFpsAverage; + auto const fps_diff = workframerate - Global.fFpsAverage; if (fps_diff < -Global.fFpsDeviation) { Global.fDistanceFactor = std::min(std::max(1.0f, Global.fDistanceFactor - 0.05f), Global.gfx_distance_factor_max); } diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 1b4897386..0e84761e1 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -277,6 +277,8 @@ class opengl33_renderer : public gfx_renderer { void setup_pass(viewport_config &Viewport, renderpass_config &Config, rendermode const Mode, float const Znear = 0.f, float const Zfar = 1.f, bool const Ignoredebug = false); void setup_matrices(); void setup_drawing(bool const Alpha = false); + // alpha to coverage for the alpha tested materials of the opaque colour pass, when multisampled + void setup_alpha_to_coverage(bool const Enable); void setup_shadow_unbind_map(); void setup_shadow_bind_map(); void setup_shadow_color( glm::vec4 const &Shadowcolor ); @@ -560,6 +562,7 @@ class opengl33_renderer : public gfx_renderer { material_handle m_invalid_material; bool m_blendingenabled; + bool m_alphatocoverageenabled{ false }; bool m_widelines_supported; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 180dba771..8c6debdc7 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -68,6 +68,28 @@ submodel_material( TSubModel const *Submodel ) { null_handle ); } +bool +is_scaled( glm::vec3 const &Scale ) { + + return ( Scale.x != 1.0f ) || ( Scale.y != 1.0f ) || ( Scale.z != 1.0f ); +} + +// pushes the placement of a scaled model instance: the translation and rotation of Render( TModel3d *, ..., Position, Angle ), +// followed by the scale of the instance, applied before the submodel transforms (as in the opengl 3.3 renderer) +void +push_scaled_instance_transform( glm::dvec3 const &Position, glm::vec3 const &Angle, glm::vec3 const &Scale ) { + + ::glPushMatrix(); + ::glTranslated( Position.x, Position.y, Position.z ); + if( Angle.y != 0.0 ) + ::glRotatef( Angle.y, 0.f, 1.f, 0.f ); + if( Angle.x != 0.0 ) + ::glRotatef( Angle.x, 1.f, 0.f, 0.f ); + if( Angle.z != 0.0 ) + ::glRotatef( Angle.z, 0.f, 0.f, 1.f ); + ::glScalef( Scale.x, Scale.y, Scale.z ); +} + } // namespace float const EU07_OPACITYDEFAULT { 0.5f }; @@ -2475,12 +2497,23 @@ opengl_renderer::Render( TAnimModel *Instance ) { Instance->RaPrepare(); if( Instance->pModel ) { // renderowanie rekurencyjne submodeli - Render( - Instance->pModel, - Instance->Material(), - distancesquared, - Instance->location() - m_renderpass.camera.position(), - Instance->vAngle ); + auto const position { Instance->location() - m_renderpass.camera.position() }; + if( is_scaled( Instance->Scale() ) ) { + // the scale stretches the normals too, they're normalized again for the lighting + push_scaled_instance_transform( position, Instance->vAngle, Instance->Scale() ); + m_normalizenormals = true; + Render( Instance->pModel, Instance->Material(), distancesquared ); + m_normalizenormals = false; + ::glPopMatrix(); + } + else { + Render( + Instance->pModel, + Instance->Material(), + distancesquared, + position, + Instance->vAngle ); + } // debug data ++m_renderpass.draw_stats.models; } @@ -2848,7 +2881,7 @@ opengl_renderer::Render( TSubModel *Submodel ) { break; } } #else - if( true == m_renderspecular ) { + if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) { ::glEnable( GL_NORMALIZE ); } #endif @@ -2937,7 +2970,7 @@ opengl_renderer::Render( TSubModel *Submodel ) { break; } } #else - if( true == m_renderspecular ) { + if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) { ::glDisable( GL_NORMALIZE ); } #endif @@ -3632,12 +3665,23 @@ opengl_renderer::Render_Alpha( TAnimModel *Instance ) { Instance->RaPrepare(); if( Instance->pModel ) { // renderowanie rekurencyjne submodeli - Render_Alpha( - Instance->pModel, - Instance->Material(), - distancesquared, - Instance->location() - m_renderpass.camera.position(), - Instance->vAngle ); + auto const position { Instance->location() - m_renderpass.camera.position() }; + if( is_scaled( Instance->Scale() ) ) { + // the scale stretches the normals too, they're normalized again for the lighting + push_scaled_instance_transform( position, Instance->vAngle, Instance->Scale() ); + m_normalizenormals = true; + Render_Alpha( Instance->pModel, Instance->Material(), distancesquared ); + m_normalizenormals = false; + ::glPopMatrix(); + } + else { + Render_Alpha( + Instance->pModel, + Instance->Material(), + distancesquared, + position, + Instance->vAngle ); + } } } @@ -3940,7 +3984,7 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { break; } } #else - if( true == m_renderspecular ) { + if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) { ::glEnable( GL_NORMALIZE ); } #endif @@ -4010,7 +4054,7 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { break; } } #else - if( true == m_renderspecular ) { + if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) { ::glDisable( GL_NORMALIZE ); } #endif @@ -4327,12 +4371,15 @@ opengl_renderer::Update( double const Deltatime ) { } m_updateaccumulator = 0.0; - m_framerate = 1000.f / ( Timer::subsystem.gfx_total.average() ); + // the frames actually shown, the wait for fpslimit included (eu07/maszyna#416) + m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() ); + // the draw ranges follow the time spent on drawing alone, as before + auto const drawframerate { 1000.f / ( Timer::subsystem.gfx_total.average() ) }; // adjust draw ranges etc, based on recent performance // TODO: it doesn't make much sense with vsync if( Global.targetfps != 0.f ) { - auto const fps_diff = m_framerate - Global.targetfps; + auto const fps_diff = drawframerate - Global.targetfps; if( fps_diff < -0.5f ) { Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max ); } @@ -4342,7 +4389,7 @@ opengl_renderer::Update( double const Deltatime ) { } // legacy framerate parameters else if( Global.fFpsAverage != 0.f ) { - auto const fps_diff = m_framerate - Global.fFpsAverage; + auto const fps_diff = drawframerate - Global.fFpsAverage; if( fps_diff < -Global.fFpsDeviation ) { Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max ); } diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index 3a3538a6c..15c9e7cdb 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -364,6 +364,7 @@ private: float m_specularopaquescalefactor { 1.f }; float m_speculartranslucentscalefactor { 1.f }; bool m_renderspecular{ false }; // controls whether to include specular component in the calculations + bool m_normalizenormals{ false }; // set while a scaled model instance is drawn, its normals need normalizing for the lighting renderpass_config m_renderpass; // parameters for current render pass section_sequence m_sectionqueue; // list of sections in current render pass diff --git a/shaders/mat_default.frag b/shaders/mat_default.frag index bc48d939c..5459f1d21 100644 --- a/shaders/mat_default.frag +++ b/shaders/mat_default.frag @@ -29,7 +29,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -42,7 +43,7 @@ void main() glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, 0.0, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); /* float distance = dot(f_pos.xyz, f_pos.xyz); if( distance <= cascade_end.x ) { color.r += 0.25; } diff --git a/shaders/mat_default_detail.frag b/shaders/mat_default_detail.frag index 63d15c7ce..0f8ad7d5a 100644 --- a/shaders/mat_default_detail.frag +++ b/shaders/mat_default_detail.frag @@ -35,7 +35,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -52,7 +53,7 @@ void main() glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_default_specgloss.frag b/shaders/mat_default_specgloss.frag index 254a0cc7f..52d94aec0 100644 --- a/shaders/mat_default_specgloss.frag +++ b/shaders/mat_default_specgloss.frag @@ -32,7 +32,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -46,7 +47,7 @@ void main() metalic = texture(specgloss, f_coord).b; fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); /* float distance = dot(f_pos.xyz, f_pos.xyz); if( distance <= cascade_end.x ) { color.r += 0.25; } diff --git a/shaders/mat_detail_normalmap.frag b/shaders/mat_detail_normalmap.frag index 85f552899..debfe3bab 100644 --- a/shaders/mat_detail_normalmap.frag +++ b/shaders/mat_detail_normalmap.frag @@ -39,7 +39,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; @@ -64,7 +65,7 @@ void main() float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_detail_normalmap_specgloss.frag b/shaders/mat_detail_normalmap_specgloss.frag index a3799ce1e..0fa9ea2ee 100644 --- a/shaders/mat_detail_normalmap_specgloss.frag +++ b/shaders/mat_detail_normalmap_specgloss.frag @@ -42,7 +42,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -72,7 +73,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_detail_parallax.frag b/shaders/mat_detail_parallax.frag index 75919b13f..28de25095 100644 --- a/shaders/mat_detail_parallax.frag +++ b/shaders/mat_detail_parallax.frag @@ -49,7 +49,8 @@ void main() vec4 detailnormal_map = texture(detailnormalmap, f_coord_p * param[2].x); vec4 tex_color = texture(diffuse, f_coord_p); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -72,7 +73,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_detail_parallax_specgloss.frag b/shaders/mat_detail_parallax_specgloss.frag index fcc33ac34..8d1b86457 100644 --- a/shaders/mat_detail_parallax_specgloss.frag +++ b/shaders/mat_detail_parallax_specgloss.frag @@ -55,7 +55,8 @@ void main() vec4 tex_color = texture(diffuse, f_coord_p); vec4 specgloss_map = texture(specgloss, f_coord_p); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; @@ -78,7 +79,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_normalmap.frag b/shaders/mat_normalmap.frag index 3ef505eba..9757324d8 100644 --- a/shaders/mat_normalmap.frag +++ b/shaders/mat_normalmap.frag @@ -34,7 +34,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -51,7 +52,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_normalmap_specgloss.frag b/shaders/mat_normalmap_specgloss.frag index a4b184627..3f043b51a 100644 --- a/shaders/mat_normalmap_specgloss.frag +++ b/shaders/mat_normalmap_specgloss.frag @@ -38,7 +38,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -57,7 +58,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_parallax.frag b/shaders/mat_parallax.frag index 7adac0549..49e8eb2a0 100644 --- a/shaders/mat_parallax.frag +++ b/shaders/mat_parallax.frag @@ -42,7 +42,8 @@ void main() vec4 tex_color = texture(diffuse, f_coord_p); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -59,7 +60,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_parallax_specgloss.frag b/shaders/mat_parallax_specgloss.frag index 8b590fae1..04349ef2c 100644 --- a/shaders/mat_parallax_specgloss.frag +++ b/shaders/mat_parallax_specgloss.frag @@ -46,7 +46,8 @@ void main() vec4 tex_color = texture(diffuse, f_coord_p); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -65,7 +66,7 @@ void main() fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_reflmap.frag b/shaders/mat_reflmap.frag index bd4c4ae79..1ffdd822f 100644 --- a/shaders/mat_reflmap.frag +++ b/shaders/mat_reflmap.frag @@ -32,7 +32,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -49,7 +50,7 @@ void main() if(alphatestfail) fragcolor.r = 1.0; - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; diff --git a/shaders/mat_reflmap_specgloss.frag b/shaders/mat_reflmap_specgloss.frag index 4c89083c7..71ebbac24 100644 --- a/shaders/mat_reflmap_specgloss.frag +++ b/shaders/mat_reflmap_specgloss.frag @@ -36,7 +36,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -54,7 +55,7 @@ void main() if(alphatestfail) fragcolor.r = 1.0; - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; diff --git a/shaders/mat_shadowlessnormalmap.frag b/shaders/mat_shadowlessnormalmap.frag index cb2c040e9..ebf135ba1 100644 --- a/shaders/mat_shadowlessnormalmap.frag +++ b/shaders/mat_shadowlessnormalmap.frag @@ -34,7 +34,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -51,7 +52,7 @@ void main() glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, 1.0); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_shadowlessnormalmap_specgloss.frag b/shaders/mat_shadowlessnormalmap_specgloss.frag index adc473ff6..2bd6d215f 100644 --- a/shaders/mat_shadowlessnormalmap_specgloss.frag +++ b/shaders/mat_shadowlessnormalmap_specgloss.frag @@ -38,7 +38,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -56,7 +57,7 @@ void main() metalic = texture(specgloss, f_coord).b; fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, 1.0); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_sunlessnormalmap.frag b/shaders/mat_sunlessnormalmap.frag index 0b3fc7f67..a5e97d30c 100644 --- a/shaders/mat_sunlessnormalmap.frag +++ b/shaders/mat_sunlessnormalmap.frag @@ -99,7 +99,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -115,7 +116,7 @@ void main() float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; fragcolor = apply_lights_sunless(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/shaders/mat_sunlessnormalmap_specgloss.frag b/shaders/mat_sunlessnormalmap_specgloss.frag index 21cc9f6e9..4e2abe1d9 100644 --- a/shaders/mat_sunlessnormalmap_specgloss.frag +++ b/shaders/mat_sunlessnormalmap_specgloss.frag @@ -113,7 +113,8 @@ void main() { vec4 tex_color = texture(diffuse, f_coord); - bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + float alphacoverage = alpha_coverage(tex_color.a); + bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage); if(alphatestfail) discard; // if (tex_color.a < opacity) @@ -131,7 +132,7 @@ void main() metalic = texture(specgloss, f_coord).b; fragcolor = apply_lights_sunless(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult); #if POSTFX_ENABLED out_color = color; #else diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index ea2177170..d10d555a3 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "world/Event.h" @@ -109,6 +110,8 @@ state_manager::init_scripting_interface() { simulation::Memory.insert( memorycell ); simulation::Region->insert( memorycell ); } + // the cell a test scenery reports its result to + simulation::test().init_result_cell(); } // legacy method, calculates changes in simulation state over specified time diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index bdc4b0598..11e28b61f 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -68,15 +68,15 @@ world_environment::compute_weather() const { Global.AirTemperature > 1 ? "rain:" : "snow:"; - Global.fTurbidity = Global.Overcast <= 0.10 ? 3 : + Global.fTurbidity = Global.Overcast <= 0.10 ? 4 : Global.Overcast <= 0.20 ? 4 : Global.Overcast <= 0.30 ? 5 : Global.Overcast <= 0.40 ? 5 : - Global.Overcast <= 0.50 ? 5 : - Global.Overcast <= 0.60 ? 5 : - Global.Overcast <= 0.70 ? 6 : - Global.Overcast <= 0.80 ? 7 : - Global.Overcast <= 0.90 ? 8 : + Global.Overcast <= 0.50 ? 6 : + Global.Overcast <= 0.60 ? 6 : + Global.Overcast <= 0.70 ? 7 : + Global.Overcast <= 0.80 ? 8 : + Global.Overcast <= 0.90 ? 9 : 9; } diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 664f3b955..244700070 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationsounds.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" #include "scene/scenenodegroups.h" #include "scene/scenelayers.h" #include "scene/sceneterrain.h" @@ -363,6 +364,10 @@ state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scrat // config parameters (re)definition Global.ConfigParse( Input ); + if( Global.test.enabled ) { + // a scenery doesn't get to turn on what a test keeps off + simulation::apply_test_mode_settings(); + } } void diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp new file mode 100644 index 000000000..89a8a1046 --- /dev/null +++ b/simulation/simulationtest.cpp @@ -0,0 +1,270 @@ +/* +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/simulationtest.h" + +#include "application/application.h" +#include "scene/scene.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#ifdef _WIN32 +#include "Console.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +bool is_moving(TDynamicObject const *Vehicle) +{ + return std::abs(Vehicle->GetVelocity()) > 0.01; +} + +// [s] of real time since the start of the simulator +double elapsed_wall_time() +{ + return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); +} + +} // namespace + +namespace simulation { + +test_manager &test() +{ + static test_manager instance; + return instance; +} + +void apply_test_mode_settings() +{ + // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way + Global.editor_session = false; + Global.local_start_vehicle = "ghostview"; + Global.GfxRenderer = "null"; + Global.NvRenderer = false; + Global.bSoundEnabled = false; + Global.python_enabled = false; + Global.bInactivePause = false; + Global.bFullScreen = false; + Global.fullscreen_windowed = false; + Global.VSync = false; + Global.iMultisampling = 0; + Global.gfx_usegles = false; + Global.minframetime = std::chrono::duration(0.0f); + Global.extra_viewports.clear(); + Global.headtrack_conf.joy.clear(); + // a test runs on its own: no network, and no input from outside (eu07/maszyna#541) + Global.network_servers.clear(); + Global.network_client.reset(); + Global.InputGamepad = false; + Global.InputMouse = false; + Global.uart_conf.enable = false; + Global.motiontelemetry_conf.enable = false; +#ifdef WITH_ZMQ + Global.zmq_address.clear(); +#endif + // nor anything to the outside: no keyboard leds, LPT or PoKeys desk (feedbackmode), no messages to a + // multiplayer server (multiplayer, which also holds some events back for it), no program run at the end + Global.iFeedbackMode = 0; +#ifdef _WIN32 + Console::ModeSet(Global.iFeedbackMode, Global.iFeedbackPort); +#endif + Global.iMultiplayer = 0; + Global.exec_on_exit.clear(); + // and the same way every time, unless given another seed (-seed, or randomseed in the settings) + if (!Global.random_seed) + Global.random_seed = seed_of("test"); + // the real time limit, which the scenery may set too + test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout)); +} + +void test_manager::init_result_cell() const +{ + auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) }; + // neither of the reported values, so that a cell nobody wrote to says nothing + cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2); + simulation::Region->insert(cell.get()); + // the table owns its cells + simulation::Memory.insert(cell.release()); +} + +void test_manager::start() +{ + if (m_started) + return; + m_started = true; + { + std::scoped_lock lock { m_lock }; + m_progress = test_progress {}; + } + if (simulation::Vehicles.sequence().empty()) + { + // most likely the scenery wasn't found, or it isn't a test scenery + finish(test_result::error, "the scenery has no vehicles"); + return; + } + for (auto const &name : Global.test.vehicles) + { + if (simulation::Vehicles.find(name) == nullptr) + { + finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); + return; + } + } + // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key + Global.iPause = 0; + auto tested { std::string("every vehicle") }; + if (false == Global.test.vehicles.empty()) + { + tested = "the consists of"; + for (auto const &name : Global.test.vehicles) + tested += " " + name; + } + auto const walllimit { m_walllimit.load() }; + WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}", tested, Global.test.timeout, + walllimit > 0.0 ? std::format("{:.0f} s", walllimit) : std::string("none"), Global.test.standstill, + Global.test.pass_on_standstill ? ", standstill passes" : "", + Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed", + Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop")); +} + +void test_manager::update(double const Deltatime) +{ + if (false == m_started || m_finished) + return; + + test_frame frame { Deltatime, std::nullopt, {}, tested_trains_at_rest() }; + if (auto const *cell = simulation::Memory.find(std::string(result_cell))) + { + frame.reported = cell->Value1(); + frame.reason = cell->Text(); + } + + auto const limits { test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass } }; + std::optional verdict; + auto passrequested { false }; + { + std::scoped_lock lock { m_lock }; + auto const requestedbefore { m_progress.passrequested }; + verdict = evaluate_frame(m_progress, frame, limits); + passrequested = m_progress.passrequested && false == requestedbefore; + } + if (verdict.has_value()) + { + finish(verdict->result, verdict->reason); + return; + } + if (passrequested) + { + WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for the tested trains to stop", m_progress.time, + frame.reason.empty() ? std::string() : std::format(" ({})", frame.reason))); + } +} + +bool test_manager::tested_trains_at_rest() const +{ + if (Global.test.vehicles.empty()) + return std::ranges::none_of(simulation::Vehicles.sequence(), is_moving); + // the consists as they are now: a train the tested one couples to joins it, one it leaves behind doesn't + return std::ranges::none_of(Global.test.vehicles, [](std::string const &Name) { + auto *vehicle { simulation::Vehicles.find(Name) }; + return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, is_moving) != nullptr; + }); +} + +void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal) +{ + auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) }; + if (false == Global.test.enabled) + { + WriteLog(reason, logtype::generic); + return; + } + if (false == Global.test.fail_if_stop_overran) + { + WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_progress.time)); + return; + } + finish(test_result::signal_passed_at_danger, reason); +} + +void test_manager::finish(test_result const Result, std::string_view const Reason) +{ + if (conclude(Result, Reason)) + Application.queue_quit(true); +} + +bool test_manager::conclude(test_result const Result, std::string_view const Reason) +{ + std::scoped_lock lock { m_lock }; + if (m_finished || false == Global.test.enabled) + return false; + m_result = Result; + m_finished = true; + + auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, Reason) }; + if (Result == test_result::pass) + WriteLog(line); + else + ErrorLog(line); + // the process has no console of its own; whoever started it with a redirected output gets the verdict there too + std::fprintf(stdout, "%s\n", line.c_str()); + std::fflush(stdout); + return true; +} + +int test_manager::exit_code() const +{ + std::scoped_lock lock { m_lock }; + return static_cast(m_finished ? m_result : test_result::error); +} + +void test_manager::watch_wall_clock(double const Limit) +{ + m_walllimit = Limit; + if (Limit <= 0.0 || m_watchdog.joinable()) + return; + m_watchdog = std::jthread([this](std::stop_token const &Stop) { + while (false == Stop.stop_requested()) + { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + check_wall_clock(elapsed_wall_time()); + } + }); +} + +void test_manager::check_wall_clock(double const Elapsed) +{ + auto const limit { m_walllimit.load() }; + if (limit <= 0.0 || Elapsed < limit) + return; + // the run hangs, or is too slow: it ends here, whatever the main thread is doing. a run whose test has ended + // but which doesn't close ends with its result + if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit))) + ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit)); + // what was logged last gets written, unless the log is held up by a hung thread + StopLogService(); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + std::_Exit(exit_code()); +} + +} // namespace simulation diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h new file mode 100644 index 000000000..784cd39e8 --- /dev/null +++ b/simulation/simulationtest.h @@ -0,0 +1,76 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "simulation/simulationtestrules.h" + +#include +#include +#include +#include + +// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight +// fixed-step loop and the simulator quits with an exit code saying how the test went +namespace simulation { + +class test_manager { + +public: + // name of the memory cell a scenery reports its result to + static constexpr std::string_view result_cell { "__test.result" }; + // fixed simulation time step of one frame in test mode [s]: 3 physics steps of 10 ms + static constexpr double frame_step { 0.03 }; + + // creates the result cell; called with the other scripting interface cells, before the scenery is read + void init_result_cell() const; + // the simulation is ready: start the clocks + void start(); + // checks the end conditions after a simulation frame of Deltatime seconds + void update(double Deltatime); + // reported by a driver whose train went past a signal showing stop + void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal); + // ends the test with given result and closes the application; the first call wins + void finish(test_result Result, std::string_view Reason); + // ends the test with given result, without closing the application: for the ways out that close it anyway + // (a bad command line, a failed start, an exception). returns false if the test had already ended + bool conclude(test_result Result, std::string_view Reason); + // (re)sets the real time limit of the run [s] since the start of the simulator, 0 = none. the first limit + // starts the watchdog, which ends a run still going at the limit with the timeout code, whatever it's doing + void watch_wall_clock(double Limit); + + bool finished() const { return m_finished; } + // exit code of the process: the result, or error while the test hasn't finished + int exit_code() const; + +private: + // the watchdog's check, at Elapsed seconds of real time since the start of the simulator + void check_wall_clock(double Elapsed); + // every vehicle of the tested trains stands: the consists of test.vehicle, or every vehicle without it + bool tested_trains_at_rest() const; + + // the watchdog may end the test from its own thread + mutable std::mutex m_lock; + bool m_started { false }; + std::atomic m_finished { false }; + test_result m_result { test_result::error }; + test_progress m_progress; + std::atomic m_walllimit { 0.0 }; // [s] since the start of the simulator, 0 = none + std::jthread m_watchdog; +}; + +// the test of the run +test_manager &test(); + +// the settings of the test mode, over whatever the settings files and the scenery say: applied once the command +// line is read, and again after each config block of the scenery, which could turn the sound, the network or the +// program run at the end back on +void apply_test_mode_settings(); + +} // namespace simulation diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp new file mode 100644 index 000000000..fcedaed7d --- /dev/null +++ b/simulation/simulationtestrules.cpp @@ -0,0 +1,162 @@ +/* +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/simulationtestrules.h" + +#include +#include +#include + +namespace { + +// the cell holds what the scenery wrote, so the values are whole numbers; the margin only keeps a stray fraction out +bool holds(double const Value, double const Expected) +{ + return std::abs(Value - Expected) < 1e-6; +} + +// the text of the result cell, as said after the result +std::string reason_suffix(std::string_view const Reason) +{ + return Reason.empty() ? std::string() : std::format(" ({})", Reason); +} + +// options of the simulator which take a value, see eu07_application::init_settings() +bool takes_value(std::string_view const Option) +{ + return Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini"; +} + +// a number of seconds given to Option, at Index of Arguments; the index is moved past the value +std::optional option_seconds(std::span const Arguments, std::size_t &Index) +{ + if (Index + 1 >= Arguments.size()) + return std::nullopt; + ++Index; + return simulation::parse_seconds(Arguments[Index]); +} + +} // namespace + +namespace simulation { + +std::string_view to_string(test_result const Result) +{ + using enum test_result; + switch (Result) + { + case pass: return "pass"; + case fail: return "fail"; + case signal_passed_at_danger: return "signal passed at danger"; + case timeout: return "timeout"; + case standstill: return "standstill"; + case error: return "error"; + } + return "unknown"; +} + +std::optional parse_seconds(std::string_view const Text) +{ + auto const *const last{Text.data() + Text.size()}; + double value{0.0}; + if (auto const [parsed, status]{std::from_chars(Text.data(), last, value)}; status != std::errc{} || parsed != last || false == std::isfinite(value) || value < 0.0) + return std::nullopt; + return value; +} + +test_command_line parse_test_command_line(std::span const Arguments) +{ + test_command_line result; + for (std::size_t i = 1; i < Arguments.size(); ++i) + { + std::string_view const option{Arguments[i]}; + if (option == "--test") + { + result.enabled = true; + } + else if (option == "--test-timeout" || option == "--test-wall-timeout") + { + auto const seconds{option_seconds(Arguments, i)}; + if (false == seconds.has_value()) + { + // a typo would otherwise turn the limit off + if (result.error.empty()) + result.error = std::format("{} needs a number of seconds", option); + continue; + } + if (option == "--test-timeout") + result.timeout = seconds; + else + result.wall_timeout = seconds; + } + else if (takes_value(option)) + { + ++i; + } + } + return result; +} + +std::string describe_exception(std::exception_ptr const &Exception) +{ + if (nullptr == Exception) + return "the simulator was terminated"; + try + { + std::rethrow_exception(Exception); + } + catch (std::exception const &Error) + { + return std::format("critical error: {}", Error.what()); + } + catch (...) + { + return "critical error: an exception of unknown type"; + } +} + +double wall_clock_limit(std::optional const Given, double const Simulationtimeout) +{ + if (Given.has_value()) + return *Given; + return Simulationtimeout > 0.0 ? Simulationtimeout + wall_timeout_loading_allowance : 0.0; +} + +std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits) +{ + using enum test_result; + + Progress.time += Frame.deltatime; + + if (Frame.reported.has_value()) + { + auto const value{*Frame.reported}; + if (holds(value, 0.0)) + return test_verdict{fail, std::format("__test.result set to 0{}", reason_suffix(Frame.reason))}; + if (holds(value, 1.0)) + { + if (false == Limits.no_movement_before_pass) + return test_verdict{pass, std::format("__test.result set to 1{}", reason_suffix(Frame.reason))}; + Progress.passrequested = true; + } + } + + Progress.resttime = Frame.atrest ? Progress.resttime + Frame.deltatime : 0.0; + + if (Progress.passrequested && Progress.resttime >= pass_settle_time) + return test_verdict{pass, "__test.result set to 1 and the tested trains stopped"}; + if (Limits.standstill > 0.0 && Progress.resttime >= Limits.standstill) + return test_verdict{Limits.pass_on_standstill ? pass : standstill, std::format("the tested trains stood still for {:.0f} s", Limits.standstill)}; + if (Limits.timeout > 0.0 && Progress.time >= Limits.timeout) + return test_verdict{timeout, std::format("no result after {:.0f} s", Limits.timeout)}; + return std::nullopt; +} + +} // namespace simulation diff --git a/simulation/simulationtestrules.h b/simulation/simulationtestrules.h new file mode 100644 index 000000000..684b90cde --- /dev/null +++ b/simulation/simulationtestrules.h @@ -0,0 +1,98 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// the rules of the test mode (eu07 --test, eu07/maszyna#541) which need nothing of the running simulation: the exit +// codes, the command line, the end conditions and the real time limit. kept apart so the unit tests can check them +namespace simulation { + +// exit codes of a test run; public, scripts and CI read them. none of them is a code a process commonly ends with +// when it goes wrong on its own: 1 (killed with TerminateProcess, or a plain failure of most programs), 3 (abort() +// on Windows), 126-127 (a shell that can't run the program) or 128 + a signal number (killed, on Linux) +enum class test_result : int { + pass = 0, // __test.result set to 1, then the tested trains came to rest (or test.pass_on_standstill) + fail = 10, // __test.result set to 0 + signal_passed_at_danger = 11, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no + timeout = 12, // test.timeout seconds of simulation time, or test.wall_timeout seconds of real time went by + standstill = 13, // the tested trains stood still for test.standstill seconds without a result + error = 14, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw +}; + +std::string_view to_string(test_result Result); + +// how a test ended, and why +struct test_verdict { + test_result result{test_result::error}; + std::string reason; +}; + +// the test mode options of the command line +struct test_command_line { + bool enabled{false}; // --test + std::optional timeout; // --test-timeout + std::optional wall_timeout; // --test-wall-timeout + std::string error; // what's wrong with them; empty if nothing +}; + +// seconds given on the command line: a number, not negative. nothing for anything else +std::optional parse_seconds(std::string_view Text); + +// picks the test mode options out of a command line (the first argument is the program). the values of the other +// options are skipped, so a scenery named like an option isn't taken for one; options it doesn't know are left alone +test_command_line parse_test_command_line(std::span Arguments); + +// what ended a test run that the simulator didn't end itself: the exception caught (or being handled when the +// program was terminated), or nothing +std::string describe_exception(std::exception_ptr const &Exception); + +// time allowed for loading the scenery, on top of the simulation time, when the real time limit isn't given [s] +inline constexpr double wall_timeout_loading_allowance{600.0}; + +// the real time limit of a test run [s], 0 = none: the one given, else the simulation time limit plus time for the +// loading, so a simulation that runs at least as fast as real time is never cut short. no simulation time limit +// (test.timeout 0) means none in real time either, unless given +double wall_clock_limit(std::optional Given, double Simulationtimeout); + +// the limits and switches the end conditions go by +struct test_limits { + double timeout{3600.0}; // [s] of simulation time; 0 = never + double standstill{300.0}; // [s] of the tested trains standing without a result; 0 = never + bool pass_on_standstill{false}; + bool no_movement_before_pass{true}; +}; + +// what a frame of the simulation brought +struct test_frame { + double deltatime{0.0}; // [s] of simulation time + std::optional reported; // value of the result cell, if there is one + std::string_view reason; // text of the result cell + bool atrest{false}; // every vehicle of the tested trains stands (test.vehicle; every vehicle without it) +}; + +// the state of a test between frames +struct test_progress { + double time{0.0}; // simulation time since the start [s] + double resttime{0.0}; // how long the tested trains have been standing [s] + bool passrequested{false}; // __test.result was set to 1, the pass waits for the tested trains to stop +}; + +// how long the tested trains have to stand before a requested pass is granted [s] +inline constexpr double pass_settle_time{1.0}; + +// checks the end conditions after a frame and moves the progress on. returns the verdict once the test is over +std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits); + +} // namespace simulation diff --git a/staticFiles/python/local/abstractscreenrenderer.py b/staticFiles/python/local/abstractscreenrenderer.py index ea8be2c56..3ebf20813 100644 --- a/staticFiles/python/local/abstractscreenrenderer.py +++ b/staticFiles/python/local/abstractscreenrenderer.py @@ -1,7 +1,25 @@ -from PIL import Image +from PIL import Image, ImageDraw, ImageFont from math import ceil, floor, cos, sin, radians import os +# Pillow 10 removed ImageFont.getsize(), ImageDraw.textsize() and Image.ANTIALIAS, which the screen scripts use; for +# Python 3.14 only a newer Pillow is available, so they are put back, on top of getbbox() / textbbox() and LANCZOS +def _font_getsize(self, text, *args, **kwargs): + box = self.getbbox(text, *args, **kwargs) + return (box[2], box[3]) + +def _draw_textsize(self, text, font=None, *args, **kwargs): + box = self.textbbox((0, 0), text, font, *args, **kwargs) + return (box[2], box[3]) + +for _fontclass in (ImageFont.FreeTypeFont, ImageFont.ImageFont, getattr(ImageFont, 'TransposedFont', None)): + if _fontclass is not None and not hasattr(_fontclass, 'getsize') and hasattr(_fontclass, 'getbbox'): + _fontclass.getsize = _font_getsize +if not hasattr(ImageDraw.ImageDraw, 'textsize'): + ImageDraw.ImageDraw.textsize = _draw_textsize +if not hasattr(Image, 'ANTIALIAS'): + Image.ANTIALIAS = Image.LANCZOS + class abstractscreenrenderer(): def __init__(self, lookup_path): self.width = 0 diff --git a/stdafx.h b/stdafx.h index f2b377196..164edc240 100644 --- a/stdafx.h +++ b/stdafx.h @@ -91,7 +91,7 @@ #if defined(__aarch64__) || defined(__arm64__) #define GLM_FORCE_NEON -#else +#elif defined(__AVX2__) // set by /arch:AVX2 or -mavx2 (ENABLE_AVX2); without it GLM falls back to SSE2 #define GLM_FORCE_AVX2 #endif #define GLM_FORCE_SWIZZLE diff --git a/tests/scenarios/.gitignore b/tests/scenarios/.gitignore new file mode 100644 index 000000000..ea93687fe --- /dev/null +++ b/tests/scenarios/.gitignore @@ -0,0 +1,2 @@ +out/ +__pycache__/ diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md new file mode 100644 index 000000000..0a11c6a0a --- /dev/null +++ b/tests/scenarios/README.md @@ -0,0 +1,249 @@ +# Scenario tests + +End-to-end checks that run the real simulator on a scenery and look at how the run ended +and what a vehicle did: did it start, did it keep to the speed limit, did it brake and stop, +did it pass a signal at stop. + +Scenery and vehicle data are not in this repo, so these run against a local game install +only, not in CI. + +## The simulator's test mode + +The runner drives the simulator's test mode (eu07/maszyna#541), which works without the +runner too and is meant for scenery authors as well: + +``` +eu07 --test -s [--test-timeout ] [--test-wall-timeout ] [-seed ] [-ini ] +``` + +With `--test` the simulator: + +- needs `-s`; `-v` is ignored and every train is driven by AI (ghostview), +- reads the settings of the game folder's `eu07.ini` and of the files given with `-ini` (in that + order), not the player's own `eu07.ini` in `%APPDATA%\MaSzyna` (`~/.config/MaSzyna` on Linux), + so a test runs the same for whoever runs it, +- draws nothing: the null renderer loads the 3D models (the physics needs some of their + data) but no textures, and the window stays hidden, +- has no sound, no network, no python, no pause (not even one set by the scenery), and + no crash dialog, +- takes no input from outside: keys and mouse sent to its window, gamepad, UART (a cab + desk), ZeroMQ and commands sent by other programs (`WM_COPYDATA`) are all ignored, and + motion telemetry is off, +- gives nothing to the outside either: no keyboard leds, LPT or PoKeys (`feedbackmode`), no + messages to a multiplayer server (`multiplayer`), no program run at the end (`execonexit`), + no console window of its own (`showsystemconsole`), no Discord presence, and the game's `imgui.ini` + stays as it is, +- keeps all of the above whatever the `config` block of the scenery says: the settings of the + test mode are applied again after it, +- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per + frame (three 10 ms physics steps), whatever the real time, the time speed or the machine, +- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two + runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal), +- quits when the test ends, and says how it ended in the exit code and in a `test: ...` + line on stdout and in the log. A command line it can't take, a start that fails, or an + exception thrown by the simulator (of any type, on Linux too) ends the same way, with the + `error` code. That line is all there is on stdout: the log goes to + the log file only (`debuglog` doesn't print it on the console in test mode). + +On Windows the simulator is a windowed program, which the `cmd` prompt and PowerShell don't wait +for. In a `.bat` file `eu07 --test ... > result.txt` waits and sets `%errorlevel%`; at the prompt +`start /wait eu07 --test ...` waits too but doesn't pass the output on. In PowerShell use +`(Start-Process eu07 '--test ...' -Wait -PassThru -RedirectStandardOutput result.txt).ExitCode`. +Scripts (Python's `subprocess`, bash) wait for it as for any other program. + +A scenery reports its result to the memory cell `__test.result`, which the simulator creates +(in every run, so a test scenery loads normally too). Write value 1 to it for a pass and 0 +for a failure, with an `UpdateValues` event; other values are ignored, and the text, if +given, goes to the log as the reason: + +``` +event test_pass UpdateValues 0 __test.result reached_the_stop 1 * endevent +event test_fail UpdateValues 0 __test.result wrong_track 0 * endevent +``` + +(`PutValues` isn't the event for it: it hands a command to a vehicle, it doesn't write a cell.) +A good place for the pass event is `event0` of a track the train should stop on: it runs +while a train stands there, and the length of the track is the margin of the stop. + +The test ends with the first of these: + +| exit code | result | when | +| --- | --- | --- | +| 0 | pass | `__test.result` was set to 1 and then the tested trains stood still for 1 s, so a train still moving towards a signal at stop has to stop first (with `test.no_movement_before_pass no` the pass ends the test at once). Also the standstill end with `test.pass_on_standstill yes` | +| 10 | fail | `__test.result` was set to 0; ends at once | +| 11 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` | +| 12 | timeout | `test.timeout` seconds of simulation time went by (default 3600), or `test.wall_timeout` seconds of real time since the start (see below) | +| 13 | standstill | the tested trains stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits | +| 14 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw | + +A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819). The +codes of the test mode keep clear of the ones a process gets when it goes wrong on its own: 1 +(killed with `TerminateProcess`, or a plain failure of most programs), 3 (`abort()` on Windows), +126-127 (a shell that can't run the program) and 128 + a signal number (killed, on Linux). + +The limits go in a `config` block of the scenery: + +``` +config +test.timeout 600 +test.wall_timeout 900 +test.standstill 120 +test.pass_on_standstill no +test.fail_if_stop_overran yes +test.no_movement_before_pass yes +test.vehicle ep07-424 +endconfig +``` + +| key | default | meaning | +| --- | --- | --- | +| `test.timeout` | 3600 | seconds of simulation time before the test ends as `timeout`; 0 = never | +| `test.wall_timeout` | `test.timeout` + 600 | seconds of real time since the start before the test ends as `timeout`; 0 = never | +| `test.standstill` | 300 | seconds with the tested trains still and no result before the test ends as `standstill`; 0 = never | +| `test.pass_on_standstill` | no | the standstill end passes the test instead | +| `test.fail_if_stop_overran` | yes | a signal passed at danger ends the test; with `no` it's only logged | +| `test.no_movement_before_pass` | yes | a pass waits until the tested trains stand still; with `no` it ends the test at once | +| `test.vehicle` | none | a vehicle of a train under test, by its name in the scenery (once for each train under test). The tested trains are the consists of these vehicles as they are at the moment (a train the tested one couples to joins it), and only they count for the pass and the standstill: other trains, AI traffic, may run on. A name the scenery doesn't have ends the test with `error`. Not given, every vehicle of the scenery counts. A signal passed at danger counts for every train either way | + +`--test-timeout` and `--test-wall-timeout` on the command line win over `test.timeout` and +`test.wall_timeout` of the scenery and the settings files. + +`test.wall_timeout` is a watchdog in real time, for a run that hangs or crawls: when the +simulator still runs that many seconds after its start, loading included, it says `test: timeout` +and quits with the timeout code, whatever it is doing at the moment, with no dialog. Not given, +it is `test.timeout` + 600 s: ten minutes for the loading, and a simulation that runs at least as +fast as real time is never cut short by it. With `test.timeout 0` there is no watchdog unless +`test.wall_timeout` is given; `test.wall_timeout 0` turns it off. A test that has ended but whose +simulator doesn't close is ended by the watchdog too, with its own result. + +A signal is passed at danger when the head of a train goes past a signal which its driver +has in its speed table, showing stop. So it's the driver's view that counts: a train without +a driver isn't watched, and neither is a signal the driver never scanned (a train placed at +100 km/h 150 m before a signal at stop got past it before its AI first looked ahead; at +60 km/h it was caught). Outside the test mode the same is written to the log, nothing more. + +## Running + +``` +python tests/scenarios/run.py --game-dir "C:/Steam/steamapps/common/MaSzyna" -j 4 +``` + +Python 3.10+, no extra packages. Options: + +- `EU07_GAME_DIR` can replace `--game-dir`. +- `--exe path/to/eu07.exe` picks the build to test; the default is the newest + `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command + line options. +- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. +- `-j N` runs N cases at once. Each case prints its results when it is done. All 17 cases + take about 30 s with `-j 4`, loading included. +- `--watch` runs a case the old way, in a visible window in real time (or faster with + `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For + watching what a case does. + +Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`, +`stdout.txt`, the physicslogs of the vehicle and of other trains of the case) are moved to +`tests/scenarios/out//`. + +## How it works + +For each case the runner: + +1. writes `scenery/autotest_.scn` into the game dir: the base scenery with its own + trainsets removed, the start time changed if the case says so, the case's track events + added, and the case's `.scn` fragment added: its trainsets after `FirstInit`, everything + else (the case's `test_config`, event launchers standing in for keys the scenery expects a + player to press, extra events) before it, +2. starts the simulator with `--test -s autotest_.scn -ini out//autotest.ini + --test-wall-timeout `, plus `--test-timeout ` when the case gives a + `duration`; the extra ini turns on + `physicslog` and writes the logs to `logs/log (autotest_) .txt` rather than the + shared `log.txt` (`multiplelogs`), +3. waits until the simulator quits by itself. It gives up early when the log reports + `Bad vehicle` / `Bad trainset`, or when the scenario has loaded and no physicslog appeared. + After the case's `timeout` of wall-clock time the simulator ends itself with the timeout code; + one that doesn't is killed 30 s later, +4. compares the result from the exit code with the case's `expect`, then runs the checks on + the physicslog. + +The lead vehicle is named `autotest_`, so every case has its own physicslog and log +files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt` +geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base +scenery is newer, and after a run cut short (`wall_timeout`, `error`, a crash, or killed by run.py), +which could have been writing it. + +## Writing a case + +`cases/.json`: + +| key | meaning | +| --- | --- | +| `base_scenery` | scenery file in the game's `scenery/` dir | +| `strip_trainsets` | drop the base scenery's trainsets (default `true`) | +| `time` | replace the scenery start time, `HH:MM` | +| `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail | +| `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes | +| `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]`; the block always has `test.vehicle` with the case's lead vehicle, so only its train counts for the pass and the standstill | +| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) | +| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | +| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | +| `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | +| `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | +| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) | +| `checks` | list of checks, below | + +`{{vehicle}}` is always set, also inside `vars` values: the node name of the lead vehicle, +the one whose physicslog is checked, and the train under test (`test.vehicle`). Other vehicles +of the consist take names made from it, e.g. `{{vehicle}}_s`; another train with a driver is named +`_{{vehicle}}`, so its physicslog is moved out of the game dir too. The td.scn cases share two fragments, `td_timetable.scn` (route set, +train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ +only in `vars.consist`. Przystanek is a technical stop in that timetable (`pt`), where the AI +doesn't wait for the departure time: it sets off as soon as it counts the train as standing at +the W4, which is below 1 km/h, so the train stands there for a few seconds at most, or doesn't +quite stop (since the AI braking of #264 the SN61 turns back at 0.4 km/h). The +timetable cases therefore check that the train comes down to 1 km/h, with no hold, 1380-1420 m +from the start (each of the seven trains stops at 1397-1401 m). `td_red_signal_moving.scn` is the red signal one with the train +starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking +and slides past the signal, so those cases set `test.fail_if_stop_overran no`. +`td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0` +on `tor1k`, the track in front of the signal. + +The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass +event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from +`test.timeout`), `test_mode_standstill` (exit 13, from `test.standstill`) and +`test_mode_wall_timeout` (exit 12 from the real time watchdog, which ends it while it loads). +`test_mode_standstill_traffic` (fragment `td_traffic.scn`) has a train under test standing on +track 2 of Stacja1 and AI traffic, `traffic_{{vehicle}}`, leaving track 1 on the timetable: the +standstill of 100 s ends the test although the traffic runs on (counting every vehicle, it runs +into the test timeout). +`test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto +it, with `test.no_movement_before_pass no`, so the test ends with the train still moving. + +Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use +the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are +locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of +the row instead, logged by builds from this branch on. + +- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds. +- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`. +- `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar + (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0). +- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`: after + reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the distances, + that stop has to be between them (metres travelled, as in `distance`). +- `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes + above `stop_speed` again. +- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the + distance comes from integrating the speed; on td.scn every vehicle's first stop after + Stacja1 came out at 1400 m (+-4), and the red signal stop at 140 m. +- `slips` `within`: the lead vehicle's wheels slip or lock at some point (within `within` + seconds if given), so a slippery rail case does what it's meant to. +- `slip_clears` `moving_speed`, `stop_speed`, `within` (*vehicle speed*): once stopped after + moving off, the wheels stop slipping within `within` seconds. +- `holds_still` `moving_speed`, `stop_speed`, `max_distance` (*vehicle speed*): once stopped + after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels. +- `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g. + the test ended without waiting for the train to stop. + +New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's +parameters and returns `(passed, detail)`. diff --git a/tests/scenarios/cases/en57_td_timetable.json b/tests/scenarios/cases/en57_td_timetable.json new file mode 100644 index 000000000..d4c4f26fa --- /dev/null +++ b/tests/scenarios/cases/en57_td_timetable.json @@ -0,0 +1,21 @@ +{ + "description": "EN57 EMU (three cars) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/ep09_td_timetable.json b/tests/scenarios/cases/ep09_td_timetable.json new file mode 100644 index 000000000..851b4dbfe --- /dev/null +++ b/tests/scenarios/cases/ep09_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "EP09 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\ep09_v1 104e-005 104e_3 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/et22_td_timetable.json b/tests/scenarios/cases/et22_td_timetable.json new file mode 100644 index 000000000..47622c622 --- /dev/null +++ b/tests/scenarios/cases/et22_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "ET22 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_slippery_push_red_signal.json b/tests/scenarios/cases/eu07_slippery_push_red_signal.json new file mode 100644 index 000000000..64d6ba884 --- /dev/null +++ b/tests/scenarios/cases/eu07_slippery_push_red_signal.json @@ -0,0 +1,39 @@ +{ + "description": "EU07 pushing three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids. Pushed by the train it doesn't roll back at the stop, so it used to stay skidding on locked wheels with the brakes capped by the sliding adhesion and creep (eu07/maszyna#479).", + "base_scenery": "td.scn", + "time": "10:34", + "track_friction": 0.03, + "fragment": "td_red_signal_moving.scn", + "test_config": [ + "test.fail_if_stop_overran no" + ], + "vars": { + "velocity": "30", + "consist": [ + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 900, + "checks": [ + { + "type": "slips", + "within": 60 + }, + { + "type": "slip_clears", + "moving_speed": 5, + "stop_speed": 0.05, + "within": 5 + }, + { + "type": "holds_still", + "moving_speed": 5, + "stop_speed": 0.05, + "max_distance": 0.01 + } + ] +} diff --git a/tests/scenarios/cases/eu07_slippery_red_signal.json b/tests/scenarios/cases/eu07_slippery_red_signal.json new file mode 100644 index 000000000..c2f60f22d --- /dev/null +++ b/tests/scenarios/cases/eu07_slippery_red_signal.json @@ -0,0 +1,39 @@ +{ + "description": "EU07 with three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids, then the skid ends and the train holds still.", + "base_scenery": "td.scn", + "time": "10:34", + "track_friction": 0.03, + "fragment": "td_red_signal_moving.scn", + "test_config": [ + "test.fail_if_stop_overran no" + ], + "vars": { + "velocity": "30", + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 900, + "checks": [ + { + "type": "slips", + "within": 60 + }, + { + "type": "slip_clears", + "moving_speed": 5, + "stop_speed": 0.05, + "within": 5 + }, + { + "type": "holds_still", + "moving_speed": 5, + "stop_speed": 0.05, + "max_distance": 0.01 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_red_signal.json b/tests/scenarios/cases/eu07_td_red_signal.json new file mode 100644 index 000000000..b02acdc81 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_red_signal.json @@ -0,0 +1,18 @@ +{ + "description": "EU07 on td.scn with no route set: pulls off, stops before the exit signal stacja1_j at stop, and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 5, "within": 150 }, + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json new file mode 100644 index 000000000..3774242cd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "EU07 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/sm42_td_timetable.json b/tests/scenarios/cases/sm42_td_timetable.json new file mode 100644 index 000000000..994f94c0e --- /dev/null +++ b/tests/scenarios/cases/sm42_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "SM42 diesel shunter on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json new file mode 100644 index 000000000..1a03c31f8 --- /dev/null +++ b/tests/scenarios/cases/sn61_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "SN61 diesel railcar on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/td_red_signal.scn b/tests/scenarios/cases/td_red_signal.scn new file mode 100644 index 000000000..981707085 --- /dev/null +++ b/tests/scenarios/cases/td_red_signal.scn @@ -0,0 +1,6 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// same start as td_timetable.scn, but nobody sets the route: the exit signal stacja1_j, +// about 150 m ahead of the train, stays at stop. +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_red_signal_moving.scn b/tests/scenarios/cases/td_red_signal_moving.scn new file mode 100644 index 000000000..648e5d90a --- /dev/null +++ b/tests/scenarios/cases/td_red_signal_moving.scn @@ -0,0 +1,6 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop), +// but the train starts already moving at {{velocity}} km/h, so it has to brake right away. +trainset td/rozklad tdo_n1734 0.0 {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_red_signal_pass.scn b/tests/scenarios/cases/td_red_signal_pass.scn new file mode 100644 index 000000000..724050322 --- /dev/null +++ b/tests/scenarios/cases/td_red_signal_pass.scn @@ -0,0 +1,8 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop), +// with the test mode's pass event: the case puts it as event0 on tor1k, the track in front of +// the signal, so it runs once the train stands there. the test passes when every vehicle stopped. +event test_pass UpdateValues 0 __test.result stopped_before_stacja1_j 1 * endevent +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_timetable.scn b/tests/scenarios/cases/td_timetable.scn new file mode 100644 index 000000000..e67dcf9ad --- /dev/null +++ b/tests/scenarios/cases/td_timetable.scn @@ -0,0 +1,12 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// the trainset goes after FirstInit, the launcher before it. +// the case's consist stands where td.scn keeps its timetable train (track 1 of Stacja1) +// and gets the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2. +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +// td.scn sets routes from the keyboard (shift+1..4 run events keyctrl01..04). keyctrl04 is the +// way out of track 1: switch zwr02 and the exit signal stacja1_j at 40. +// a launcher with a positive time fires once at that hour (HHMM), radius -1 means anywhere. +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_traffic.scn b/tests/scenarios/cases/td_traffic.scn new file mode 100644 index 000000000..49720a0b5 --- /dev/null +++ b/tests/scenarios/cases/td_traffic.scn @@ -0,0 +1,13 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: two trains at Stacja1. +// the train under test (test.vehicle) stands on track 2, where its driver has nothing to do; the other one, +// AI traffic, has the td/rozklad timetable on track 1 and leaves for Przystanek at 10:35. the standstill of +// the test waits for the train under test only, so the traffic running on doesn't hold it up. +trainset none tor2k 30.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset +trainset td/rozklad tdo_n1734 0.0 0.1 +node -1 0 traffic_{{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +// the way out of track 1 for the traffic, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/test_mode_pass.json b/tests/scenarios/cases/test_mode_pass.json new file mode 100644 index 000000000..686b7d160 --- /dev/null +++ b/tests/scenarios/cases/test_mode_pass.json @@ -0,0 +1,31 @@ +{ + "description": "Test mode, pass: EU07 on td.scn with no route set stops before the exit signal stacja1_j; event0 of the track there reports the pass, and the test ends as passed once the train stands.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal_pass.scn", + "track_events": { + "tor1k": "event0 test_pass" + }, + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 5, + "within": 150 + }, + { + "type": "stops", + "moving_speed": 5, + "stop_speed": 0.5, + "hold": 0.5 + }, + { + "type": "distance", + "max": 150 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_pass_while_moving.json b/tests/scenarios/cases/test_mode_pass_while_moving.json new file mode 100644 index 000000000..cdf798f16 --- /dev/null +++ b/tests/scenarios/cases/test_mode_pass_while_moving.json @@ -0,0 +1,28 @@ +{ + "description": "Test mode, pass without waiting for a stop: like test_mode_pass, but event2 of the track in front of the exit signal reports the pass as the train runs onto it, and with test.no_movement_before_pass no the test ends at once, the train still moving.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal_pass.scn", + "track_events": { + "tor1k": "event2 test_pass" + }, + "test_config": [ + "test.no_movement_before_pass no" + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 5, + "within": 150 + }, + { + "type": "ends_moving", + "min_speed": 3 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_signal_passed_at_danger.json b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json new file mode 100644 index 000000000..338e7e6ea --- /dev/null +++ b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json @@ -0,0 +1,22 @@ +{ + "description": "Test mode, signal passed at danger: EU07 on td.scn with no route set starts at 60 km/h about 150 m before the exit signal stacja1_j at stop. Its AI driver is still preparing the engine and doesn't brake, and the run ends when the train passes the signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal_moving.scn", + "vars": { + "velocity": "60", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "signal_passed_at_danger", + "timeout": 600, + "checks": [ + { + "type": "max_speed", + "limit": 61 + }, + { + "type": "distance", + "min": 140 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_standstill.json b/tests/scenarios/cases/test_mode_standstill.json new file mode 100644 index 000000000..4dd891cf0 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standstill.json @@ -0,0 +1,26 @@ +{ + "description": "Test mode, standstill: EU07 on td.scn with no route set stops before the exit signal stacja1_j at stop and stays; nothing reports a result, so the test ends once the train under test stood still for test.standstill 120 seconds (the train waits about 70 s before it pulls off, so less would end it before the start).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal.scn", + "test_config": [ + "test.standstill 120" + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "standstill", + "timeout": 600, + "checks": [ + { + "type": "stops", + "moving_speed": 5, + "stop_speed": 0.5, + "hold": 5 + }, + { + "type": "distance", + "max": 150 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_standstill_traffic.json b/tests/scenarios/cases/test_mode_standstill_traffic.json new file mode 100644 index 000000000..8b545e2a5 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standstill_traffic.json @@ -0,0 +1,18 @@ +{ + "description": "Test mode, standstill with traffic: an EU07 stands on track 2 of Stacja1 on td.scn while another EU07, AI traffic, leaves track 1 on the td/rozklad timetable at 10:35 and runs on. Only the train under test (test.vehicle, the case's vehicle) counts, so the test ends on test.standstill 100 although the traffic is moving; counting every vehicle, it would run into the 300 s test timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_traffic.scn", + "test_config": [ + "test.standstill 100" + ], + "expect": "standstill", + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "max_speed", + "limit": 0.5 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_timeout.json b/tests/scenarios/cases/test_mode_timeout.json new file mode 100644 index 000000000..46899e89c --- /dev/null +++ b/tests/scenarios/cases/test_mode_timeout.json @@ -0,0 +1,21 @@ +{ + "description": "Test mode, timeout: EU07 on td.scn with no route set pulls off towards the exit signal stacja1_j at stop; nothing reports a result and test.timeout 90 from the scenery's config block runs out first.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal.scn", + "test_config": [ + "test.timeout 90" + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "timeout", + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 5, + "within": 90 + } + ] +} diff --git a/tests/scenarios/cases/test_mode_wall_timeout.json b/tests/scenarios/cases/test_mode_wall_timeout.json new file mode 100644 index 000000000..078ccca93 --- /dev/null +++ b/tests/scenarios/cases/test_mode_wall_timeout.json @@ -0,0 +1,11 @@ +{ + "description": "Test mode, real time limit: EU07 on td.scn, with a limit of 2 s of real time (the case's timeout, which the runner passes as --test-wall-timeout). The scenery takes longer to load, so the simulator's watchdog ends the run while it loads, with the timeout code and a verdict saying it was the real time.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_red_signal.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "expect": "wall_timeout", + "timeout": 2 +} diff --git a/tests/scenarios/cases/vectron_td_timetable.json b/tests/scenarios/cases/vectron_td_timetable.json new file mode 100644 index 000000000..04656a00f --- /dev/null +++ b/tests/scenarios/cases/vectron_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "Vectron 1293-107 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py new file mode 100644 index 000000000..18b3e3f2e --- /dev/null +++ b/tests/scenarios/run.py @@ -0,0 +1,640 @@ +#!/usr/bin/env python3 +"""Scenario tests: run the real simulator on a scenery and check what a vehicle did. + +A case (cases/.json) names a base scenery from the game install, a fragment +added to it (usually a trainset with an AI driver), the result the simulator's test +mode should end with, and checks on the vehicle's physics log. The runner: + + 1. builds scenery/autotest_.scn in the game dir: the base scenery with its own + trainsets removed, optionally a different start time, and the case fragment added, + 2. starts eu07 in test mode (--test: every train driven by AI, nothing drawn, fixed + time steps as fast as it can) with that scenery and an extra settings file (-ini) + that turns on physicslog, + 3. waits until the simulator quits by itself and reads the test result from its exit + code: pass, fail, signal passed at danger, timeout (after `duration` seconds of + simulation, if the case gives one), standstill or error, + 4. compares the result with the one the case expects, evaluates the checks on the + physicslog and prints PASS/FAIL per check. + +Scenery and vehicle data are not part of this repo, so this runs against a local game +install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md. + +Usage: + python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" -j 4 # all cases + python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass, field +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[1] +CASES_DIR = HERE / "cases" +OUT_DIR = HERE / "out" + +# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp. +# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa. +COL_TIME = 0 +COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid +COL_BRAKE_PRESS = 8 +COL_COMMAND = 16 # text, read as None +COL_WHEELSLIP = 20 +COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it + +# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtestrules.h +EXIT_RESULTS = { + 0: "pass", + 10: "fail", + 11: "signal_passed_at_danger", + 12: "timeout", + 13: "standstill", + 14: "error", +} +# the timeout of the simulator's real time watchdog (test.wall_timeout) has the timeout code too; told +# apart by its verdict, so a run that hung doesn't pass a case that expects the simulation time to run out +WALL_TIMEOUT = "wall_timeout" +RESULTS = (*EXIT_RESULTS.values(), WALL_TIMEOUT) + +# settings layered over the game's eu07.ini for a test run (test mode doesn't read the player's own +# in %APPDATA%); the window ones only matter +# with --watch, test mode keeps its window hidden and turns the sound off by itself +TEST_INI = """\ +fullscreen no +fullscreenwindowed no +width 1280 +height 720 +inactivepause no +soundenabled no +physicslog yes +multiplelogs yes +timespeed {timespeed} +""" +# multiplelogs: log and errors go to logs/log () .txt instead of the shared +# log.txt, so runs of different cases can go in parallel + + +# ---------------------------------------------------------------- scenery + + +def split_trainsets(text: str) -> tuple[str, str]: + """Splits text into (everything else, the trainset ... endtrainset blocks).""" + rest, trainsets = [], [] + inside = False + for line in text.splitlines(keepends=True): + tokens = line.split("//", 1)[0].split() + if not inside and tokens and tokens[0].lower() == "trainset": + inside = True + if inside: + trainsets.append(line) + if any(t.lower() == "endtrainset" for t in tokens): + inside = False + continue + rest.append(line) + return "".join(rest), "".join(trainsets) + + +def set_start_time(text: str, hhmm: str) -> str: + return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1) + + +def add_track_events(text: str, events: dict) -> str: + """Adds lines (e.g. "event0 test_pass") to tracks named in events, before their endtrack.""" + for track, lines in events.items(): + lines = [lines] if isinstance(lines, str) else lines + m = re.search(rf"(?im)^\s*node\s+\S+\s+\S+\s+{re.escape(track)}\s+track\b.*?^(\s*endtrack\b)", text, re.S) + if not m: + sys.exit(f"track_events: no track {track} in the base scenery itself (not in its includes)") + text = text[: m.start(1)] + "".join(line + "\n" for line in lines) + text[m.start(1):] + return text + + +def set_track_friction(text: str, friction: float) -> str: + """Sets the friction of every track: node track ...""" + return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+", + lambda m: m.group(1) + f"{friction}", text) + + +def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str: + """Replaces {{name}} with the case's value; a list value becomes one line per item.""" + def value(m): + if m.group(1) in keep: + return m.group(0) + v = values.get(m.group(1)) + if v is None: + sys.exit(f"fragment uses {{{{{m.group(1)}}}}} but the case sets no such var") + return "\n".join(v) if isinstance(v, list) else str(v) + return re.sub(r"\{\{(\w+)\}\}", value, fragment) + + +def scenery_cache(game_dir: Path, case_name: str) -> Path: + """The simulator's geometry cache of the case scenery.""" + return game_dir / "scenery" / f"autotest_{case_name}.sbt" + + +def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str: + """Writes the case scenery into the game's scenery dir and returns its file name.""" + scenery_dir = game_dir / "scenery" + # sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled + text = (scenery_dir / case["base_scenery"]).read_bytes().decode("latin-1") + if case.get("strip_trainsets", True): + text, _ = split_trainsets(text) + if "time" in case: + text = set_start_time(text, case["time"]) + if "track_friction" in case: + text = set_track_friction(text, case["track_friction"]) + if "track_events" in case: + text = add_track_events(text, case["track_events"]) + fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") + # vars first: {{vehicle}} inside a var's value gets filled in the second pass + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) + fragment = fill_vars(fragment, {"vehicle": vehicle}) + # FirstInit binds event launchers to their events and links the tracks. so launchers and + # events of the case go in before it (read after it they never fire), trainsets after it + # (placed before it they stand on unlinked track and derail at once) + before, trainsets = split_trainsets(fragment) + # settings of the test mode, read like any other config block: the case's vehicle is the train under test, + # whose consist the pass and the standstill wait for, and the case's own (test.timeout and so on) + config = [f"test.vehicle {vehicle}", *case.get("test_config", [])] + before = "config\n" + "".join(line + "\n" for line in config) + "endconfig\n" + before + header = f"\n// ---- autotest: {case_name} ----\n" + firstinit = re.search(r"(?im)^\s*firstinit\b", text) + if firstinit: + text = text[: firstinit.start()] + header + before + "\n" + text[firstinit.start():] + else: + text += header + before + "\n" + text += header + trainsets + "\n" + name = f"autotest_{case_name}.scn" + (scenery_dir / name).write_bytes(text.encode("latin-1")) + # the simulator caches the scenery's static geometry in .sbt and reads it instead of + # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so + # drop the cache once the base scenery has changed + cache = scenery_cache(game_dir, case_name) + if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime: + cache.unlink() + return name + + +# ---------------------------------------------------------------- run + + +def read_physicslog(path: Path) -> list[list[float]]: + """Returns rows of columns, None for the text ones; skips the header and partial lines.""" + rows = [] + try: + lines = path.read_text(errors="replace").splitlines() + except FileNotFoundError: + return rows + for line in lines[1:]: + parts = line.split() + if len(parts) <= COL_BRAKE_PRESS: + continue # line still being written + try: + row = [float(p) for p in parts[: COL_BRAKE_PRESS + 1]] + except ValueError: + continue + for p in parts[COL_BRAKE_PRESS + 1:]: + try: + row.append(float(p)) + except ValueError: + row.append(None) + rows.append(row) + return rows + + +def find_logs(game_dir: Path, scenery: str, since: float) -> dict[str, Path]: + """The log.txt / errors.txt of one run; with multiplelogs each scenery gets its own files.""" + stem = scenery.rsplit(".", 1)[0] + found = {} + for kind in ("log", "errors"): + files = [p for p in (game_dir / "logs").glob(f"{kind} ({stem}) *.txt") if p.stat().st_mtime >= since] + if files: + found[kind] = max(files, key=lambda p: p.stat().st_mtime) + return found + + +def read_text(path: Path | None) -> str: + try: + return path.read_text(errors="replace") if path else "" + except FileNotFoundError: + return "" + + +# load problems that leave the case without its vehicle; no point waiting for the timeout +FATAL_LOG_LINES = ("Bad vehicle:", "Bad trainset:") +# wall seconds from start to the first physicslog row before giving up. "Scenario loading +# time" in the log is not the end of loading (the trainsets after FirstInit still follow), +# and with several simulators loading at once the first rows took well over 15 s +STARTUP_TIMEOUT = 120.0 +# wall seconds past a case's timeout before the runner kills a simulator that didn't end itself +KILL_GRACE = 30.0 + + +@dataclass +class RunResult: + rows: list[list[float]] = field(default_factory=list) + exit_code: int | None = None # None: still running when we closed it (the normal end with --watch) + verdict: str = "" # the simulator's own line about the test result + failure: str = "" # why the run was cut short + wall_seconds: float = 0.0 + logs: dict[str, Path] = field(default_factory=dict) + + +def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path, + duration: float | None, timeout: float, watch: bool, say) -> RunResult: + """Runs the simulator on the scenery. In test mode it quits by itself and the exit code + is the result; with watch it runs in a window and gets closed after `duration`.""" + physicslog.unlink(missing_ok=True) + if watch: + cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)] + else: + # the simulator's own watchdog ends a run that takes too long, with the timeout code and its verdict + cmd = [str(exe), "--test", "-s", scenery, "-ini", str(ini), "--test-wall-timeout", f"{timeout:g}"] + if duration is not None: + cmd += ["--test-timeout", f"{duration:g}"] + say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True) + since = time.time() - 1 + started = time.monotonic() + # the test result line goes to stdout; a file, not a pipe, so a chatty run can't block on it + stdout = (ini.parent / "stdout.txt").open("w+b") + proc = subprocess.Popen(cmd, cwd=game_dir, stdout=stdout, stderr=subprocess.STDOUT) + result = RunResult() + last_report = 0.0 + try: + while True: + time.sleep(0.25) # at timespeed 20 that is 5 s of simulation + wall = time.monotonic() - started + result.rows = read_physicslog(physicslog) + sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 + if wall - last_report >= 15: + v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0 + say(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h", progress=True) + last_report = wall + if proc.poll() is not None: + result.exit_code = proc.returncode + break + if watch and sim_t >= duration: + break + # in test mode a little later than the simulator's own limit, for a run that can't even end itself + if wall > timeout + (0 if watch else KILL_GRACE): + result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation" + break + if not result.rows: + result.logs = find_logs(game_dir, scenery, since) + fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines() + if any(k in l for k in FATAL_LOG_LINES)] + if fatal: + result.failure = "vehicle failed to load: " + " | ".join(fatal) + break + if wall > STARTUP_TIMEOUT: + result.failure = f"no physicslog rows after {STARTUP_TIMEOUT:.0f}s" + break + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + result.wall_seconds = time.monotonic() - started + stdout.seek(0) + result.verdict = next((line.strip() for line in stdout.read().decode(errors="replace").splitlines() + if line.startswith("test:")), "") + stdout.close() + result.rows = read_physicslog(physicslog) + result.logs = find_logs(game_dir, scenery, since) + return result + + +# ---------------------------------------------------------------- checks + + +def check_starts(rows, min_speed, within): + for r in rows: + if r[COL_TIME] > within: + break + if r[COL_VELOCITY] >= min_speed: + return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s" + top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0) + return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}" + + +def check_max_speed(rows, limit, tolerance=0.0): + worst = max(rows, key=lambda r: r[COL_VELOCITY]) + v, t = worst[COL_VELOCITY], worst[COL_TIME] + ok = v <= limit + tolerance + return ok, f"top speed {v:.1f} km/h at t={t:.1f}s (limit {limit} +{tolerance})" + + +def _first_moving(rows, moving_speed): + return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None) + + +def _distances(rows): + """Metres travelled up to each row, from the speed; the physicslog has no position.""" + out, d = [0.0], 0.0 + for a, b in zip(rows, rows[1:]): + d += (a[COL_VELOCITY] + b[COL_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME]) + out.append(d) + return out + + +def check_brakes(rows, min_pressure, moving_speed=20): + start = _first_moving(rows, moving_speed) + if start is None: + return False, "never moved, so never braked" + for r in rows[start:]: + if r[COL_BRAKE_PRESS] >= min_pressure: + return True, f"brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h" + return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off" + + +def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None): + start = _first_moving(rows, moving_speed) + if start is None: + return False, f"never reached {moving_speed} km/h" + dist = _distances(rows) + stopped_at = None + for i in range(start, len(rows)): + r = rows[i] + if r[COL_VELOCITY] <= stop_speed: + if stopped_at is None: + stopped_at = i + if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold: + where = dist[stopped_at] + detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m" + if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance): + return False, f"{detail}, wanted between {min_distance} and {max_distance} m" + return True, detail + else: + stopped_at = None + return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off" + + +def check_stays_stopped(rows, moving_speed, stop_speed): + """Once stopped after moving off, never moves again (e.g. waiting at a red signal).""" + start = _first_moving(rows, moving_speed) + if start is None: + return False, f"never reached {moving_speed} km/h" + stop = next((i for i in range(start, len(rows)) if rows[i][COL_VELOCITY] <= stop_speed), None) + if stop is None: + return False, f"never came down to {stop_speed} km/h" + moved = next((r for r in rows[stop:] if r[COL_VELOCITY] > stop_speed), None) + if moved is not None: + return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s but moved again at t={moved[COL_TIME]:.1f}s, v={moved[COL_VELOCITY]:.1f} km/h" + return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s and stayed until t={rows[-1][COL_TIME]:.1f}s" + + +def check_distance(rows, max=None, min=None): + """Total distance travelled, in metres.""" + d = _distances(rows)[-1] + ok = (max is None or d <= max) and (min is None or d >= min) + bounds = " ".join(s for s in (f">= {min}" if min is not None else "", f"<= {max}" if max is not None else "") if s) + return ok, f"travelled {d:.0f} m (wanted {bounds})" + + +def check_slips(rows, within=None): + """The lead vehicle's wheels slip (or lock in a skid) at some point, e.g. to make sure a slippery rail case does what it's meant to.""" + for r in rows: + if within is not None and r[COL_TIME] > within: + break + if len(r) > COL_WHEELSLIP and r[COL_WHEELSLIP]: + return True, f"wheels slipping at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h" + return False, "the wheels never slipped" + + +def check_holds_still(rows, moving_speed, stop_speed, max_distance): + """Once stopped after moving off, the vehicle doesn't creep. Uses the vehicle speed rather than the + wheel speed, so it also catches a vehicle sliding on locked wheels.""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows] + start = next((i for i, v in enumerate(speed) if v >= moving_speed), None) + if start is None: + return False, f"never reached {moving_speed} km/h" + stop = next((i for i in range(start, len(rows)) if speed[i] <= stop_speed), None) + if stop is None: + return False, f"never came down to {stop_speed} km/h" + d, top, top_t = 0.0, 0.0, rows[stop][COL_TIME] + for i in range(stop + 1, len(rows)): + d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME]) + if speed[i] > top: + top, top_t = speed[i], rows[i][COL_TIME] + held = rows[-1][COL_TIME] - rows[stop][COL_TIME] + detail = f"stopped at t={rows[stop][COL_TIME]:.1f}s, then moved {d:.3f} m in {held:.0f}s, top {top:.4f} km/h at t={top_t:.1f}s" + return d <= max_distance, detail + + +def check_ends_moving(rows, min_speed): + """The run ended with the vehicle still moving, e.g. a pass that didn't wait for the trains to stop.""" + if not rows: + return False, "the physicslog is empty" + last = rows[-1] + ok = last[COL_VELOCITY] >= min_speed + return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})" + + +def check_slip_clears(rows, moving_speed, stop_speed, within): + """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds + (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion).""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + start = next((i for i, r in enumerate(rows) if abs(r[COL_VEHICLE_VELOCITY]) >= moving_speed), None) + if start is None: + return False, f"never reached {moving_speed} km/h" + stop = next((i for i in range(start, len(rows)) if abs(rows[i][COL_VEHICLE_VELOCITY]) <= stop_speed), None) + if stop is None: + return False, f"never came down to {stop_speed} km/h" + deadline = rows[stop][COL_TIME] + within + late = [r for r in rows[stop:] if r[COL_TIME] > deadline and r[COL_WHEELSLIP]] + if late: + return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s, wheels still slipping at t={late[0][COL_TIME]:.1f}s ({len(late)} rows after the {within}s grace)" + return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s" + + +CHECKS = { + "slips": check_slips, + "slip_clears": check_slip_clears, + "holds_still": check_holds_still, + "starts": check_starts, + "max_speed": check_max_speed, + "brakes": check_brakes, + "stops": check_stops, + "stays_stopped": check_stays_stopped, + "distance": check_distance, + "ends_moving": check_ends_moving, +} + + +# ---------------------------------------------------------------- main + + +def find_exe(explicit: str | None) -> Path: + if explicit: + return Path(explicit).resolve() + candidates = sorted(REPO.glob("cmake-build-*/bin/Release/eu07*.exe"), key=lambda p: p.stat().st_mtime) + if not candidates: + sys.exit("no eu07 executable found under cmake-build-*/bin/Release, pass --exe") + return candidates[-1] + + +def count_lines(path: Path) -> int: + try: + return sum(1 for line in path.read_text(errors="replace").splitlines() if line.strip()) + except FileNotFoundError: + return 0 + + +def describe_exit(code: int | None) -> str: + if code is None: + return "none, still running" + name = EXIT_RESULTS.get(code) + return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" + + +def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool: + case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) + say(f"\n=== {name}: {case.get('description', '')}") + out = OUT_DIR / name + shutil.rmtree(out, ignore_errors=True) + out.mkdir(parents=True) + + # the lead vehicle is named after the case, so parallel runs never share a physicslog + vehicle = f"autotest_{name}" + scenery = build_scenery(case, game_dir, name, vehicle) + ini = out / "autotest.ini" + ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii") + physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + + duration = float(case["duration"]) if "duration" in case else None + # a case that only records `duration` seconds ends on the test timeout; one that says + # how the test ends (a pass event, a signal passed at danger...) expects that result + expect = case.get("expect", "timeout" if duration is not None else "pass") + if expect not in RESULTS: + sys.exit(f"{name}: expect must be one of {', '.join(RESULTS)}") + if watch and duration is None: + sys.exit(f"{name}: --watch needs a case with duration") + result = run_simulator(exe, game_dir, scenery, ini, physicslog, + duration, float(case.get("timeout", 600)), watch, say) + + # the logs are ours alone (named after the case scenery), move them out of the game dir + for kind, path in result.logs.items(): + shutil.move(path, out / f"{kind}.txt") + if physicslog.exists(): + shutil.move(physicslog, out / physicslog.name) + # other trains of the case with a driver, named _, log too + for other in physicslog.parent.glob(f"*_{vehicle}.dat"): + shutil.move(other, out / other.name) + + ok = True + sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 + say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}") + if watch: + if result.exit_code is not None: + say(f" FAIL simulator exited on its own with code {result.exit_code}") + ok = False + else: + if result.verdict: + say(f" {result.verdict}") + got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None + if got == "timeout" and "of real time" in result.verdict: + got = WALL_TIMEOUT + passed = got == expect + watchdog = ", from the real time watchdog" if got == WALL_TIMEOUT else "" + say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}") + ok &= passed + # a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing + # the scenery's geometry cache; the simulator checks only the header of it, so the next runs would read + # a truncated one. it is written again on the next run + if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)): + scenery_cache(game_dir, name).unlink(missing_ok=True) + if result.failure: + say(f" FAIL {result.failure}") + ok = False + if not result.rows and case.get("checks"): + if not result.failure: + say(f" FAIL no physicslog for '{vehicle}'") + return False + + for check in case.get("checks", []): + params = {k: v for k, v in check.items() if k != "type"} + passed, detail = CHECKS[check["type"]](result.rows, **params) + say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}") + ok &= passed + + errors = count_lines(out / "errors.txt") + if errors: + say(f" note errors.txt has {errors} line(s)") + if case.get("fail_on_errors") and errors: + ok = False + return ok + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("cases", nargs="*", help="case names from cases/ (default: all)") + ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"), + help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)") + ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)") + ap.add_argument("--watch", action="store_true", + help="run in a visible window in real time (see --timespeed) instead of the test mode, " + "closed after the case's duration; the exit code isn't checked") + ap.add_argument("--timespeed", type=float, default=1.0, + help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)") + ap.add_argument("-j", "--jobs", type=int, default=1, + help="cases run at once, each in a simulator of its own (default 1)") + args = ap.parse_args() + + if not args.game_dir: + sys.exit("pass --game-dir or set EU07_GAME_DIR") + game_dir = Path(args.game_dir).resolve() + exe = find_exe(args.exe) + print(f"exe: {exe}\ngame: {game_dir}") + + names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json")) + missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()] + if missing: + sys.exit("no such case: " + ", ".join(missing)) + + started = time.monotonic() + results = {} + if args.jobs <= 1: + def say(line, progress=False): + print(line, flush=True) + for n in names: + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + else: + # each case prints its block when it is done, so parallel output does not interleave + def job(n): + lines = [] + def say(line, progress=False): + if not progress: + lines.append(line) + ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + return n, ok, lines + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + for n in names: + print(f"started {n}", flush=True) + for fut in as_completed([pool.submit(job, n) for n in names]): + n, ok, lines = fut.result() + print("\n".join(lines), flush=True) + results[n] = ok + + print(f"\n=== summary ({time.monotonic() - started:.0f}s)") + for n in names: + print(f" {'PASS' if results[n] else 'FAIL'} {n}") + return 0 if all(results.values()) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/data/diesel_electric.json b/tests/unit/data/diesel_electric.json new file mode 100644 index 000000000..bef605880 --- /dev/null +++ b/tests/unit/data/diesel_electric.json @@ -0,0 +1,46 @@ +{ + "_comment": "Diesel-electric locomotive made after the SU46 (303D): the line contactors close on the first power position of the master controller, the pressure switch (on by default) opens them with too low a pressure in the main pipe or the brakes applied.", + "Param": { "Category": "train", "M": 105000, "Mred": 15000, "Vmax": 120, "PWR": 1400, "SandCap": 400 }, + "Dimensions": { "L": 18.99, "H": 4.292, "W": 2.904, "Cx": 0.3 }, + "Wheels": { "D": 1.1, "AIM": 4000, "Tw": 1.435, "Axle": "Co'Co'", "Ad": 1.75, "Bd": 10.3, "Rmin": 100 }, + "Brake": { + "BrakeValve": "LSt", "NBpA": 4, "MBF": 85.0, "MaxBP": 4.4, "LocMaxBP": 4.4, "MaxASBP": 1.3, "RM": 0.71, "BCN": 12, "BCR": 0.114, + "BCD": 0.06, "BCM": 5.84, "HiPP": 5, "LoPP": 3.5, "Vv": 0.9, "MinCP": 7, "MaxCP": 8.5, "CompressorSpeed": 0.05, "BCS": 1, "BSA": 2, + "BM": "P10-Bgu", "CompressorPower": "Converter", "BVV": 200, "BRE": 0.8 + }, + "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 103 }, + "Cntrl": { + "BrakeHandle": "FV4a", "LocBrakeHandle": "FD1", "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 6, "BDelay3": 36, "BDelay4": 32, + "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": 15, "SCPN": 4, "AutoRelay": "Yes", "IniCDelay": 0.5, "SCDelay": 0.1, + "BrakeDelays": "GPR", "ConverterStart": "Automatic", "ConverterStartDelay": 10 + }, + "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 110, "LMaxCurrent": 100 }, + "Engine": { + "AIM": 1.6, "EngineType": "DumbDE", "Trans": "18:62", "Ftmax": 317000, "Flat": 0, "Vhyp": 15.0, "Vadd": 3.8, "Cr": 1.0, "RelayType": 46, + "OilMinPressure": 0.055, "OilMaxPressure": 0.6, "WaterMinTemperature": 40, "WaterMaxTemperature": 92, "WaterCoolingTemperature": 76, + "HeatKW": 0.068599, "HeatKV": 0.3, "HeatKFE": 1, "HeatKFS": 87.76269, "HeatKFO": 26.72716, "HeatKFO2": 57.72 + }, + "Circuit": { "CircuitRes": 0.01, "ImaxLo": 3300, "IminLo": 2500 }, + "_power": "rows: engine speed [rpm], power [kW], generator voltage limit, current limit, one per master controller position", + "WWList": { + "Size": 15, + "rows": [ + [696, 0, 0, 0], + [696, 0, 0, 0], + [696, 80, 350, 1000], + [696, 80, 350, 1000], + [763, 214, 455, 1400], + [830, 321, 500, 1600], + [897, 428, 545, 1800], + [964, 535, 590, 2000], + [1031, 642, 635, 2200], + [1098, 748, 680, 2400], + [1165, 855, 725, 2600], + [1232, 962, 770, 2800], + [1299, 1069, 815, 3000], + [1366, 1176, 865, 3200], + [1433, 1283, 910, 3400], + [1500, 1390, 960, 3600] + ] + } +} diff --git a/tests/unit/data/diesel_shunter.json b/tests/unit/data/diesel_shunter.json new file mode 100644 index 000000000..3cbcdb992 --- /dev/null +++ b/tests/unit/data/diesel_shunter.json @@ -0,0 +1,53 @@ +{ + "_comment": "Diesel shunter with a mechanical gearbox, made after the SM03 (Ls150): the fuel pump starts on its own with the engine, a converter run by the engine feeds the low voltage circuit, the only cab control of the engine is the starter button.", + "Param": { "Category": "train", "M": 23200, "Vmax": 25.68, "PWR": 111.855, "SandCap": 200 }, + "Dimensions": { "L": 6.94, "H": 3.21, "W": 2.97, "Cx": 0.3 }, + "Wheels": { "D": 0.94, "Tw": 1.435, "AIM": 250, "Axle": "B", "Ad": 2.5, "Bd": 2.5, "Rmin": 50, "BearingType": "Roll" }, + "Brake": { + "BrakeValve": "K", "NBpA": 2, "MBF": 85.0, "MaxBP": 3.5, "LocMaxBP": 5.0, "BCN": 1, "BCR": 0.114, "BCD": 0.12, "BCM": 10.0, + "HiPP": 5, "LoPP": 3.5, "Vv": 0.3, "MinCP": 7.0, "MaxCP": 8.0, "CompressorSpeed": 0.0125, "CompressorPower": "Main", + "BCS": 0.8, "BSA": 0, "BM": "P10-Bg", "BVV": 40, "BRE": 0.9 + }, + "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 3 }, + "Cntrl": { + "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 4, "ASB": "Manual", "LocalBrake": "PneumaticBrake", "ManualBrake": "Yes", + "DynamicBrake": "Passive", "MCPN": 9, "SCPN": 7, "AutoRelay": "No", "IniCDelay": 0.5, "SCDelay": 0.1, "BrakeDelays": "P", + "BrakeHandle": "Knorr", "LocBrakeHandle": "Knorr", "FuelStart": "Automatic", "ConverterStart": "Automatic" + }, + "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 24, "LMaxCurrent": 100 }, + "Engine": { + "EngineType": "DieselEngine", "Trans": "1:1", "nmin": 900, "nmax": 1500, "nmax_cutoff": 1550, "AIM": 100, + "OilMinPressure": 0.343, "OilMaxPressure": 0.686, "WaterCoolingTemperature": 80, "WaterShutters": "yes", "WaterAuxCircuit": "no", + "HeatKFO": 160, "HeatKFO2": 180, "HeatKFS": 160, "HeatKFE": 7, "HeatKW": 2, "HeatKV": 0.3, "IsTC": "No", "EUS": 0.35, "EDS": 1.0 + }, + "_gears": "rows: gear, ratio, engagement speed, top speed; the even ones neutral", + "MotorParamTable": { + "minVelfullengage": 3.8, "engageDia": 1, "engageMaxForce": 800, "engagefriction": 1, + "rows": [ + [0, 0, 0, -1], + [1, 46.88, -1, 5.73], + [2, 0, 0, -1], + [3, 28.65, 2.9, 9.42], + [4, 0, 0, -1], + [5, 17.12, 4.7, 15.69], + [6, 0, 0, -1], + [7, 10.46, 10.6, 100] + ] + }, + "_throttle": "rows: position, fill, speed governor mode; position 0 idles", + "DList": { + "Size": 9, "Mmax": 784.5, "nMmax": 15, "Mnmax": 686.4, "nmax": 25, "nominalfill": 1, "Mstand": 200.0, + "rows": [ + [0, 0.1, 0], + [1, 0.2, 2], + [2, 0.3, 2], + [3, 0.4, 2], + [4, 0.5, 2], + [5, 0.6, 2], + [6, 0.7, 2], + [7, 0.8, 2], + [8, 0.9, 2], + [9, 1.0, 2] + ] + } +} diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index b933a0ab5..4af8be18a 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -5,6 +5,21 @@ namespace test { +namespace { + +// whether the pressure switch of a vehicle in the train still cuts the start off: a half of a locomotive whose +// switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero +bool start_cut_off(consist &Train) { + for (std::size_t i = 0; i < Train.size(); ++i) { + if (Train[i].mover().ControlPressureSwitch) { + return true; + } + } + return false; +} + +} // namespace + scenario::scenario(std::string Name, std::vector Channels, track const &Track) : m_name(std::move(Name)), m_channels(std::move(Channels)), m_track(Track) { reseed_random(); } @@ -53,6 +68,11 @@ void scenario::get_going() { void scenario::full_power(double Seconds) { auto &controlling{driver().controlling}; + // as a driver does, wait for the brakes to let go far enough for every pressure switch of the train to allow the + // start; otherwise whether all the halves of a locomotive start hangs on thousandths of a bar of their cylinders + for (int i = 0; i < 120 && start_cut_off(m_train); ++i) { + wait(1.0); + } controlling.IncMainCtrl(1); for (int i = 0; i < 90 && false == controlling.StLinFlag; ++i) { wait(1.0); diff --git a/tests/unit/test_ai_hints.cpp b/tests/unit/test_ai_hints.cpp new file mode 100644 index 000000000..d01e421c9 --- /dev/null +++ b/tests/unit/test_ai_hints.cpp @@ -0,0 +1,31 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the hints for the AI driver from the AI section of the .fiz + +TEST_CASE("ai hints: without the AI section the pantographs follow the built-in logic") { + vehicle wagon{definition::load("wagon")}; + + CHECK(wagon->AIHintPantstate == 0); + CHECK(wagon->AIHintShuntPantstate == 0); + CHECK(wagon->AIHintPantUpIfIdle); +} + +TEST_CASE("ai hints: the suggested pantograph setup for shunting is read apart from the one for train mode") { + // eu07/maszyna#461: so the ET41 doesn't shunt with all of its four pantographs up + vehicle shunting{definition::load("wagon").set("AI", "Pantstate", 1).set("AI", "ShuntPantstate", 2)}; + + CHECK(shunting->AIHintPantstate == 1); + CHECK(shunting->AIHintShuntPantstate == 2); +} + +TEST_CASE("ai hints: a .fiz with the setup for train mode only has none for shunting") { + vehicle train{definition::load("wagon").set("AI", "Pantstate", 3)}; + + CHECK(train->AIHintPantstate == 3); + CHECK(train->AIHintShuntPantstate == 0); +} diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 51c25243b..889beb338 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -4,6 +4,7 @@ #include "golden.h" #include "real_vehicles.h" #include "drive.h" +#include "consist.h" #include "McZapkie/hamulce.h" @@ -35,6 +36,7 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double // every position of the driver's handle, recorded in the trace void every_position(vehicle &Vehicle, test::trace &Trace) { Vehicle.hold_main_reservoir(std::max(Vehicle->MaxCompressor, 8.0)); + REQUIRE(Vehicle->Handle != nullptr); auto &handle{*Vehicle->Handle}; Vehicle.record(Trace); @@ -57,6 +59,13 @@ void every_position(vehicle &Vehicle, test::trace &Trace) { hold(Vehicle, Trace, "running", handle.GetPos(bh_RP), 60.0); } +// the handle put to the given position and the vehicle driven from its cab for Seconds, marked in the trace +void driven_at(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double Position, double Seconds) { + Trace.mark(Event); + Vehicle->BrakeLevelSet(Position); + test::drive(test::driving(Vehicle), {}, Seconds); +} + } // namespace TEST_CASE("brake handles: every position of the driver's handle of every real vehicle") { @@ -96,6 +105,7 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); test::trace trace{"local brake/" + path, handle_channels(), 100}; real.record(trace); + REQUIRE(real->Handle != nullptr); real->BrakeLevelSet(real->Handle->GetPos(bh_RP)); trace.mark("charge"); real.run(60.0); @@ -126,25 +136,21 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100}; real.record(trace); + REQUIRE(real->Handle != nullptr); auto &handle{*real->Handle}; - auto const at{[&trace, &real](std::string const &Event, double Position, double Seconds) { - trace.mark(Event); - real->BrakeLevelSet(Position); - test::drive(test::driving(real), {}, Seconds); - }}; - at("running", handle.GetPos(bh_RP), 60.0); + driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0); auto const running{real->PipePress}; handle.SetUniversalFlag(TUniversalBrake::ub_Overload); - at("overload button", handle.GetPos(bh_RP), 30.0); + driven_at(real, trace, "overload button", handle.GetPos(bh_RP), 30.0); handle.SetUniversalFlag(0); auto const overloaded{real->PipePress}; - at("overload decaying", handle.GetPos(bh_RP), 240.0); + driven_at(real, trace, "overload decaying", handle.GetPos(bh_RP), 240.0); auto const decayed{real->PipePress}; handle.SetUniversalFlag(TUniversalBrake::ub_HighPressure); - at("high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0); + driven_at(real, trace, "high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0); auto const filled{real->PipePress}; handle.SetUniversalFlag(0); - at("running", handle.GetPos(bh_RP), 120.0); + driven_at(real, trace, "running", handle.GetPos(bh_RP), 120.0); CHECK(running == doctest::Approx(5.0).epsilon(0.01)); CHECK(overloaded > running + 0.3); CHECK(decayed < overloaded); @@ -152,3 +158,110 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ trace.check(); } } + +// eu07/maszyna#134: the Knorr St113 of the EN57-001 releases the EP brake in the running position (bh_RP, Num 6) +// and applies it one position on (Num 8), short of the lap position (Num 5); the positions are those the keys +// select, and the EP brake works only with the control of the cab powered: the battery, the reverser out of +// neutral and the EP fuse on (Ctrl+Z), as the Oerlikon handle's +namespace { + +// the front car of the EN57-001 driven from its cab, with the motor car behind it, which has the battery of the two; +// air in the reservoirs, the battery on +void ready_knorr_ep(test::consist &Unit) { + Unit.add(definition::fiz("en57_v1/6bai"), 1); + Unit.add(definition::fiz("en57_v1/5bgb")); + auto &cab{Unit[0]}; + REQUIRE(cab->BrakeHandle == TBrakeHandle::St113); + REQUIRE(cab->Handle != nullptr); + cab->BatterySwitch(true); + cab->CabActivisation(); + cab.hold_brake_pipe(5.0); + cab->BrakeLevelSet(cab->Handle->GetPos(bh_RP)); + Unit.run(60.0); +} + +// the EP brake button pressed in the given handle position, held for Seconds; the cylinder pressure of the cab car +double ep_brake(test::consist &Unit, double Position, double Seconds) { + auto &cab{Unit[0]}; + cab->BrakeLevelSet(Position); + Unit.run(0.1); + cab->SwitchEPBrake(1); + Unit.run(Seconds); + return cab->BrakePress; +} + +// the EP force the St113 handle of the cab car gives in the given position +double ep_at(test::consist &Unit, double Position) { + auto &cab{Unit[0]}; + cab->BrakeLevelSet(Position); + Unit.run(0.1); + return cab->Handle->GetEP(); +} + +} // namespace + +TEST_CASE("brake handles: the positions of the Knorr St113 EP brake") { + test::consist unit; + ready_knorr_ep(unit); + auto &cab{unit[0]}; + REQUIRE(cab->Handle != nullptr); + auto &handle{*cab->Handle}; + // the keys: Num 6 running, Num 8 the first position on, Num 5 the middle of the handle + CHECK(handle.GetPos(bh_RP) == doctest::Approx(0.0)); + CHECK(ep_at(unit, 0.0) == doctest::Approx(-1.0)); // EP release + CHECK(ep_at(unit, 1.0) == doctest::Approx(1.0)); // EP brake + CHECK(ep_at(unit, cab->BrakeCtrlPosNo / 2) == doctest::Approx(0.0)); // lap, Num 5 + CHECK(ep_at(unit, handle.GetPos(bh_FB)) == doctest::Approx(0.0)); + CHECK(ep_at(unit, handle.GetPos(bh_EPR)) == doctest::Approx(-1.0)); + CHECK(ep_at(unit, handle.GetPos(bh_EPB)) == doctest::Approx(1.0)); +} + +TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab powered") { + for (std::string const cut : {"reverser in neutral", "EP fuse off", "battery off"}) { + CAPTURE(cut); + test::consist unit; + ready_knorr_ep(unit); + auto &cab{unit[0]}; + cab->DirectionForward(); + unit.run(1.0); + REQUIRE(cab->EPBrakeControlPowered()); + if (cut == "reverser in neutral") { + cab->DirectionBackward(); + } + else if (cut == "EP fuse off") { + cab->EpFuseSwitch(false); + } + else { + cab->BatterySwitch(false); + } + unit.run(1.0); + REQUIRE_FALSE(cab->EPBrakeControlPowered()); + // the button in the EP brake position does nothing + CHECK(ep_brake(unit, 1.0, 5.0) < 0.1); + CHECK(cab->EpForce == doctest::Approx(0.0)); + cab->SwitchEPBrake(0); + } + + test::consist unit; + ready_knorr_ep(unit); + auto &cab{unit[0]}; + cab->DirectionForward(); + unit.run(1.0); + // powered, the EP brake applies + auto const applied{ep_brake(unit, 1.0, 2.0)}; + CHECK(applied > 0.5); + // the reverser put to neutral with the button still held: the EP brake drops out and holds what it applied + cab->DirectionBackward(); + unit.run(0.1); + CHECK(cab->EpForce == doctest::Approx(0.0)); + auto const held{cab->BrakePress}; + unit.run(5.0); + CHECK(cab->BrakePress < held + 0.05); + CHECK(cab->BrakePress > 0.2); + // and doesn't release either, until the control is powered again + CHECK(ep_brake(unit, 0.0, 5.0) > 0.2); + cab->SwitchEPBrake(0); + cab->DirectionForward(); + unit.run(0.1); + CHECK(ep_brake(unit, 0.0, 10.0) < 0.1); +} diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index 834168074..e12694f3f 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "doctest.h" #include "vehicle.h" +#include "consist.h" using test::definition; using test::vehicle; @@ -91,3 +92,48 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") { wagon.run(40.0 /* s */, test::track{0.15 /* friction */, 0.0 /* gradient */}); CHECK(std::abs(wagon.speed()) < 0.1); } + +// eu07/maszyna#87: the ESt4d of the EN57's EP2 valve charged its auxiliary reservoir from the main reservoir pipe +// alone, so a dead unit hauled by a locomotive coupled with the hook and the brake hose ("3") never charged it, +// its control reservoir stopped half way, and it didn't brake. Like every ESt, it charges from the brake pipe too +TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the brake pipe and brakes") { + test::consist train; + auto &locomotive{train.add(definition::fiz("sm42_v1/6d1"))}; + train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::coupler | coupling::brakehose); + train.add(definition::fiz("en57_v1/6ba_840")); + train.add(definition::fiz("en57_v1/5bgaiii_led_spot")); + // a unit standing dead: no air anywhere, nothing in its main reservoir pipe + for (std::size_t i = 1; i < train.size(); ++i) { + auto &car{train[i].mover()}; + REQUIRE(car.BrakeValve == TBrakeValve::EP2); + car.Hamulec->ForceEmptiness(); + car.Pipe->CreatePress(0.0); + car.Pipe->Act(); + car.Pipe2->CreatePress(0.0); + car.Pipe2->Act(); + car.CompressedVolume = 0.0; + } + locomotive.hold_brake_pipe(5.0); + train.run(900.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &car{train[i].mover()}; + REQUIRE(car.ScndPipePress < 0.1); // no main reservoir pipe + CHECK(car.Hamulec->GetBRP() > 4.8); + CHECK(car.Hamulec->GetCRP() > 4.8); + CHECK(car.BrakePress < 0.1); + } + // a full service application brakes the unit, and it releases again + locomotive.hold_brake_pipe(3.5); + train.run(20.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i]->BrakePress > 2.0); + } + locomotive.hold_brake_pipe(5.0); + train.run(60.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i]->BrakePress < 0.1); + } +} diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 4c5ba9f53..063e70911 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -227,3 +227,204 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended" CHECK(security.radiostop_available()); scenario.check(); } + +namespace { + +// the SM42, its shunt mode switching its vigilance device (CA) off or not (AwareOffInShuntMode), set in the +// test whatever the converted definition says +definition sm42_vigilance(bool const Off) { + return definition::fiz("sm42_v1/6d1").set("Security", "AwareOffInShuntMode", Off ? "Yes" : "No"); +} + +// runs the train for Seconds with nobody acknowledging the vigilance; returns whether the vigilance alarm came +bool unattended(scenario &Scenario, int const Seconds) { + bool blinked{false}; + for (int i = 0; i < Seconds; ++i) { + Scenario.train().run(1.0, Scenario.line()); + blinked |= Scenario.cab().SecuritySystem.is_vigilance_blinking(); + } + return blinked; +} + +} // namespace + +TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, where its definition says so") { + // eu07/maszyna#457: with AwareOffInShuntMode=Yes the shunt mode of the SM42 switches its vigilance device (CA) + // off, it alerts again once the shunt mode is off + scenario scenario{"cab/sm42 vigilance in shunt mode", motion() + brakes(), test::track{}}; + scenario.train().add(sm42_vigilance(true), 1); + REQUIRE(scenario.start_up()); + auto &sm42{scenario.cab()}; + auto const &security{sm42.SecuritySystem}; + REQUIRE(sm42.CurrentSwitch(true)); + REQUIRE(sm42.ShuntMode); + scenario.get_going(); + sm42.AnPos = 0.3; + sm42.IncMainCtrl(1); + scenario.act("unattended in shunt mode"); + bool blinked{false}; + for (int i = 0; i < 120; ++i) { + scenario.train().run(1.0, scenario.line()); + blinked |= security.is_blinking(); + } + CHECK(sm42.Vel > 1.0); + CHECK_FALSE(blinked); + CHECK(sm42.PipePress > 3.5); + scenario.act("shunt mode off"); + scenario.notch_back(0); + REQUIRE(sm42.CurrentSwitch(false)); + sm42.IncMainCtrl(1); + scenario.act("unattended"); + CHECK(unattended(scenario, 120)); + scenario.check(); +} + +TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by default") { + // without AwareOffInShuntMode the shunt mode leaves the vigilance device alone: unattended, it alerts and brakes + scenario scenario{"cab/sm42 vigilance kept in shunt mode", motion() + brakes(), test::track{}}; + scenario.train().add(sm42_vigilance(false), 1); + REQUIRE(scenario.start_up()); + auto &sm42{scenario.cab()}; + REQUIRE(sm42.CurrentSwitch(true)); + REQUIRE(sm42.ShuntMode); + scenario.get_going(); + sm42.AnPos = 0.3; + sm42.IncMainCtrl(1); + scenario.act("unattended in shunt mode"); + CHECK(unattended(scenario, 120)); + CHECK(sm42.ShuntMode); + CHECK(sm42.PipePress < 1.0); + scenario.check(); +} + +TEST_CASE("cab: the SM42's vigilance alarm on, not cleared by switching into the shunt mode") { + // the shunt mode switches the vigilance device off for the time to come: an alarm already on goes on to the + // emergency braking, until the driver acknowledges it (#275 review) + scenario scenario{"cab/sm42 vigilance alarm into shunt mode", motion() + brakes(), test::track{}}; + scenario.train().add(sm42_vigilance(true), 1); + REQUIRE(scenario.start_up()); + auto &sm42{scenario.cab()}; + auto const &security{sm42.SecuritySystem}; + scenario.get_going(); + sm42.IncMainCtrl(1); + scenario.act("unattended"); + // the alerter counts only on the move, which takes a while on the first notch + for (int i = 0; i < 300 && false == security.is_vigilance_blinking(); ++i) { + scenario.train().run(1.0, scenario.line()); + } + REQUIRE(security.is_vigilance_blinking()); + REQUIRE_FALSE(security.is_braking()); + scenario.act("shunt mode on"); + for (int i = 0; i < 20 && false == sm42.IsMainCtrlNoPowerPos(); ++i) { + sm42.DecMainCtrl(1); + } + REQUIRE(sm42.CurrentSwitch(true)); + REQUIRE(sm42.ShuntMode); + scenario.train().run(15.0, scenario.line()); + CHECK(security.is_vigilance_blinking()); + CHECK(security.is_beeping()); + CHECK(security.is_braking()); + CHECK(sm42.PipePress < 1.0); + scenario.act("acknowledged"); + sm42.SecuritySystemReset(); + scenario.train().run(1.0, scenario.line()); + CHECK_FALSE(security.is_blinking()); + CHECK_FALSE(security.is_braking()); + scenario.check(); +} + +namespace { + +TSecuritySystem sm42_security(bool const OffInShuntMode) { + TSecuritySystem security; + security.load(std::string{"Security: AwareSystem=Active AwareMinSpeed=0.0 AwareDelay=60 SoundSignalDelay=2.5 MaxHoldTime=1.0 " + "EmergencyBrakeDelay=2.5 AwareOffInShuntMode="} + + (OffInShuntMode ? "Yes" : "No"), + 90.0); + security.set_enabled(true); + security.update(0.1, 20.0, true, 1); + return security; +} + +void run(TSecuritySystem &Security, double const Seconds) { + for (int i = 0; i < std::lround(Seconds / 0.1); ++i) { + Security.update(0.1, 20.0, true, 1); + } +} + +} // namespace + +TEST_CASE("cab: the alerter in the shunt mode, with and without AwareOffInShuntMode") { + for (auto const off : {false, true}) { + CAPTURE(off); + auto security{sm42_security(off)}; + security.set_shunt_mode(true); + run(security, 120.0); + // without the key the shunt mode changes nothing: the alerter alerts and brakes + CHECK(security.is_vigilance_blinking() != off); + CHECK(security.is_braking() != off); + } +} + +TEST_CASE("cab: the alerter's alarm on, not cleared by the shunt mode") { + auto security{sm42_security(true)}; + run(security, 61.0); + REQUIRE(security.is_vigilance_blinking()); + REQUIRE_FALSE(security.is_braking()); + security.set_shunt_mode(true); + run(security, 10.0); + CHECK(security.is_vigilance_blinking()); + CHECK(security.is_beeping()); + CHECK(security.is_braking()); + security.acknowledge_press(); + security.acknowledge_release(); + run(security, 0.1); + CHECK_FALSE(security.is_blinking()); + CHECK_FALSE(security.is_braking()); + // then nothing more on the move in the shunt mode + run(security, 300.0); + CHECK_FALSE(security.is_blinking()); + // and back in the line mode the alerter counts again + security.set_shunt_mode(false); + run(security, 61.0); + CHECK(security.is_vigilance_blinking()); +} + +TEST_CASE("cab: the vigilance button held too long, its alarm not cleared by the shunt mode") { + // the alarm of the button held too long stays on in the shunt mode too, until the button is let go + TSecuritySystem security; + security.load("Security: AwareSystem=Active AwareMinSpeed=0.0 AwareDelay=60 SoundSignalDelay=2.5 MaxHoldTime=1.0 " + "EmergencyBrakeDelay=2.5 AwareOffInShuntMode=Yes", + 90.0); + security.set_enabled(true); + security.update(0.1, 20.0, true, 1); + security.acknowledge_press(); + for (int i = 0; i < 20; ++i) { + security.update(0.1, 20.0, true, 1); + } + REQUIRE(security.is_vigilance_blinking()); + security.set_shunt_mode(true); + for (int i = 0; i < 60; ++i) { + security.update(0.1, 20.0, true, 1); + } + CHECK(security.is_vigilance_blinking()); + CHECK(security.is_braking()); + security.acknowledge_release(); + security.update(0.1, 20.0, true, 1); + CHECK_FALSE(security.is_blinking()); + CHECK_FALSE(security.is_braking()); + // held again in the shunt mode, no new alarm + security.acknowledge_press(); + for (int i = 0; i < 100; ++i) { + security.update(0.1, 20.0, true, 1); + } + CHECK_FALSE(security.is_blinking()); + security.acknowledge_release(); + // out of the shunt mode, held too long again + security.set_shunt_mode(false); + security.acknowledge_press(); + for (int i = 0; i < 20; ++i) { + security.update(0.1, 20.0, true, 1); + } + CHECK(security.is_vigilance_blinking()); +} diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index 0dd3ddc20..c73c45d85 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -37,3 +37,145 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh CHECK(unit->ConverterOverloadRelayStart == start_t::automatic); } } + +namespace { + +// the first position of the master controller after Position without the starting resistors in the circuit +int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) { + for (auto position{Position + 1}; position <= Vehicle.MainCtrlPosNo; ++position) { + if (Vehicle.RList[position].R < 0.01) { + return position; + } + } + return 0; +} + +// the vehicle with its cab occupied, the master controller set to Position and the shunt controller off +void controllers_at(vehicle &Vehicle, int Position) { + Vehicle->CabActive = 1; + Vehicle->MainCtrlPos = Position; + Vehicle->ScndCtrlPos = 0; +} + +} // namespace + +TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and on the resistive positions (eu07/maszyna#402)") { + for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) { + CAPTURE(path); + vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1}; + REQUIRE(locked->ScndCtrlResistiveLock); + REQUIRE(locked->ScndCtrlPosNo > 0); + auto const resistancefree{resistance_free_position(locked.mover())}; + REQUIRE(resistancefree > 1); + if (resistancefree <= 1) { + continue; // not reached, the REQUIRE above ends the test; tells the static analysis the index below is in range + } + REQUIRE(locked->RList[resistancefree - 1].R >= 0.01); + + SUBCASE("zero") { + controllers_at(locked, 0); + CHECK(locked->IsScndCtrlLockedByMainCtrl()); + CHECK_FALSE(locked->IncScndCtrl(1)); + CHECK_FALSE(locked->IncScndCtrl(2)); + CHECK(locked->ScndCtrlPos == 0); + } + SUBCASE("resistive positions") { + for (auto position{1}; position < resistancefree; ++position) { + CAPTURE(position); + controllers_at(locked, position); + CHECK_FALSE(locked->IncScndCtrl(1)); + CHECK(locked->ScndCtrlPos == 0); + } + } + SUBCASE("every resistance-free position") { + for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.mover(), position)) { + CAPTURE(position); + controllers_at(locked, position); + CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl()); + CHECK(locked->IncScndCtrl(1)); + CHECK(locked->ScndCtrlPos == 1); + } + } + SUBCASE("the shunt goes down on a resistance-free position") { + controllers_at(locked, resistancefree); + REQUIRE(locked->IncScndCtrl(1)); + REQUIRE(locked->IncScndCtrl(1)); + CHECK(locked->DecScndCtrl(1)); + CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->DecScndCtrl(2)); + CHECK(locked->ScndCtrlPos == 0); + } + SUBCASE("the shunt doesn't go down on a resistive position either") { + // a state the lock doesn't let arise (see below), set by hand to check the controller alone + controllers_at(locked, resistancefree - 1); + locked->ScndCtrlPos = 1; + CHECK(locked->IsScndCtrlLockedByMainCtrl()); + CHECK_FALSE(locked->DecScndCtrl(1)); + CHECK_FALSE(locked->DecScndCtrl(2)); + CHECK(locked->ScndCtrlPos == 1); + } + SUBCASE("the master controller taken back from a shunt step drops the shunt") { + controllers_at(locked, resistancefree); + REQUIRE(locked->IncScndCtrl(1)); + if (locked->TrainType == dt_ET22) { + // the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before + CHECK_FALSE(locked->DecMainCtrl(1)); + CHECK(locked->MainCtrlPos == resistancefree); + CHECK(locked->DecScndCtrl(1)); + } + CHECK(locked->DecMainCtrl(1)); + CHECK(locked->MainCtrlPos == resistancefree - 1); + CHECK(locked->ScndCtrlPos == 0); + // and the master controller goes on down to zero, nothing left locked + while (locked->MainCtrlPos > 0 && locked->DecMainCtrl(1)) { + } + CHECK(locked->MainCtrlPos == 0); + } + SUBCASE("the master controller set directly (AI, consist) drops the shunt in the next update") { + controllers_at(locked, resistancefree); + REQUIRE(locked->IncScndCtrl(1)); + locked->MainCtrlPos = resistancefree - 1; + locked.step(); + CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->MainCtrlPos == resistancefree - 1); + } + SUBCASE("the master controller moved up from a shunt step onto a resistive position drops the shunt") { + // the last series position, followed by the resistive parallel ones + auto lastseries{0}; + for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.mover(), position)) { + if (locked->RList[position + 1].R >= 0.01) { + lastseries = position; + break; + } + } + REQUIRE(lastseries > 0); + controllers_at(locked, lastseries); + locked->DirActive = 1; + REQUIRE(locked->IncScndCtrl(1)); + if (locked->TrainType == dt_ET22) { + CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before + CHECK(locked->ScndCtrlPos == 1); + } + else { + CHECK(locked->IncMainCtrl(1)); + CHECK(locked->MainCtrlPos == lastseries + 1); + CHECK(locked->ScndCtrlPos == 0); + } + } + } +} + +TEST_CASE("cntrl: without ScndCtrlResistiveLock the field shunting engages on any position, as before") { + for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) { + CAPTURE(path); + vehicle unlocked{definition::fiz(path), 0.0, "test", 1}; + CHECK_FALSE(unlocked->ScndCtrlResistiveLock); + for (auto const position : {0, 1}) { + CAPTURE(position); + controllers_at(unlocked, position); + CHECK_FALSE(unlocked->IsScndCtrlLockedByMainCtrl()); + CHECK(unlocked->IncScndCtrl(1)); + CHECK(unlocked->ScndCtrlPos == 1); + } + } +} diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index c5aa2fff7..4f55ce0b8 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -113,3 +113,93 @@ TEST_CASE("compressor: without a pressure switch the air over the cut-out pressu REQUIRE(vehicle->CompressorFlag); // nothing stops it CHECK(vehicle->CompressedVolume < 8.5 * 0.81); // a fifth of the air let out } + +TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { + auto vehicle{compressor_vehicle(30.0)}; + vehicle->Mains = true; // engine started + run_compressor(vehicle, 20.0); + REQUIRE_FALSE(vehicle->CompressorFlag); + + vehicle->Mains = false; // engine stopped, 10 s short of the delay + run_compressor(vehicle, 1.0); + vehicle->Mains = true; + run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one + CHECK_FALSE(vehicle->CompressorFlag); + + run_compressor(vehicle, 15.1); + CHECK(vehicle->CompressorFlag); +} + +TEST_CASE("compressor: the start delay holds back a compressor switched on by hand too") { + auto vehicle{compressor_vehicle(30.0)}; + vehicle->CompressorStart = start_t::manual; + vehicle->CompressorAllow = true; // switch in the cabinet on before the engine start + vehicle->Mains = true; + + run_compressor(vehicle, 29.9); + CHECK_FALSE(vehicle->CompressorFlag); + run_compressor(vehicle, 0.2); + CHECK(vehicle->CompressorFlag); +} + +TEST_CASE("compressor: the start delay is read from the brake section") { + auto const delay{[](std::string const &Section) { + return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->CompressorStartDelay; + }}; + CHECK(delay("Brake") == doctest::Approx(30.0)); + CHECK(delay("Cntrl") == doctest::Approx(0.0)); // the key isn't taken from the control section +} + +namespace { + +// 401Da: the compressor runs from the 110 V of the auxiliary generator driven by the engine, here the converter +// started with the main circuit, which gets up to voltage the converter start delay after the engine start +definition generator_vehicle(double const ConverterDelay, double const CompressorDelay) { + return definition::load("cab_vehicle") + .set("Param", "PWR", 370) + .set("Light", "Light", "Generator") + .set("Light", "LMaxVoltage", 110) + .set("Brake", "Vv", 0.6) + .set("Brake", "MinCP", 6.5) + .set("Brake", "MaxCP", 8.0) + .set("Brake", "CompressorSpeed", 0.003) + .set("Brake", "CompressorPower", "Converter") + .set("Brake", "CompressorStartDelay", CompressorDelay) + .set("Cntrl", "CompressorStart", "Automatic") + .set("Cntrl", "ConverterStart", "Automatic") + .set("Cntrl", "ConverterStartDelay", ConverterDelay); +} + +} // namespace + +TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { + vehicle loco{generator_vehicle(30.0, 0.0)}; + REQUIRE(loco->CompressorPower == 2); + REQUIRE(loco->ConverterStartDelay == doctest::Approx(30.0)); + + loco.run(1.0); // engine off + CHECK_FALSE(loco->Power110vIsAvailable); + + loco->Mains = true; // engine started + loco.run(25.0); + CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->CompressorFlag); + + loco.run(10.0); + CHECK(loco->Power110vIsAvailable); + CHECK(loco->CompressorFlag); +} + +TEST_CASE("compressor: fed from the converter the start delay counts from the converter voltage") { + vehicle loco{generator_vehicle(20.0, 10.0)}; + REQUIRE(loco->CompressorStartDelay == doctest::Approx(10.0)); + + loco.run(1.0); // engine off + loco->Mains = true; // engine started + loco.run(25.0); + REQUIRE(loco->Power110vIsAvailable); // the converter is up + CHECK_FALSE(loco->CompressorFlag); // but the compressor waits for its own delay as well + + loco.run(10.0); + CHECK(loco->CompressorFlag); +} diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index 2a0ff6e50..bbb1c0dd9 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -525,3 +525,130 @@ TEST_CASE("couplers: a collision of coupled vehicles keeps the momentum of the p CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) > 13.5); CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) < 15.05 + 1e-6); } + +// eu07/maszyna#520: an electric and a diesel locomotive got their control coupled (multiple-unit control) when the +// scenario or the Starter asked for it, or when the couplers let it through, as a Vectron and an SM42 did + +namespace { + +// the given setting of the control coupling check for the test, restored after it +class control_coupling_check_setting { +public: + explicit control_coupling_check_setting(bool Enabled) { Global.control_coupling_engine_check = Enabled; } + ~control_coupling_check_setting() { Global.control_coupling_engine_check = m_previous; } + control_coupling_check_setting(control_coupling_check_setting const &) = delete; + control_coupling_check_setting &operator=(control_coupling_check_setting const &) = delete; + +private: + bool m_previous{Global.control_coupling_engine_check}; +}; + +constexpr int scenario_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + +// couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the +// first one only), returns the coupling the pair got +int scenario_couple(vehicle &First, vehicle &Second, int Coupling = scenario_coupling) { + REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), Coupling, true, false)); + CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag); + return First->Couplers[end::rear].CouplingFlag; +} + +} // namespace + +TEST_CASE("couplers: an electric and a diesel locomotive don't share their control") { + control_coupling_check_setting const check{true}; + // the E6ACT names no control system (ControlType), as the Vectron doesn't; the SM42 names its own, the SM03 none + auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}}; + REQUIRE(electric->EngineType == TEngineType::ElectricInductionMotor); + + SUBCASE("a diesel-electric one with its own control system") { + auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; + REQUIRE(diesel->EngineType == TEngineType::DieselElectric); + CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); + CHECK(scenario_couple(electric, diesel) == (scenario_coupling & ~coupling::control)); + } + SUBCASE("a diesel-mechanical one without a control system named, either") { + auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; + REQUIRE(diesel->EngineType == TEngineType::DieselEngine); + CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear)); + CHECK(scenario_couple(diesel, electric) == (scenario_coupling & ~coupling::control)); + } + SUBCASE("unless both name the same control system") { + auto diesel{vehicle{definition::fiz("sm03_v1/sm03").set("BuffCoupl", "ControlType", "shared"), 0.0, "diesel"}}; + auto shared{vehicle{definition::fiz("e6act_v2/e6acta").set("BuffCoupl", "ControlType", "shared"), 0.0, "electric"}}; + CHECK(scenario_couple(shared, diesel) == scenario_coupling); + } + SUBCASE("unless the vehicles make one unit, coupled for good") { + auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; + auto const forgood{scenario_coupling | coupling::permanent}; + CHECK(scenario_couple(electric, diesel, forgood) == forgood); + } + SUBCASE("unless the check is turned off") { + control_coupling_check_setting const off{false}; + auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; + CHECK(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); + CHECK(scenario_couple(electric, diesel) == scenario_coupling); + } +} + +TEST_CASE("couplers: locomotives of the same traction and the cars keep their control coupling") { + control_coupling_check_setting const check{true}; + + SUBCASE("two locomotives or motor cars of the same traction") { + // two electric ones, an electric one of each motor type, two diesel ones, a diesel-mechanical and a + // diesel-electric one, an electric multiple unit's control trailer and its motor car + std::initializer_list> const pairs{ + {"ep09_v2/104e", "et22_v3/201e-w"}, + {"e6act_v2/e6acta", "eu04_v1/eu04-01"}, + {"sm03_v1/sm03", "wmb10_v1/wmb10"}, + {"sm03_v1/sm03", "st44_v2/m62-1151"}, + {"en57_v1/5bgb", "en57_v1/6bai"}}; + for (auto const &paths : pairs) { + CAPTURE(paths.first); + CAPTURE(paths.second); + auto first{vehicle{definition::fiz(paths.first), 0.0, "first"}}; + auto second{vehicle{definition::fiz(paths.second), 0.0, "second"}}; + CHECK(scenario_couple(first, second) == scenario_coupling); + } + } + SUBCASE("a diesel locomotive and a car") { + auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; + auto car{vehicle{definition::load("wagon"), 0.0, "car"}}; + CHECK(scenario_couple(diesel, car) == scenario_coupling); + } +} + +TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive couple without the control connection") { + crash_damage_setting const crashdamage{true}; + control_coupling_check_setting const check{true}; + auto const flag{coupling::coupler | coupling::brakehose | coupling::control}; + auto automatic = [flag](std::string const &Path) { + return definition::fiz(Path).set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", flag); + }; + auto moving{vehicle{automatic("e6act_v2/e6acta"), 5.0, "moving"}}; + + SUBCASE("a diesel one") { + auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(couple_during(pair, 3.0)); + CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose)); + } + SUBCASE("an electric one") { + auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(couple_during(pair, 3.0)); + CHECK(pair.coupling() == flag); + } +} + +TEST_CASE("couplers: the AI and the player get the coupling the vehicles can take") { + control_coupling_check_setting const check{true}; + auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}}; + auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; + auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}}; + + CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == (scenario_coupling & ~coupling::control)); + CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling); + // nothing to take away without the control connection asked for + CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, coupling::coupler) == coupling::coupler); +} diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index 07686dc10..c4ea147d3 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -177,3 +177,32 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); scenario.check(); } + +TEST_CASE("diesel: the SM42's shunt mode, switched on and off with one move of the switch") { + // eu07/maszyna#497: the shunt mode of the diesel-electrics (ShuntMode=1) shares its switch with the motor + // overload relay threshold of the electric locomotives (CurrentSwitch()). the SM42 has no such relay, so + // the switch sets the shunt mode at the first move, at the controller's zero position only + scenario scenario{"diesel/sm42 shunt mode", motion() + traction(), test::track{}}; + scenario.add("sm42_v1/6d1", 1); + REQUIRE(scenario.start_up()); + auto &sm42{scenario.cab()}; + REQUIRE(sm42.ShuntModeAllow); + CHECK_FALSE(sm42.ShuntMode); + scenario.act("shunt mode on"); + CHECK(sm42.CurrentSwitch(true)); + CHECK(sm42.ShuntMode); + scenario.get_going(); + scenario.act("shunting power"); + sm42.AnPos = 0.5; + CHECK(sm42.IncMainCtrl(1)); + scenario.wait(60.0); + CHECK(sm42.Vel > 1.0); + // not with the controller out of its zero position + CHECK_FALSE(sm42.CurrentSwitch(false)); + CHECK(sm42.ShuntMode); + scenario.notch_back(0); + scenario.act("shunt mode off"); + CHECK(sm42.CurrentSwitch(false)); + CHECK_FALSE(sm42.ShuntMode); + scenario.check(); +} diff --git a/tests/unit/test_dimmer.cpp b/tests/unit/test_dimmer.cpp new file mode 100644 index 000000000..d4d2e2663 --- /dev/null +++ b/tests/unit/test_dimmer.cpp @@ -0,0 +1,112 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the headlight dimmer's position indexes the DimmerList of the .fiz. a short or an empty list, or a DefaultPos +// past its end, put the dimmer outside the list, where the lights and the cab read past the end of it + +namespace { + +// rows: high beam, dimmed, off +nlohmann::ordered_json const plain{"no", "no", "no"}; +nlohmann::ordered_json const dimmed{"no", "yes", "no"}; +nlohmann::ordered_json const off{"no", "no", "yes"}; + +definition dimmer_list(nlohmann::ordered_json const &Rows, int const Defaultposition, bool const Cycle = false) { + return definition::load("cab_vehicle") + .set("DimmerList", "rows", Rows) + .set("DimmerList", "Size", static_cast(Rows.size())) + .set("DimmerList", "DefaultPos", Defaultposition) + .set("DimmerList", "Cycle", Cycle ? "yes" : "no"); +} + +} // namespace + +TEST_CASE("dimmer: a position outside the list reads as a plain one, neither off nor dimmed") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({off, dimmed}), 0)}; + REQUIRE(cab->dimPositions.size() == 2); + + for (auto const position : {-1, 2, 100}) { + CAPTURE(position); + cab->modernDimmerPosition = position; + auto const entry{cab->currentDimPosition()}; + CHECK_FALSE(entry.isOff); + CHECK_FALSE(entry.isDimmed); + CHECK_FALSE(entry.isHighBeam); + } + cab->modernDimmerPosition = 0; + CHECK(cab->currentDimPosition().isOff); + cab->modernDimmerPosition = 1; + CHECK(cab->currentDimPosition().isDimmed); +} + +TEST_CASE("dimmer: positions are clamped to the list") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; + + CHECK(cab->clampDimmerPosition(-3) == 0); + CHECK(cab->clampDimmerPosition(1) == 1); + CHECK(cab->clampDimmerPosition(3) == 2); + CHECK(cab->clampDimmerPosition(100) == 2); +} + +TEST_CASE("dimmer: a DefaultPos past the end of the list starts the dimmer at its last position") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7)}; + + CHECK(cab->modernDimmerDefaultPosition == 1); + // the cab puts the modern dimmer to its default position when it's entered (TTrain::set_cab_controls()) + cab->modernDimmerPosition = cab->modernDimmerDefaultPosition; + CHECK(cab->currentDimPosition().isDimmed); +} + +TEST_CASE("dimmer: without the modern dimmer a DefaultPos past the end of the list puts the dimmer at its last position") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7).set("Switches", "ModernDimmer", "No")}; + REQUIRE_FALSE(cab->enableModernDimmer); + + CHECK(cab->modernDimmerPosition == 1); + CHECK(cab->currentDimPosition().isDimmed); +} + +TEST_CASE("dimmer: an empty list leaves the dimmer at 0, reading as a plain position, and it doesn't move") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array(), 3, true)}; + REQUIRE(cab->dimPositions.empty()); + + CHECK(cab->modernDimmerDefaultPosition == 0); + CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->clampDimmerPosition(1) == 0); + CHECK_FALSE(cab->currentDimPosition().isOff); + CHECK_FALSE(cab->stepDimmerPosition(1)); + CHECK_FALSE(cab->stepDimmerPosition(-1)); + CHECK(cab->modernDimmerPosition == 0); +} + +TEST_CASE("dimmer: stepping stays within the list") { + SUBCASE("without cycling it stops at the ends") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; + CHECK_FALSE(cab->stepDimmerPosition(-1)); + CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->stepDimmerPosition(1)); + CHECK(cab->stepDimmerPosition(1)); + CHECK(cab->modernDimmerPosition == 2); + CHECK_FALSE(cab->stepDimmerPosition(1)); + CHECK(cab->modernDimmerPosition == 2); + } + SUBCASE("with cycling it goes around to the other end") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0, true)}; + CHECK(cab->stepDimmerPosition(-1)); + CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->stepDimmerPosition(1)); + CHECK(cab->modernDimmerPosition == 0); + } + SUBCASE("a position past the end steps from the last one") { + vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; + cab->modernDimmerPosition = 9; + CHECK(cab->stepDimmerPosition(-1)); + CHECK(cab->modernDimmerPosition == 1); + cab->modernDimmerPosition = 9; + CHECK(cab->stepDimmerPosition(1)); // can't go further, but comes back into the list + CHECK(cab->modernDimmerPosition == 2); + } +} diff --git a/tests/unit/test_door_closure.cpp b/tests/unit/test_door_closure.cpp new file mode 100644 index 000000000..c92d8fef8 --- /dev/null +++ b/tests/unit/test_door_closure.cpp @@ -0,0 +1,158 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "vehicle.h" + +// the door closure signalling (SOD, the i-door_blocked lamp of a cab): the state of each vehicle's doors and of the +// whole train, the most severe of its vehicles, as the driver gathers it for the lamp (eu07/maszyna#288) + +using test::scenario; +using test::definition; +using test::vehicle; +using namespace test::channels; + +namespace { + +// the state of the whole train, the way TController::determine_consist_state() gathers it +door_closure_t consist_closure(scenario &Scenario) { + auto closure{door_closure_t::none}; + for (std::size_t i = 0; i < Scenario.train().size(); ++i) { + closure = std::max(closure, Scenario.vehicle(i).door_closure()); + } + return closure; +} + +} // namespace + +TEST_CASE("door closure: the lamp is lit for locked doors, blinks for released ones and is dark for open ones") { + for (auto const lit : {true, false}) { + CAPTURE(lit); + CHECK(door_closure_lamp(door_closure_t::locked, lit)); + CHECK(door_closure_lamp(door_closure_t::released, lit) == lit); + CHECK_FALSE(door_closure_lamp(door_closure_t::open, lit)); + CHECK_FALSE(door_closure_lamp(door_closure_t::none, lit)); + } + // a consist takes the most severe state of its vehicles + CHECK(std::max(door_closure_t::none, door_closure_t::locked) == door_closure_t::locked); + CHECK(std::max(door_closure_t::locked, door_closure_t::released) == door_closure_t::released); + CHECK(std::max(door_closure_t::released, door_closure_t::open) == door_closure_t::open); +} + +TEST_CASE("door closure: a unit with permits, locked, released by the permit and open, in any of its cars") { + scenario scenario{"door closure/elf", motion() + doors()}; + scenario.add("elf_v1/21we-a", 1).add("elf_v1/21we-b").add("elf_v1/21we-c"); + scenario.start_up(); + auto &cab{scenario.cab()}; + auto &last{scenario.vehicle(scenario.train().size() - 1)}; + // closed with no permit: no door can be opened + CHECK(cab.door_closure() == door_closure_t::locked); + CHECK(last.door_closure() == door_closure_t::locked); + CHECK(consist_closure(scenario) == door_closure_t::locked); + + scenario.act("permit left"); + cab.PermitDoors(side::left, true); + scenario.wait(2.0); + CHECK(last.door_closure() == door_closure_t::released); + CHECK(consist_closure(scenario) == door_closure_t::released); + + scenario.act("the last car opens its own door"); + last.OperateDoors(side::left, true, range_t::local); + scenario.wait(5.0); + // the cab's own doors stay closed, the train is open all the same + CHECK(cab.door_closure() == door_closure_t::released); + CHECK(last.door_closure() == door_closure_t::open); + CHECK(consist_closure(scenario) == door_closure_t::open); + + scenario.act("close, the steps stay out under the permit"); + last.OperateDoors(side::left, false, range_t::local); + cab.OperateDoors(side::left, false); + scenario.wait(10.0); + CHECK(last.Doors.instances[side::left].position <= 0.f); + // a step out isn't a closed door + CHECK(consist_closure(scenario) == door_closure_t::open); + + scenario.act("revoke the permit"); + cab.PermitDoors(side::left, false); + scenario.wait(10.0); + CHECK(consist_closure(scenario) == door_closure_t::locked); +} + +TEST_CASE("door closure: the doors of a unit without permits are released at a standstill") { + scenario scenario{"door closure/en57", motion() + doors()}; + scenario.add("en57_v1/5bgaiii_led_spot", 1).add("en57_v1/6ba_840").add("en57_v1/5bgb"); + scenario.start_up(); + auto &cab{scenario.cab()}; + auto &middle{scenario.vehicle(1)}; + REQUIRE_FALSE(cab.Doors.permit_needed); + REQUIRE(middle.Doors.permit_needed); + // the door lock engages only once the train runs (DoorLockSpeed), till then the end cars' doors can be opened + CHECK(cab.door_closure() == door_closure_t::released); + CHECK(middle.door_closure() == door_closure_t::locked); + CHECK(consist_closure(scenario) == door_closure_t::released); + scenario.act("open right"); + cab.OperateDoors(side::right, true); + scenario.wait(10.0); + CHECK(consist_closure(scenario) == door_closure_t::open); + scenario.act("close right"); + cab.OperateDoors(side::right, false); + scenario.wait(10.0); + CHECK(consist_closure(scenario) == door_closure_t::released); +} + +TEST_CASE("door closure: a locomotive has no doors to signal, its coach does") { + scenario scenario{"door closure/eu07 with a coach", motion() + doors()}; + scenario.add("4e_v1/4e", 1).add("bdhpumn_v3/bdhpumn"); + scenario.start_up(); + CHECK(scenario.cab().door_closure() == door_closure_t::none); + scenario.act("open right"); + scenario.cab().PermitDoors(side::right, true); + scenario.cab().OperateDoors(side::right, true); + scenario.wait(10.0); + CHECK(scenario.vehicle(1).door_closure() == door_closure_t::open); + CHECK(consist_closure(scenario) == door_closure_t::open); +} + +TEST_CASE("door closure: the signalling is switched on by DoorClosureSignal in the Doors section, off without it") { + SUBCASE("without the key") { + vehicle wagon{definition::load("wagon")}; + CHECK_FALSE(wagon->Doors.closure_signal); + } + SUBCASE("with the key") { + vehicle wagon{definition::load("wagon").set("Doors", "DoorClosureSignal", "Yes")}; + CHECK(wagon->Doors.closure_signal); + } +} + +TEST_CASE("door closure: without DoorClosureSignal the lamp shows the lock of the vehicle's own doors, as before") { + vehicle wagon{definition::load("wagon")}; + REQUIRE_FALSE(wagon->Doors.closure_signal); + for (auto const locked : {true, false}) { + wagon->Doors.is_locked = locked; + for (auto const consist : {door_closure_t::none, door_closure_t::locked, door_closure_t::released, door_closure_t::open}) { + for (auto const lit : {true, false}) { + CAPTURE(locked); + CAPTURE(static_cast(consist)); + CAPTURE(lit); + // no blinking at a standstill with the doors closed, whatever the consist does + CHECK(wagon->door_closure_lamp_lit(consist, lit) == locked); + } + } + } +} + +TEST_CASE("door closure: with DoorClosureSignal the lamp shows the consist in three states") { + vehicle wagon{definition::load("wagon").set("Doors", "DoorClosureSignal", "Yes")}; + REQUIRE(wagon->Doors.closure_signal); + for (auto const locked : {true, false}) { + // the vehicle's own lock doesn't matter, the consist does + wagon->Doors.is_locked = locked; + for (auto const lit : {true, false}) { + CAPTURE(locked); + CAPTURE(lit); + CHECK(wagon->door_closure_lamp_lit(door_closure_t::locked, lit)); + CHECK(wagon->door_closure_lamp_lit(door_closure_t::released, lit) == lit); + CHECK_FALSE(wagon->door_closure_lamp_lit(door_closure_t::open, lit)); + CHECK_FALSE(wagon->door_closure_lamp_lit(door_closure_t::none, lit)); + } + } +} diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp new file mode 100644 index 000000000..290260f6a --- /dev/null +++ b/tests/unit/test_door_wings.cpp @@ -0,0 +1,54 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/doorwings.h" + +// the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low +// poly interior get the same pose, worked out once from the door position of the mover + +TEST_CASE("door wings: only the door animations move wings") { + CHECK(door_wings::is_wing(0x010)); // TAnim::TypeSet for the doors + CHECK_FALSE(door_wings::is_wing(0x000)); // axles + CHECK_FALSE(door_wings::is_wing(0x055)); // pantographs, five submodels + CHECK_FALSE(door_wings::is_wing(0x070)); // doorsteps + CHECK_FALSE(door_wings::is_wing(0x080)); // mirrors + CHECK(door_wings::is_wing(0x210)); // the parameter count in the upper bits doesn't matter +} + +TEST_CASE("door wings: odd wings are on the left, even ones on the right") { + CHECK_FALSE(door_wings::on_right_side(1)); + CHECK(door_wings::on_right_side(2)); + CHECK_FALSE(door_wings::on_right_side(3)); + CHECK(door_wings::on_right_side(4)); +} + +TEST_CASE("door wings: a sliding wing shifts along the vehicle by the door position") { + CHECK(door_wings::slide(0.f) == glm::vec3(0.f, 0.f, 0.f)); + CHECK(door_wings::slide(0.65f) == glm::vec3(0.f, 0.f, 0.65f)); +} + +TEST_CASE("door wings: a plug wing goes out first, then slides") { + auto const rangeout{0.1f}; + // closed + CHECK(door_wings::plug(0.f, rangeout) == glm::vec3(0.f, 0.f, 0.f)); + // still going out, and not sliding yet + auto const out{door_wings::plug(0.02f, rangeout)}; + CHECK(out.x == doctest::Approx(0.04f)); + CHECK(out.z == 0.f); + // out as far as it goes, sliding by what the position has beyond half of the way out + auto const open{door_wings::plug(0.7f, rangeout)}; + CHECK(open.x == rangeout); + CHECK(open.y == 0.f); + CHECK(open.z == doctest::Approx(0.65f)); +} + +TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as far the other way") { + auto const angles{door_wings::fold(40.f)}; + CHECK(angles.smaller == 40.f); + CHECK(angles.larger == -80.f); + CHECK(angles.step == 40.f); + auto const closed{door_wings::fold(0.f)}; + CHECK(closed.smaller == 0.f); + CHECK(closed.larger == 0.f); + CHECK(closed.step == 0.f); +} diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp new file mode 100644 index 000000000..9230330f4 --- /dev/null +++ b/tests/unit/test_engine_shutdown.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +// stopping the engine of a diesel shunter like the SM03 (eu07/maszyna#427): its fuel pump starts on its own with the +// engine and the engine runs the converter which feeds the low voltage circuit, so neither the fuel pump switch nor the +// battery switch stop it. the cab has only the starter button, and the command opening the main circuit has to stop it + +namespace { + +// the shunter with its engine started from the cab and idling +test::vehicle running_shunter() { + test::vehicle shunter{test::definition::load("diesel_shunter")}; + shunter->CabOccupied = 1; + shunter->CabActivisation(); + shunter->BatterySwitch(true); + shunter->OilPumpSwitch(true); + shunter.run(20.0); // the oil pressure builds up + shunter->MainSwitch(true); + shunter.run(15.0); + return shunter; +} + +} // namespace + +TEST_CASE("engine shutdown: the shunter starts with the starter button") { + auto shunter{running_shunter()}; + REQUIRE(shunter->EngineType == TEngineType::DieselEngine); + REQUIRE(shunter->FuelPump.start_type == start_t::automatic); + CHECK(shunter->Mains); + CHECK(shunter->FuelPump.is_active); + CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); +} + +TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch stop the engine") { + auto shunter{running_shunter()}; + shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch + shunter.run(10.0); + CHECK(shunter->Mains); + shunter->BatterySwitch(false); + shunter.run(10.0); + CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump + CHECK(shunter->Mains); + CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); +} + +TEST_CASE("engine shutdown: the command opening the main circuit stops the engine and it stays stopped") { + auto shunter{running_shunter()}; + REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button + CHECK(shunter->MainSwitch(false)); + shunter.run(20.0); + CHECK_FALSE(shunter->Mains); + CHECK_FALSE(shunter->FuelPump.is_active); + CHECK(shunter->enrot == 0.0); +} + +TEST_CASE("engine shutdown: the engine starts again after it was stopped") { + auto shunter{running_shunter()}; + shunter->MainSwitch(false); + shunter.run(20.0); + REQUIRE(shunter->enrot == 0.0); + shunter->MainSwitch(true); + shunter.run(15.0); + CHECK(shunter->Mains); + CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); +} + +TEST_CASE("engine shutdown: vehicles without a diesel keep ignoring the command with only the button closing the circuit") { + test::vehicle wagon{test::definition::load("wagon")}; + CHECK_FALSE(wagon->MainCircuitOpensWithStarterOnly()); + test::vehicle electric{test::definition::load("wagon").set("Engine", "EngineType", "ElectricSeriesMotor")}; + REQUIRE(electric->EngineType == TEngineType::ElectricSeriesMotor); + CHECK_FALSE(electric->MainCircuitOpensWithStarterOnly()); +} diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp new file mode 100644 index 000000000..c721e5a1a --- /dev/null +++ b/tests/unit/test_engine_start.cpp @@ -0,0 +1,298 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" + +#include "vehicle/enginestart.h" + +// starting the engines of the vehicles in multiple from the cab (eu07/maszyna#80): the cab's own switch (main_*) works +// all of them unless Engine:JointEngineStart=No keeps it to its own vehicle, and the switches mainb_* and mainc_* start +// the second and the third vehicle alone. the cab (TTrain) passes the vehicle's MainSwitchRange() to its MainSwitch(), +// finds the vehicles with engine(), and runs remote_switch for the switches of the others + +using test::consist; +using test::definition; + +namespace { + +// the SN61 railcar, whose cab has a set of switches for each of up to three railcars in multiple +definition sn61(bool const Joint = true) { + auto railcar{definition::fiz("sn61_v2/sn61")}; + if (false == Joint) { + railcar.set("Engine", "JointEngineStart", "No"); + } + return railcar; +} + +// the battery, the cab and the pumps of every railcar of the train switched on from the first one's cab, the oil +// pressure built up, and the controller at the first position giving the engines fuel, which a mechanical diesel +// starts at: everything but the engines ready to start +void prepare(consist &Train) { + auto &cab{Train[0].mover()}; + cab.BatterySwitch(true); + cab.CabActivisation(); + cab.OilPumpSwitch(true); + cab.FuelPumpSwitch(true); + while (cab.RList[cab.MainCtrlPos].R == 0.0 && cab.IncMainCtrl(1)) { + // up to the first position with fuel + } + Train.run(20.0); +} + +bool running(TMoverParameters const &Vehicle) { + return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.dizel_nmin; +} + +// the time step of the train in the loops below +auto const dt{0.01}; + +// the count of the steps of dt making up Seconds +int steps(double const Seconds) { + return static_cast(std::lround(Seconds / dt)); +} + +// the switch of Engine held closed for Seconds, then let go, in steps of the train +void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters *Engine, double const Seconds, bool const Closesonrelease = false) { + for (auto step = 0; step < steps(Seconds); ++step) { + Switch.update(Engine, true, false, dt, Closesonrelease); + Train.step({}, dt); + } + Switch.update(Engine, false, false, dt, Closesonrelease); +} + +} // namespace + +TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No keeps the cab's switch to its vehicle") { + consist train; + auto const &joint{train.add(sn61(), 1).mover()}; + auto const &separate{train.add(sn61(false)).mover()}; + CHECK(joint.JointEngineStart); + CHECK_FALSE(separate.JointEngineStart); + CHECK(joint.MainSwitchRange() == range_t::consist); + CHECK(separate.MainSwitchRange() == range_t::local); +} + +TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own one, those behind the cab first") { + consist train; + auto &first{train.add(sn61(), 1).mover()}; + auto &second{train.add(sn61()).mover()}; + auto &third{train.add(sn61()).mover()}; + CHECK(engine_start::engine(first, first, 1) == &first); + CHECK(engine_start::engine(first, first, 2) == &second); + CHECK(engine_start::engine(first, first, 3) == &third); + CHECK(engine_start::engine(first, first, 4) == nullptr); + CHECK(engine_start::engine(first, first, 0) == nullptr); + // from the rear cab of the first railcar the others are in front of the cab, in the same order + first.CabOccupied = -1; + CHECK(engine_start::engine(first, first, 2) == &second); + CHECK(engine_start::engine(first, first, 3) == &third); + // from the middle one, the one behind its cab comes first + second.CabOccupied = 1; + CHECK(engine_start::engine(second, second, 2) == &third); + CHECK(engine_start::engine(second, second, 3) == &first); + second.CabOccupied = -1; + CHECK(engine_start::engine(second, second, 2) == &first); + CHECK(engine_start::engine(second, second, 3) == &third); +} + +TEST_CASE("engine start: only the vehicles with an engine and under control through the cable count") { + consist train; + auto &first{train.add(sn61(), 1).mover()}; + // a vehicle without an engine between the railcars is passed over + auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).mover()}; + auto &second{train.add(sn61()).mover()}; + REQUIRE(trailer.Power < 0.01); + CHECK(engine_start::engine(first, first, 2) == &second); + // the vehicle with the cab doesn't drive itself: its engine is in the vehicle it controls, which isn't counted twice + trailer.CabOccupied = 1; + CHECK(engine_start::engine(trailer, first, 1) == &first); + CHECK(engine_start::engine(trailer, first, 2) == &second); + CHECK(engine_start::engine(trailer, first, 3) == nullptr); + + // coupled without the control cable, the other railcar isn't under the cab's control + consist apart; + auto &alone{apart.add(sn61(), 1).mover()}; + apart.add(sn61(), 0, coupling::coupler | coupling::brakehose); + CHECK(engine_start::engine(alone, alone, 2) == nullptr); +} + +TEST_CASE("engine start: by default the cab's switch starts and stops the engines of all the vehicles in multiple") { + consist train; + auto &first{train.add(sn61(), 1).mover()}; + auto const &second{train.add(sn61()).mover()}; + prepare(train); + REQUIRE_FALSE(first.Mains); + REQUIRE_FALSE(second.Mains); + first.MainSwitch(true, first.MainSwitchRange()); + train.run(15.0); + CHECK(running(first)); + CHECK(running(second)); + first.MainSwitch(false, first.MainSwitchRange()); + train.run(5.0); + CHECK_FALSE(first.Mains); + CHECK_FALSE(second.Mains); +} + +TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") { + consist train; + auto &first{train.add(sn61(false), 1).mover()}; + auto &second{train.add(sn61(false)).mover()}; + auto &third{train.add(sn61(false)).mover()}; + prepare(train); + // the cab's own switch starts its own engine only + first.MainSwitch(true, first.MainSwitchRange()); + train.run(15.0); + REQUIRE(running(first)); + CHECK_FALSE(second.Mains); + CHECK_FALSE(third.Mains); + + // the second one's switch, mainb_*, starts the second engine + engine_start::remote_switch switchb; + engine_start::remote_switch switchc; + auto *engineb{engine_start::engine(first, first, 2)}; + auto *enginec{engine_start::engine(first, first, 3)}; + REQUIRE(engineb == &second); + REQUIRE(enginec == &third); + hold(train, switchb, engineb, 2.0); // past the SN61's delay of 1.5 s + train.run(15.0); + CHECK(running(second)); + CHECK_FALSE(third.Mains); + // and the third one's, mainc_*, the third + hold(train, switchc, enginec, 2.0); + train.run(15.0); + CHECK(running(third)); + + // the switches open their own vehicles' circuits only + CHECK(engine_start::remote_switch::open(second)); + train.run(5.0); + CHECK_FALSE(second.Mains); + CHECK(running(first)); + CHECK(running(third)); + first.MainSwitch(false, first.MainSwitchRange()); + train.run(5.0); + CHECK_FALSE(first.Mains); + CHECK(running(third)); + CHECK_FALSE(engine_start::remote_switch::open(second)); // already stopped +} + +TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's delay, with the vehicle ready") { + consist train; + train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0"), 1); + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).mover()}; + REQUIRE(second.InitialCtrlDelay == doctest::Approx(2.0)); + engine_start::remote_switch switchb; + + // without the battery the switch does nothing, however long it's held + hold(train, switchb, &second, 5.0); + train.run(5.0); + CHECK_FALSE(second.Mains); + CHECK_FALSE(second.dizel_startup); + + prepare(train); + // let go too early + hold(train, switchb, &second, 1.0); + CHECK_FALSE(engine_start::remote_switch::is_running(second)); + // the switch opening the circuit held along, the closing one does nothing + for (auto step = 0; step < steps(3.0); ++step) { + switchb.update(&second, true, true, dt, false); + train.step({}, dt); + } + CHECK_FALSE(engine_start::remote_switch::is_running(second)); + // held long enough + hold(train, switchb, &second, 2.5); + CHECK(engine_start::remote_switch::is_running(second)); + train.run(15.0); + CHECK(running(second)); +} + +TEST_CASE("engine start: a switch closing on release, as an electric locomotive's impulse switch, waits to be let go") { + consist train; + train.add(sn61(false), 1); + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).mover()}; + prepare(train); + engine_start::remote_switch switchb; + // held past the delay, the circuit stays open while the switch is held + for (auto step = 0; step < steps(2.0); ++step) { + switchb.update(&second, true, false, dt, true); + train.step({}, dt); + } + CHECK_FALSE(engine_start::remote_switch::is_running(second)); + // and closes when let go + switchb.update(&second, false, false, dt, true); + CHECK(engine_start::remote_switch::is_running(second)); + train.run(15.0); + REQUIRE(running(second)); + // let go before the delay, it doesn't + CHECK(engine_start::remote_switch::open(second)); + train.run(5.0); + REQUIRE_FALSE(engine_start::remote_switch::is_running(second)); + hold(train, switchb, &second, 0.5, true); + CHECK_FALSE(engine_start::remote_switch::is_running(second)); +} + +TEST_CASE("engine start: an engine stopping on its own stops the others only when they started together") { + for (auto const joint : {true, false}) { + CAPTURE(joint); + consist train; + auto &first{train.add(sn61(joint), 1).mover()}; + auto const &second{train.add(sn61(joint)).mover()}; + prepare(train); + engine_start::remote_switch switchb; + first.MainSwitch(true, first.MainSwitchRange()); + hold(train, switchb, engine_start::engine(first, first, 2), 2.0); + train.run(15.0); + REQUIRE(running(first)); + REQUIRE(running(second)); + // the first one's fuel cut off, its engine stops + first.FuelPump.is_disabled = true; + train.run(15.0); + CHECK_FALSE(first.Mains); + CHECK(first.enrot == 0.0); + // started on their own, the others keep running + CHECK(running(second) == (false == joint)); + } +} + +// a stopped engine stays stopped on its own: only an engine stopping while it ran tells the others, as a joint start's +// engines stop together; one stopped from another vehicle's switch, or not started at all, doesn't stop those running, +// whatever the flags of the vehicles in a mixed train +TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the others when it has spun down") { + consist train; + // the middle railcar keeps the joint start, as a .fiz without the key does. what a vehicle without the cab relays + // goes on away from the cab, so it's the third one that would stop + auto &first{train.add(sn61(false), 1).mover()}; + auto &second{train.add(sn61()).mover()}; + auto &third{train.add(sn61(false)).mover()}; + prepare(train); + engine_start::remote_switch switchb; + engine_start::remote_switch switchc; + first.MainSwitch(true, first.MainSwitchRange()); + hold(train, switchb, engine_start::engine(first, first, 2), 2.0); + hold(train, switchc, engine_start::engine(first, first, 3), 2.0); + train.run(15.0); + REQUIRE(running(first)); + REQUIRE(running(second)); + REQUIRE(running(third)); + // mainb_off + CHECK(engine_start::remote_switch::open(second)); + train.run(30.0); + CHECK_FALSE(second.Mains); + CHECK(second.enrot == 0.0); + CHECK(running(first)); + CHECK(running(third)); +} + +TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop the one started from its switch") { + consist train; + // the cab's railcar keeps the joint start, its engine stopped + auto &first{train.add(sn61(), 1).mover()}; + auto &second{train.add(sn61(false)).mover()}; + prepare(train); + REQUIRE_FALSE(first.Mains); + // mainb_on + engine_start::remote_switch switchb; + hold(train, switchb, engine_start::engine(first, first, 2), 2.0); + train.run(15.0); + CHECK(running(second)); + CHECK_FALSE(first.Mains); + CHECK(first.enrot == 0.0); +} diff --git a/tests/unit/test_framepacer.cpp b/tests/unit/test_framepacer.cpp new file mode 100644 index 000000000..bb9acb025 --- /dev/null +++ b/tests/unit/test_framepacer.cpp @@ -0,0 +1,110 @@ +#include "stdafx.h" +#include "doctest.h" +#include "utilities/framepacer.h" + +// the main loop's frame limiter (fpslimit in eu07.ini, eu07/maszyna#416), driven with made-up clock readings +namespace +{ +using namespace std::chrono_literals; +using clock_type = frame_pacer::clock; + +clock_type::time_point const kStart{clock_type::time_point{} + 100s}; +constexpr clock_type::duration kFrame{std::chrono::duration_cast(std::chrono::duration(1.f / 30.f))}; + +// runs frames that take Work each, with every wait overshooting by Oversleep; returns when the last of Frames ends +clock_type::time_point run_frames(frame_pacer &Pacer, int const Frames, clock_type::duration const Work, clock_type::duration const Oversleep) +{ + auto now{kStart}; + for (auto frame = 0; frame < Frames; ++frame) + { + now += Work; + if (auto const next{Pacer.next_frame(now, kFrame)}) + { + CHECK(*next > now); + now = *next + Oversleep; + } + } + return now; +} +} // namespace + +TEST_CASE("frame pacer: without a limit nothing waits") +{ + frame_pacer pacer; + CHECK_FALSE(pacer.next_frame(kStart, clock_type::duration::zero()).has_value()); + CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value()); +} + +TEST_CASE("frame pacer: a quick frame waits out the rest of the frame time") +{ + frame_pacer pacer; + // the first frame only sets the cadence + CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value()); + auto const next{pacer.next_frame(kStart + 5ms, kFrame)}; + REQUIRE(next.has_value()); + CHECK(*next == kStart + kFrame); +} + +TEST_CASE("frame pacer: a slow frame doesn't wait") +{ + frame_pacer pacer; + CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value()); + CHECK_FALSE(pacer.next_frame(kStart + kFrame + 5ms, kFrame).has_value()); +} + +TEST_CASE("frame pacer: the frame rate holds the limit with fast frames") +{ + frame_pacer pacer; + auto const end{run_frames(pacer, 301, 2ms, clock_type::duration::zero())}; + // 300 paced frames after the first + CHECK(end == kStart + 2ms + 300 * kFrame); +} + +TEST_CASE("frame pacer: a wait that overshoots is made up in the next frame") +{ + // the windows timer wakes a sleeping thread up to ~15.6 ms late; sleeping off what is left of each frame + // then drops 30 fps to about 22. on a fixed cadence the frame rate still averages to the limit + frame_pacer pacer; + auto const end{run_frames(pacer, 301, 2ms, 12ms)}; + auto const elapsed{std::chrono::duration(end - kStart).count()}; + CHECK(300.0 / elapsed == doctest::Approx(30.0).epsilon(0.01)); +} + +TEST_CASE("frame pacer: after a long frame the cadence starts anew instead of catching up") +{ + frame_pacer pacer; + CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value()); + // a hitch of half a second + auto const late{kStart + 500ms}; + CHECK_FALSE(pacer.next_frame(late, kFrame).has_value()); + // the next quick frame waits a whole frame time from there rather than running at once + auto const next{pacer.next_frame(late + 1ms, kFrame)}; + REQUIRE(next.has_value()); + CHECK(*next == late + kFrame); +} + +TEST_CASE("frame pacer: turning the limit off and on again starts a new cadence") +{ + frame_pacer pacer; + CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value()); + CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value()); + CHECK_FALSE(pacer.next_frame(kStart + 2s, kFrame).has_value()); + auto const next{pacer.next_frame(kStart + 2s + 1ms, kFrame)}; + REQUIRE(next.has_value()); + CHECK(*next == kStart + 2s + kFrame); +} + +TEST_CASE("frame pacer: the wait stays exact after days of system uptime") +{ + // fpslimit 60 gives the frame time as float seconds; the old limiter handed the float rest of the frame + // to sleep_for, which adds it to steady_clock::now() in float nanoseconds. after 95 hours of uptime that + // rounds the wake-up time to steps of ~33 ms, and a 14 ms wait came out as no wait at all + frame_pacer pacer; + std::chrono::duration const frametime{1.f / 60.f}; + auto const uptime{clock_type::time_point{} + 95h}; + CHECK_FALSE(pacer.next_frame(uptime, frametime).has_value()); + auto const next{pacer.next_frame(uptime + 2ms, frametime)}; + REQUIRE(next.has_value()); + auto const wait{std::chrono::duration(*next - (uptime + 2ms)).count()}; + CHECK(wait == doctest::Approx(1000.0 / 60.0 - 2.0).epsilon(0.001)); +} diff --git a/tests/unit/test_gauge_duplicates.cpp b/tests/unit/test_gauge_duplicates.cpp new file mode 100644 index 000000000..7bdbe9095 --- /dev/null +++ b/tests/unit/test_gauge_duplicates.cpp @@ -0,0 +1,53 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/gaugeduplicates.h" + +// cab controls with more than one submodel (eu07/maszyna#527): a definition of a control in the .mmd marked +// "duplicate: yes" adds a copy of the control already defined in the cab, instead of replacing it. TGauge itself +// (3d models, sounds) is not part of the core library, the rule which decides it is + +namespace { + +// stand-ins for the 3d models of the cab +struct model {}; + +} // namespace + +TEST_CASE("gauge duplicates: the values of the duplicate key which mark a duplicate") { + CHECK(gauge_duplicates::is_duplicate("yes")); + CHECK(gauge_duplicates::is_duplicate("true")); + CHECK(gauge_duplicates::is_duplicate("1")); + CHECK_FALSE(gauge_duplicates::is_duplicate("no")); + CHECK_FALSE(gauge_duplicates::is_duplicate("false")); + CHECK_FALSE(gauge_duplicates::is_duplicate("0")); + CHECK_FALSE(gauge_duplicates::is_duplicate("")); +} + +TEST_CASE("gauge duplicates: a duplicate adds a copy to the control loaded from either model of the cab") { + model cab; + model lowpoly; + CHECK(gauge_duplicates::adds_copy(true, &cab, &cab, &lowpoly)); + CHECK(gauge_duplicates::adds_copy(true, &lowpoly, &cab, &lowpoly)); + // a cab without a low poly interior + CHECK(gauge_duplicates::adds_copy(true, &cab, &cab, nullptr)); +} + +TEST_CASE("gauge duplicates: a definition not marked as a duplicate replaces the control, as before") { + model cab; + model lowpoly; + CHECK_FALSE(gauge_duplicates::adds_copy(false, &cab, &cab, &lowpoly)); + CHECK_FALSE(gauge_duplicates::adds_copy(false, nullptr, &cab, &lowpoly)); +} + +TEST_CASE("gauge duplicates: with nothing loaded in this cab a duplicate is the control itself") { + model cab; + model lowpoly; + model previouscab; + // the control isn't defined before it + CHECK_FALSE(gauge_duplicates::adds_copy(true, nullptr, &cab, &lowpoly)); + CHECK_FALSE(gauge_duplicates::adds_copy(true, nullptr, &cab, nullptr)); + // the control is left over from the cab loaded before + CHECK_FALSE(gauge_duplicates::adds_copy(true, &previouscab, &cab, &lowpoly)); + CHECK_FALSE(gauge_duplicates::adds_copy(true, &previouscab, &cab, nullptr)); +} diff --git a/tests/unit/test_hold_coil_lever.cpp b/tests/unit/test_hold_coil_lever.cpp new file mode 100644 index 000000000..cd3a3fee5 --- /dev/null +++ b/tests/unit/test_hold_coil_lever.cpp @@ -0,0 +1,30 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/holdcoillever.h" + +// the lever of the line breaker's hold coil on the ET22 and the EP09 stays where it's put (eu07/maszyna#364), when the +// cab declares its main_off_bt control with "type: toggle"; otherwise main_off_bt is the push button it always was + +TEST_CASE("hold coil lever: only a main_off_bt declared as a toggle switch is the bistable lever (eu07/maszyna#364)") { + CHECK(hold_coil_lever::is_bistable(true, true)); + // declared as a push button + CHECK_FALSE(hold_coil_lever::is_bistable(true, false)); + // no type given: a control defaults to the toggle type, which existing cabs relied on for the push button + CHECK_FALSE(hold_coil_lever::is_bistable(false, true)); +} + +TEST_CASE("hold coil lever: operated, it goes over to the other position and stays there") { + // on: the hold coil fed, the line breaker can close + CHECK_FALSE(hold_coil_lever::cuts_off(0.f)); + auto const off{hold_coil_lever::operated(0.f)}; + CHECK(off == doctest::Approx(1.f)); + CHECK(hold_coil_lever::cuts_off(off)); + // operated again it goes back on + auto const on{hold_coil_lever::operated(off)}; + CHECK(on == doctest::Approx(0.f)); + CHECK_FALSE(hold_coil_lever::cuts_off(on)); + // caught on the way between the positions it goes to the far one + CHECK(hold_coil_lever::operated(0.3f) == doctest::Approx(1.f)); + CHECK(hold_coil_lever::operated(0.7f) == doctest::Approx(0.f)); +} diff --git a/tests/unit/test_lights_preset_cablight.cpp b/tests/unit/test_lights_preset_cablight.cpp new file mode 100644 index 000000000..7c64c7d5a --- /dev/null +++ b/tests/unit/test_lights_preset_cablight.cpp @@ -0,0 +1,96 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +// the cab interior light set by the positions of the light preset selector: an optional third column of LightsList, +// 1 the cab light on, 2 dimmed, 0 off; a row without it leaves the cab light to its own switch (eu07/maszyna#529) + +using test::definition; +using test::vehicle; + +namespace { + +auto const shunting{light::headlight_left | light::headlight_right}; + +} // namespace + +TEST_CASE("lights preset cab light: a table without the column sets no position's cab light") { + vehicle wagon{definition::load("wagon") + .set("LightsList", "Size", 2) + .set("LightsList", "Default", 1) + .set("LightsList", "rows", {{0, 0}, {shunting, shunting}})}; + + REQUIRE(wagon->LightsPosNo == 2); + CHECK(wagon->Lights[end::front][1] == shunting); + CHECK_FALSE(wagon->LightsPresetCabLight(1).has_value()); + CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value()); +} + +TEST_CASE("lights preset cab light: the third column turns the cab light off, on, or on dimmed") { + // off - shunting - shunting with the cab lit - shunting with the cab lit dimmed - shunting leaving the cab light + vehicle wagon{definition::load("wagon") + .set("LightsList", "Size", 5) + .set("LightsList", "Default", 1) + .set("LightsList", "rows", {{0, 0, 0}, {shunting, shunting}, {shunting, shunting, 1}, {shunting, shunting, 3}, {shunting, 0, -1}})}; + + REQUIRE(wagon->LightsPosNo == 5); + // the light columns read as before + CHECK(wagon->Lights[end::front][2] == shunting); + CHECK(wagon->Lights[end::rear][2] == shunting); + CHECK(wagon->Lights[end::rear][4] == 0); + + auto const off{wagon->LightsPresetCabLight(1)}; + REQUIRE(off.has_value()); + CHECK_FALSE(off->light); + CHECK_FALSE(off->dim); + + CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value()); + + auto const lit{wagon->LightsPresetCabLight(3)}; + REQUIRE(lit.has_value()); + CHECK(lit->light); + CHECK_FALSE(lit->dim); + + auto const dimmed{wagon->LightsPresetCabLight(4)}; + REQUIRE(dimmed.has_value()); + CHECK(dimmed->light); + CHECK(dimmed->dim); + + // a negative value is the same as no value + CHECK_FALSE(wagon->LightsPresetCabLight(5).has_value()); +} + +TEST_CASE("lights preset cab light: positions outside the table, and the lightsset custom one, set nothing") { + vehicle wagon{definition::load("wagon") + .set("LightsList", "Size", 1) + .set("LightsList", "Default", 1) + .set("LightsList", "rows", {{shunting, shunting, 1}})}; + + CHECK(wagon->LightsPresetCabLight(1).has_value()); + CHECK_FALSE(wagon->LightsPresetCabLight(0).has_value()); + CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value()); + CHECK_FALSE(wagon->LightsPresetCabLight(18).has_value()); + CHECK_FALSE(wagon->LightsPresetCabLight(19).has_value()); +} + +TEST_CASE("lights preset cab light: a stray note after the two columns is not read as the cab light") { + // some vehicles of the game carry rows like "38 38 / A" + auto text{definition::load("wagon") + .set("LightsList", "Size", 2) + .set("LightsList", "Default", 1) + .set("LightsList", "rows", {{0, 0}, {38, 38}}) + .text()}; + auto const list{text.find("LightsList")}; + REQUIRE(list != std::string::npos); + auto const row{text.find("38", list)}; + REQUIRE(row != std::string::npos); + auto const rowend{text.find('\n', row)}; + REQUIRE(rowend != std::string::npos); + text.insert(rowend, " / A"); + TMoverParameters wagon(0.0, "wagon", "test", 0); + REQUIRE(wagon.LoadFIZ_Text(text)); + REQUIRE(wagon.LightsPosNo == 2); + CHECK(wagon.Lights[end::front][1] == 38); + CHECK(wagon.Lights[end::rear][1] == 38); + CHECK_FALSE(wagon.LightsPresetCabLight(2).has_value()); +} diff --git a/tests/unit/test_lights_programmer.cpp b/tests/unit/test_lights_programmer.cpp new file mode 100644 index 000000000..8a31563d8 --- /dev/null +++ b/tests/unit/test_lights_programmer.cpp @@ -0,0 +1,93 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/lightsprogrammer.h" + +// the lights the light preset selector (programmer) of the occupied cab gives the vehicles of the consist, +// TDynamicObject::SetLights(): the cab's front lights at the end the cab faces, its back lights at the other +// end, and no lights at an end with another vehicle coupled + +namespace { + +int const pc1{light::headlight_left | light::headlight_upper | light::headlight_right}; +int const tailmarkers{light::redmarker_left | light::redmarker_right}; +std::array const cablights{pc1, tailmarkers}; // Lights[end::front], Lights[end::rear] + +// the lights at the vehicle's own end, placed the way TDynamicObject::RaLightsSet() places them +int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, end const Side) { + auto const headend{Direction > 0 ? end::front : end::rear}; + return Side == headend ? Lights.head : Lights.rear; +} + +struct setup { + int cab; // CabOccupied of the vehicle with the programmer + int direction; // its iDirection + std::array coupled; // vehicle coupled at its end::front / end::rear +}; + +lights_programmer::consist_lights lights_for(setup const &Setup) { + // TDynamicObject::SetLights(): the cab faces the head of the consist when CabOccupied * DirectionGet() >= 0 + auto const cabfacinghead{Setup.cab * (Setup.direction > 0 ? 1 : -1) >= 0}; + return lights_programmer::vehicle_lights(cablights, cabfacinghead, Setup.direction, Setup.coupled); +} + +} // namespace + +TEST_CASE("lights programmer: a lone vehicle gets the cab's front lights ahead of the cab and its back lights behind it") { + for (auto const direction : {0, 1}) { + CAPTURE(direction); + // cab 1 faces end::front + auto const fromcab1{lights_for({1, direction, {false, false}})}; + CHECK(lights_at(fromcab1, direction, end::front) == pc1); + CHECK(lights_at(fromcab1, direction, end::rear) == tailmarkers); + // cab -1 faces end::rear + auto const fromcab2{lights_for({-1, direction, {false, false}})}; + CHECK(lights_at(fromcab2, direction, end::rear) == pc1); + CHECK(lights_at(fromcab2, direction, end::front) == tailmarkers); + } +} + +TEST_CASE("lights programmer: the end with the train coupled goes dark, not the other one (eu07/maszyna#395)") { + // a locomotive driven from either cab, with the train coupled at either end, either way round in the consist. + // the end with the train goes dark, the free end shows the lights meant for it + for (auto const direction : {0, 1}) { + for (auto const cab : {1, -1}) { + for (auto const trainend : {end::front, end::rear}) { + CAPTURE(direction); + CAPTURE(cab); + CAPTURE(trainend); + std::array coupled{false, false}; + coupled[trainend] = true; + auto const freeend{trainend == end::front ? end::rear : end::front}; + auto const cabfront{cab > 0 ? end::front : end::rear}; + + auto const lights{lights_for({cab, direction, coupled})}; + + CHECK(lights_at(lights, direction, trainend) == 0); + CHECK(lights_at(lights, direction, freeend) == (freeend == cabfront ? pc1 : tailmarkers)); + } + } + } +} + +TEST_CASE("lights programmer: 6Dg driven backwards from its second cab position pulls the train with its head lights lit (eu07/maszyna#395)") { + // the reported case: the train coupled behind the driver (end::front, which cab -1 has at its back), the + // locomotive running towards end::rear, the train in tow. the head lights stay lit, the end with the train goes dark; + // before the fix the couplings were looked up at the swapped ends and it was the other way round + auto const lights{lights_for({-1, 1, {true, false}})}; + + CHECK(lights_at(lights, 1, end::rear) == pc1); + CHECK(lights_at(lights, 1, end::front) == 0); +} + +TEST_CASE("lights programmer: a vehicle coupled at both ends stays dark") { + for (auto const direction : {0, 1}) { + for (auto const cab : {1, -1}) { + CAPTURE(direction); + CAPTURE(cab); + auto const lights{lights_for({cab, direction, {true, true}})}; + CHECK(lights.head == 0); + CHECK(lights.rear == 0); + } + } +} diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index 79c419edf..fd7e24f08 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -57,3 +57,74 @@ TEST_CASE("line contactors: the ground relay and overload lamps follow the same vehicle->MotorConnectorsCheck(); CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); } + +// on the diesel-electric SU45 and SU46 (eu07/maszyna#263) the lamp tells just the line contactors are open: lit with the +// master controller at 0 and with the start cut off by too low a pressure in the main pipe, out on the power positions + +namespace { + +// the diesel-electric locomotive with its engine running and the brakes released, the master controller at 0 +test::vehicle diesel_electric() { + test::vehicle vehicle{test::definition::load("diesel_electric")}; + vehicle->CabOccupied = 1; + vehicle->CabActivisation(); + vehicle->BatterySwitch(true); + vehicle->OilPumpSwitch(true); + vehicle->FuelPumpSwitch(true); + vehicle.run(20.0); // the oil pressure builds up + vehicle.hold_brake_pipe(5.0); // bar + vehicle->MainSwitch(true); + vehicle.run(30.0); + vehicle->DirectionForward(); + vehicle.run(60.0); // the brakes release + return vehicle; +} + +} // namespace + +TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") { + auto vehicle{diesel_electric()}; + REQUIRE(vehicle->EngineType == TEngineType::DieselElectric); + REQUIRE(vehicle->Mains); + REQUIRE_FALSE(vehicle->ControlPressureSwitch); + CHECK_FALSE(vehicle->StLinFlag); + CHECK(vehicle->LineContactorsLampLit()); + + vehicle->IncMainCtrl(1); + vehicle.run(3.0); + CHECK(vehicle->StLinFlag); + CHECK_FALSE(vehicle->LineContactorsLampLit()); + + vehicle->DecMainCtrl(1); + vehicle.run(3.0); + CHECK_FALSE(vehicle->StLinFlag); + CHECK(vehicle->LineContactorsLampLit()); +} + +TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contactors opened by too low a main pipe pressure") { + auto vehicle{diesel_electric()}; + vehicle->IncMainCtrl(1); + vehicle.run(1.0); + vehicle->IncMainCtrl(1); + vehicle.run(2.0); + REQUIRE(vehicle->StLinFlag); + + vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch + vehicle.run(10.0); + REQUIRE(vehicle->ControlPressureSwitch); + CHECK_FALSE(vehicle->StLinFlag); + CHECK(vehicle->LineContactorsLampLit()); // it went out here + CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off + + // the pressure back, the contactors stay open on the second position and the lamp stays lit, as it should; + // they close again only on the first one + vehicle.hold_brake_pipe(5.0); + vehicle.run(60.0); + REQUIRE_FALSE(vehicle->ControlPressureSwitch); + CHECK_FALSE(vehicle->StLinFlag); + CHECK(vehicle->LineContactorsLampLit()); + vehicle->DecMainCtrl(1); + vehicle.run(3.0); + CHECK(vehicle->StLinFlag); + CHECK_FALSE(vehicle->LineContactorsLampLit()); +} diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp new file mode 100644 index 000000000..126e3307c --- /dev/null +++ b/tests/unit/test_linebreaker.cpp @@ -0,0 +1,114 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "vehicle/linebreaker.h" + +// the line breaker (WS) controls of the cab (eu07/maszyna#394) + +using test::consist; +using test::definition; + +namespace { + +// the line breaker lever of the EP05 (main_sw), a single two-state lever, the way TTrain works it: the state +// the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close +struct lever { + TMoverParameters &mover; + int breaker{0}; // as TTrain::m_linebreakerstate: 0 open, 1 closed + bool on{false}; + + void press() { + switch (linebreaker::pressed(breaker, true, on)) { + case linebreaker::toggle::close: + on = true; + break; + case linebreaker::toggle::open: + on = false; + if (breaker == 1 && mover.MainSwitch(false)) { + breaker = 0; + } + break; + default: + break; + } + } + // TTrain::Update() + void update() { + if (breaker == 0 && mover.Mains) { + breaker = 1; + } + if (breaker == 1 && false == mover.Mains) { + breaker = 0; + } + if (on && breaker == 0 && mover.MainSwitchCheck()) { + breaker = mover.MainSwitch(true) ? 1 : 0; + } + } +}; + +} // namespace + +TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens a closed one") { + using enum linebreaker::toggle; + for (auto const latching : {false, true}) { + CHECK(linebreaker::pressed(0, latching, false) == close); + CHECK(linebreaker::pressed(1, latching, true) == open); + CHECK(linebreaker::pressed(1, latching, false) == open); + // freshly closed, the cab finishes closing it first + CHECK(linebreaker::pressed(2, latching, true) == none); + } + // a lever left on over an open breaker goes off; push buttons have no position to keep + CHECK(linebreaker::pressed(0, true, true) == open); + CHECK(linebreaker::pressed(0, false, true) == close); +} + +TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { + consist train; + auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).mover()}; + test::track const line{0.15, 0.0, test::catenary_3kv}; + auto const driver{test::driving(train)}; + REQUIRE(test::start_up(driver, line)); + REQUIRE(ep05.Mains); + REQUIRE(ep05.ConverterFlag); + lever ws{ep05, 1, true}; + + // the converter overload relay knocks the line breaker out, as the cab does it when the converter is + // switched on together with the compressor; the lever stays on + ep05.ConvOvldFlag = true; + ep05.MainSwitch(false, range_t::local); + ws.update(); + REQUIRE_FALSE(ep05.Mains); + REQUIRE(ws.breaker == 0); + CHECK(ws.on); + // with the relay tripped the breaker doesn't close + test::drive(driver, line, 5.0); + CHECK_FALSE(ep05.MainSwitchCheck()); + + // nothing holds the lever: it goes off, and on again, though the breaker stays open + ws.press(); + CHECK_FALSE(ws.on); + ws.press(); + CHECK(ws.on); + ws.update(); + CHECK_FALSE(ep05.Mains); + ws.press(); + CHECK_FALSE(ws.on); + + // the relay reset, with the converter switched off, the lever put on closes the breaker again + ep05.ConverterSwitch(false, range_t::local); + test::drive(driver, line, 1.0); + CHECK(ep05.RelayReset(relay_t::primaryconverteroverload, range_t::local)); + CHECK_FALSE(ep05.ConvOvldFlag); + ws.update(); + CHECK_FALSE(ep05.Mains); // the lever is off + ws.press(); + ws.update(); + CHECK(ep05.Mains); + CHECK(ws.breaker == 1); + // and the next press opens it + ws.press(); + CHECK_FALSE(ws.on); + CHECK_FALSE(ep05.Mains); +} diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp new file mode 100644 index 000000000..a5f623233 --- /dev/null +++ b/tests/unit/test_oil_pump.cpp @@ -0,0 +1,55 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the oil pump lamp of the cab (i-oilpump) shows OilPump.is_active: the pre-lubrication pump of 401Da, which works +// before the engine start and stops once the engine runs and makes the oil pressure itself (eu07/maszyna#546) +// NOTE: the test vehicle has no diesel engine, so the pump check is called the way dizel_Update() calls it + +TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and stops once the engine runs") { + vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Manual")}; + REQUIRE(loco->OilPump.start_type == start_t::manual); + loco->Power24vIsAvailable = true; // battery on + + loco->OilPumpCheck(0.01); + CHECK_FALSE(loco->OilPump.is_active); // not switched on yet + + loco->OilPump.is_enabled = true; // pump switch on: pre-lubrication + loco->OilPumpCheck(0.01); + CHECK(loco->OilPump.is_active); + + loco->Mains = true; // engine started + loco->OilPumpCheck(0.01); + CHECK_FALSE(loco->OilPump.is_active); +} + +TEST_CASE("oil pump: the pump started with the engine start procedure stops once the engine runs") { + vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Automatic")}; + REQUIRE(loco->OilPump.start_type == start_t::automatic); + loco->Power24vIsAvailable = true; + + loco->dizel_startup = true; // starter button pressed + loco->OilPumpCheck(0.01); + CHECK(loco->OilPump.is_active); + + loco->dizel_startup = false; // start procedure done, the pump keeps working until the engine runs + loco->OilPumpCheck(0.01); + CHECK(loco->OilPump.is_active); + + loco->Mains = true; + loco->OilPumpCheck(0.01); + CHECK_FALSE(loco->OilPump.is_active); +} + +TEST_CASE("oil pump: without power the pump and its lamp stay off") { + vehicle loco{definition::load("cab_vehicle")}; + loco->Power24vIsAvailable = false; + loco->Power110vIsAvailable = false; + + loco->OilPump.is_enabled = true; + loco->OilPumpCheck(0.01); + CHECK_FALSE(loco->OilPump.is_active); +} diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp index 33a12f72d..b65cc2ced 100644 --- a/tests/unit/test_radio.cpp +++ b/tests/unit/test_radio.cpp @@ -26,3 +26,33 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { } CHECK_FALSE(vehicle->RadioPowered()); } + +// the cut-off in the radio's power supply (eu07/maszyna#438): a fuse, a desk lever or the switch on the radio's +// power supply, closed unless the driver opens it + +TEST_CASE("radio: the radio fuse is closed by default") { + test::vehicle vehicle{test::definition::load("wagon")}; + CHECK(vehicle->RadioFuse); +} + +TEST_CASE("radio: an opened radio fuse cuts the radio off") { + test::vehicle vehicle{test::definition::load("wagon")}; + vehicle->Radio = true; + vehicle->Power24vIsAvailable = true; + vehicle->RadioFuse = false; + CHECK_FALSE(vehicle->RadioPowered()); + vehicle->RadioFuse = true; + CHECK(vehicle->RadioPowered()); +} + +TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + loco->Battery = true; + loco->Radio = true; + REQUIRE(loco->RadiostopSwitch(true)); + loco->SecuritySystemCheck(0.1); + CHECK(loco->RadioStopFlag); + loco->RadioFuse = false; + loco->SecuritySystemCheck(0.1); + CHECK_FALSE(loco->RadioStopFlag); +} diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index 05fb8ae8b..281b5dbf6 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -2,6 +2,7 @@ #include "doctest.h" #include "vehicle.h" +#include "drive.h" #include "vehicle/smoke.h" @@ -83,3 +84,78 @@ TEST_CASE("smoke: the pending particles never outgrow the room of the source") { CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, 10.0) == rate.limit); } + +TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") { + auto vehicle{diesel()}; + vehicle->dizel_spinup = true; + auto pending{source}; + pending.pending = 5.f; + + vehicle->dizel_FiringCountdown = 0.5; + CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f); + + vehicle->dizel_FiringCountdown = 0.0; + CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f); +} + +namespace { + +// the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains) +bool start_engine(test::driven const &Driven, test::track const &Track) { + for (int second = 0; second < 120 && false == Driven.controlling.Mains; ++second) { + test::start_up(Driven, Track, 1.0); + } + return Driven.controlling.Mains; +} + +} // namespace + +TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDelay after the starter began (#523)") { + // a diesel with a mechanical transmission and a diesel-electric one + for (auto const *path : {"sm42_v1/6d1", "st44_v2/m62-1151"}) { + CAPTURE(path); + test::track const track{}; + { + // SmokeDelay set in the .fiz of the locomotive + test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 2)}; + REQUIRE(locomotive->dizel_SmokeDelay == doctest::Approx(2.0)); + auto const driven{test::driving(locomotive)}; + REQUIRE(start_engine(driven, track)); + // the engine started less than a second ago: the starter still turns it + CHECK(locomotive->dizel_FiringCountdown > 0.5); + CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + // it has fired since + test::drive(driven, track, 3.0); + CHECK(locomotive->Mains); + CHECK(locomotive->dizel_FiringCountdown == 0.0); + CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + } + { + // a longer delay from the .fiz + test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 5)}; + auto const driven{test::driving(locomotive)}; + REQUIRE(start_engine(driven, track)); + test::drive(driven, track, 3.0); + CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + test::drive(driven, track, 3.0); + CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + } + } +} + +TEST_CASE("smoke: without SmokeDelay in its .fiz a diesel smokes as soon as the starter turns, as before (#523)") { + for (auto const *path : {"sm42_v1/6d1", "st44_v2/m62-1151"}) { + CAPTURE(path); + test::track const track{}; + // a locomotive which has the delay, loaded first, doesn't hand it on to the next one: the value is the vehicle's own + test::vehicle delayed{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 3)}; + REQUIRE(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + test::vehicle locomotive{test::definition::fiz(path)}; + REQUIRE(locomotive->dizel_SmokeDelay == 0.0); + CHECK(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + auto const driven{test::driving(locomotive)}; + REQUIRE(start_engine(driven, track)); + CHECK(locomotive->dizel_FiringCountdown == 0.0); + CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + } +} diff --git a/tests/unit/test_test_mode.cpp b/tests/unit/test_test_mode.cpp new file mode 100644 index 000000000..eba641096 --- /dev/null +++ b/tests/unit/test_test_mode.cpp @@ -0,0 +1,268 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "simulation/simulationtestrules.h" + +#include +#include +#include +#include +#include + +// the test mode of the simulator (eu07 --test, eu07/maszyna#541): its exit codes, command line and end conditions + +namespace { + +using simulation::test_result; + +simulation::test_command_line parse(std::vector Arguments) +{ + Arguments.insert(Arguments.begin(), "eu07"); + return simulation::parse_test_command_line(Arguments); +} + +// a frame of the default 0.03 s +simulation::test_frame frame(bool const Atrest, std::optional const Reported = std::nullopt, std::string_view const Reason = {}) +{ + return simulation::test_frame{0.03, Reported, Reason, Atrest}; +} + +// runs frames until the test ends or Seconds of simulation time go by +std::optional run(simulation::test_progress &Progress, simulation::test_limits const &Limits, double const Seconds, + simulation::test_frame const &Frame) +{ + while (Progress.time < Seconds) + { + if (auto verdict{simulation::evaluate_frame(Progress, Frame, Limits)}) + return verdict; + } + return std::nullopt; +} + +} // namespace + +TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or aborted process") +{ + std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error}; + for (auto const result : results) + { + auto const code{static_cast(result)}; + CAPTURE(code); + CHECK(code != 1); // TerminateProcess, most programs' failure + CHECK(code != 3); // abort() on Windows + CHECK(code < 126); // shells, signals on Linux + CHECK(simulation::to_string(result) != "unknown"); + } + // the codes are public: scripts and CI read them + CHECK(static_cast(test_result::pass) == 0); + CHECK(static_cast(test_result::fail) == 10); + CHECK(static_cast(test_result::signal_passed_at_danger) == 11); + CHECK(static_cast(test_result::timeout) == 12); + CHECK(static_cast(test_result::standstill) == 13); + CHECK(static_cast(test_result::error) == 14); +} + +TEST_CASE("test mode: seconds on the command line are a number, not negative") +{ + CHECK(simulation::parse_seconds("240").value_or(-1.0) == doctest::Approx(240.0)); + CHECK(simulation::parse_seconds("0.5").value_or(-1.0) == doctest::Approx(0.5)); + CHECK(simulation::parse_seconds("0").value_or(-1.0) == doctest::Approx(0.0)); + CHECK_FALSE(simulation::parse_seconds("").has_value()); + CHECK_FALSE(simulation::parse_seconds("-1").has_value()); + CHECK_FALSE(simulation::parse_seconds("60s").has_value()); + CHECK_FALSE(simulation::parse_seconds("abc").has_value()); + CHECK_FALSE(simulation::parse_seconds("inf").has_value()); + CHECK_FALSE(simulation::parse_seconds("nan").has_value()); +} + +TEST_CASE("test mode: the command line") +{ + SUBCASE("without --test there is no test") + { + auto const commandline{parse({"-s", "td.scn", "-v", "ep07-424"})}; + CHECK_FALSE(commandline.enabled); + CHECK(commandline.error.empty()); + } + SUBCASE("--test and its limits, in any order") + { + auto const commandline{parse({"--test-wall-timeout", "900", "-s", "td.scn", "--test", "--test-timeout", "240"})}; + CHECK(commandline.enabled); + CHECK(commandline.timeout.value_or(-1.0) == doctest::Approx(240.0)); + CHECK(commandline.wall_timeout.value_or(-1.0) == doctest::Approx(900.0)); + CHECK(commandline.error.empty()); + } + SUBCASE("a limit not given stays unset") + { + auto const commandline{parse({"--test", "-s", "td.scn"})}; + CHECK_FALSE(commandline.timeout.has_value()); + CHECK_FALSE(commandline.wall_timeout.has_value()); + } + SUBCASE("a limit which isn't a number is an error, not a limit turned off") + { + auto const commandline{parse({"--test", "-s", "td.scn", "--test-timeout", "4m"})}; + CHECK(commandline.enabled); + CHECK_FALSE(commandline.timeout.has_value()); + CHECK(commandline.error == "--test-timeout needs a number of seconds"); + } + SUBCASE("a limit without its value is an error") + { + auto const commandline{parse({"--test", "-s", "td.scn", "--test-wall-timeout"})}; + CHECK(commandline.error == "--test-wall-timeout needs a number of seconds"); + } + SUBCASE("the first error is the one told") + { + auto const commandline{parse({"--test", "--test-timeout", "x", "--test-wall-timeout", "y"})}; + CHECK(commandline.error == "--test-timeout needs a number of seconds"); + } + SUBCASE("values of other options aren't taken for options") + { + auto const commandline{parse({"-s", "--test", "-ini", "--test-timeout", "-v", "--test-wall-timeout", "-seed", "--test"})}; + CHECK_FALSE(commandline.enabled); + CHECK(commandline.error.empty()); + } + SUBCASE("-edit takes no option for its scenery, which is optional") + { + // a scenery after -edit or none: the option after it is read either way + CHECK(parse({"-edit", "--test", "-s", "td.scn"}).enabled); + CHECK(parse({"-edit", "td.scn", "--test"}).enabled); + // -edit leaves -s alone, which takes --test for its scenery, as the simulator reads it + CHECK_FALSE(parse({"-edit", "-s", "--test"}).enabled); + } +} + +TEST_CASE("test mode: the real time limit") +{ + SUBCASE("given, it is the limit, 0 turns it off") + { + CHECK(simulation::wall_clock_limit(120.0, 3600.0) == doctest::Approx(120.0)); + CHECK(simulation::wall_clock_limit(0.0, 3600.0) == doctest::Approx(0.0)); + } + SUBCASE("not given, it is the simulation time limit and time for the loading") + { + CHECK(simulation::wall_clock_limit(std::nullopt, 240.0) == doctest::Approx(240.0 + simulation::wall_timeout_loading_allowance)); + CHECK(simulation::wall_clock_limit(std::nullopt, 3600.0) == doctest::Approx(3600.0 + simulation::wall_timeout_loading_allowance)); + } + SUBCASE("no simulation time limit, no real time limit unless given") + { + CHECK(simulation::wall_clock_limit(std::nullopt, 0.0) == doctest::Approx(0.0)); + CHECK(simulation::wall_clock_limit(300.0, 0.0) == doctest::Approx(300.0)); + } +} + +TEST_CASE("test mode: the end conditions") +{ + simulation::test_limits limits; + simulation::test_progress progress; + + SUBCASE("nothing happens, nothing ends") + { + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value()); + CHECK(progress.time == doctest::Approx(0.03)); + CHECK(progress.resttime == doctest::Approx(0.0)); + } + SUBCASE("a cell nobody wrote to says nothing") + { + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, -1.0), limits).has_value()); + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 2.0), limits).has_value()); + CHECK_FALSE(progress.passrequested); + } + SUBCASE("0 fails at once, with the text of the cell") + { + auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0, "wrong_track"), limits)}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::fail); + CHECK(verdict->reason == "__test.result set to 0 (wrong_track)"); + } + SUBCASE("1 passes once the tested trains have stood for a second") + { + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value()); + CHECK(progress.passrequested); + // still moving: the pass waits + CHECK_FALSE(run(progress, limits, 30.0, frame(false, 1.0)).has_value()); + auto const stoppedat{progress.time}; + auto const verdict{run(progress, limits, 60.0, frame(true, 1.0))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::pass); + CHECK(progress.time - stoppedat == doctest::Approx(simulation::pass_settle_time).epsilon(0.05)); + } + SUBCASE("the pass stays requested when the cell changes back") + { + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value()); + auto const verdict{run(progress, limits, 60.0, frame(true, -1.0))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::pass); + } + SUBCASE("1 with test.no_movement_before_pass no passes at once") + { + limits.no_movement_before_pass = false; + auto const verdict{simulation::evaluate_frame(progress, frame(false, 1.0, "reached_the_stop"), limits)}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::pass); + CHECK(verdict->reason == "__test.result set to 1 (reached_the_stop)"); + } + SUBCASE("standing still without a result ends after test.standstill") + { + limits.standstill = 120.0; + auto const verdict{run(progress, limits, 1000.0, frame(true))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::standstill); + CHECK(progress.time == doctest::Approx(120.0).epsilon(0.001)); + } + SUBCASE("a move starts the standstill over") + { + limits.standstill = 120.0; + CHECK_FALSE(run(progress, limits, 100.0, frame(true)).has_value()); + CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value()); + CHECK(progress.resttime == doctest::Approx(0.0)); + CHECK_FALSE(run(progress, limits, 200.0, frame(true)).has_value()); + } + SUBCASE("test.pass_on_standstill makes the standstill a pass") + { + limits.standstill = 10.0; + limits.pass_on_standstill = true; + auto const verdict{run(progress, limits, 1000.0, frame(true))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::pass); + } + SUBCASE("test.standstill 0 never ends the test") + { + limits.standstill = 0.0; + limits.timeout = 0.0; + CHECK_FALSE(run(progress, limits, 5000.0, frame(true)).has_value()); + } + SUBCASE("no result by test.timeout") + { + limits.timeout = 240.0; + auto const verdict{run(progress, limits, 1000.0, frame(false))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::timeout); + CHECK(verdict->reason == "no result after 240 s"); + CHECK(progress.time == doctest::Approx(240.0).epsilon(0.001)); + } + SUBCASE("a result in the last frame wins over the timeout") + { + limits.timeout = 0.03; + auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0), limits)}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::fail); + } +} + +TEST_CASE("test mode: what ended a run the simulator didn't end") +{ + SUBCASE("an exception says what it was") + { + CHECK(simulation::describe_exception(std::make_exception_ptr(std::runtime_error("no scenery"))) == "critical error: no scenery"); + // e.g. std::stof on a token of a scenery which isn't a number + CHECK(simulation::describe_exception(std::make_exception_ptr(std::invalid_argument("stof"))) == "critical error: stof"); + CHECK(simulation::describe_exception(std::make_exception_ptr(std::bad_alloc())).starts_with("critical error: ")); + } + SUBCASE("something thrown which isn't a std::exception") + { + CHECK(simulation::describe_exception(std::make_exception_ptr(42)) == "critical error: an exception of unknown type"); + } + SUBCASE("terminated without an exception") + { + CHECK(simulation::describe_exception(nullptr) == "the simulator was terminated"); + } +} diff --git a/tests/unit/test_uc_steps.cpp b/tests/unit/test_uc_steps.cpp new file mode 100644 index 000000000..eb1b26fa4 --- /dev/null +++ b/tests/unit/test_uc_steps.cpp @@ -0,0 +1,115 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "drive.h" + +#include + +// the universal controller (EIMCtrlType 3) setting its power demand in steps (UCList CtrlValStep), as the 6Dg does +// in steps of 5% (eu07/maszyna#412). the 214M railbus's controller: 3 lowers the power to 0, 4 holds it, 5 raises it +// to 1, at 0.15 a second after IniCDelay (1 s) + +using test::definition; +using test::vehicle; + +namespace { + +constexpr int lower{3}; +constexpr int hold{4}; +constexpr int raise{5}; + +// the railbus started up, its brakes released and its direction set, its controller holding no power +void get_ready(vehicle &Railbus, test::track const &Track) { + auto driven{test::driving(Railbus)}; + REQUIRE(test::start_up(driven, Track)); + test::release_brakes(driven.cab); + for (int i = 0; i < 3 && Railbus->DirActive <= 0; ++i) { + Railbus->DirectionForward(); + } + while (Railbus->MainCtrlPos < hold && Railbus->IncMainCtrl(1)) { + ; + } + while (Railbus->MainCtrlPos > hold && Railbus->DecMainCtrl(1)) { + ; + } + REQUIRE(Railbus->MainCtrlPos == hold); + Railbus.run(2.0, Track); + REQUIRE(Railbus->eimic == doctest::Approx(0.0)); +} + +void move_to(vehicle &Railbus, int const Position) { + while (Railbus->MainCtrlPos < Position && Railbus->IncMainCtrl(1)) { + ; + } + while (Railbus->MainCtrlPos > Position && Railbus->DecMainCtrl(1)) { + ; + } + REQUIRE(Railbus->MainCtrlPos == Position); +} + +bool on_step(double const Value, double const Step) { + return std::abs(Value / Step - std::round(Value / Step)) < 1e-6; +} + +} // namespace + +TEST_CASE("controls: the universal controller with CtrlValStep sets its power in whole steps") { + test::track const line{0.15, 0.0}; + vehicle railbus{definition::fiz("21xm_v1/214ma").set("UCList", "CtrlValStep", 0.05), 0.0, "test", 1}; + REQUIRE(railbus->UniCtrlValStep == doctest::Approx(0.05)); + get_ready(railbus, line); + + // a tap on the raising position: one step at once, kept by the holding one + move_to(railbus, raise); + railbus.step(line); + CHECK(railbus->eimic == doctest::Approx(0.05)); + move_to(railbus, hold); + railbus.run(2.0, line); + CHECK(railbus->eimic == doctest::Approx(0.05)); + + // held there: after the initial delay a step each third of a second (0.15 a second), never in between + move_to(railbus, raise); + for (int i = 0; i < 310; ++i) { // 3.1 s + railbus.step(line); + CAPTURE(i); + CHECK(on_step(railbus->eimic, 0.05)); + } + // the first step at once, 1 s of the initial delay, then 2.1 s of 0.15 a second (6 steps) + CHECK(railbus->eimic == doctest::Approx(0.40)); + move_to(railbus, hold); + railbus.run(2.0, line); + CHECK(railbus->eimic == doctest::Approx(0.40)); + + // up to the full power, and not past it + move_to(railbus, raise); + railbus.run(10.0, line); + CHECK(railbus->eimic == doctest::Approx(1.0)); + + // down the same way: a tap is one step, holding it goes on in steps down to nothing + move_to(railbus, lower); + railbus.step(line); + CHECK(railbus->eimic == doctest::Approx(0.95)); + move_to(railbus, hold); + railbus.run(1.0, line); + CHECK(railbus->eimic == doctest::Approx(0.95)); + move_to(railbus, lower); + for (int i = 0; i < 800; ++i) { // 8 s + railbus.step(line); + CAPTURE(i); + CHECK(on_step(railbus->eimic, 0.05)); + } + CHECK(railbus->eimic == doctest::Approx(0.0)); +} + +TEST_CASE("controls: the universal controller without CtrlValStep sets its power continuously, as before") { + test::track const line{0.15, 0.0}; + vehicle railbus{definition::fiz("21xm_v1/214ma"), 0.0, "test", 1}; + REQUIRE(railbus->UniCtrlValStep == 0.0); + get_ready(railbus, line); + // a tap moves it by 0.01, held it goes on at 0.15 a second after the initial delay + move_to(railbus, raise); + railbus.step(line); + CHECK(railbus->eimic == doctest::Approx(0.01)); + railbus.run(2.0 - 0.01, line); + CHECK(railbus->eimic == doctest::Approx(0.01 + 0.15).epsilon(0.05)); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index b4f2e14be..ce299ce5d 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -456,6 +456,66 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token return false; } +bool global_settings::ConfigParseTest(cParser& Parser, std::string_view const Token) +{ + // integration test limits, usually given in the config block of a test scenery + if (Token == "test.timeout") + { + double value{ test.timeout }; + ParseOne(Parser, value); + if (false == test.timeout_from_command_line) + test.timeout = std::max(0.0, value); + return true; + } + + if (Token == "test.wall_timeout") + { + double value{ 0.0 }; + ParseOne(Parser, value); + if (false == test.wall_timeout_from_command_line) + test.wall_timeout = std::max(0.0, value); + return true; + } + + if (Token == "test.vehicle") + { + // a vehicle of a train under test, by its name in the scenery; the pass and the standstill wait for its + // consist only, not for other trains (eu07/maszyna#541). given more than once, for each of them + std::string name; + ParseOne(Parser, name, 1, true); + if (false == name.empty() && std::ranges::find(test.vehicles, name) == test.vehicles.end()) + test.vehicles.emplace_back(name); + return true; + } + + if (Token == "test.standstill") + { + ParseOne(Parser, test.standstill); + test.standstill = std::max(0.0, test.standstill); + return true; + } + + if (Token == "test.pass_on_standstill") + { + ParseOne(Parser, test.pass_on_standstill); + return true; + } + + if (Token == "test.fail_if_stop_overran") + { + ParseOne(Parser, test.fail_if_stop_overran); + return true; + } + + if (Token == "test.no_movement_before_pass") + { + ParseOne(Parser, test.no_movement_before_pass); + return true; + } + + return false; +} + bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& token) { if (token == "async.trainThreads") @@ -751,6 +811,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "controlcoupling.enginecheck") + { + ParseOne(Parser, control_coupling_engine_check, 1); + return true; + } + return false; } @@ -1316,6 +1382,9 @@ void global_settings::ConfigParse(cParser& Parser) if (ConfigParseDebug(Parser, token)) continue; + if (ConfigParseTest(Parser, token)) + continue; + // WriteLog(std::format("Unknown config token: {}", token), logtype::warning, false); } while (true); @@ -1590,6 +1659,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); export_as_text( Output, "ai.trainman", AITrainman ); + export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); export_as_text( Output, "shadows", RenderShadows ); @@ -1742,6 +1812,17 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.shadowmap.enabled", gfx_shadowmap_enabled ); // TODO: export fpslimit export_as_text( Output, "randomseed", Global.random_seed ); + export_as_text( Output, "test.timeout", test.timeout ); + if( test.wall_timeout.has_value() ) { + export_as_text( Output, "test.wall_timeout", *test.wall_timeout ); + } + export_as_text( Output, "test.standstill", test.standstill ); + export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill ); + export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran ); + export_as_text( Output, "test.no_movement_before_pass", test.no_movement_before_pass ); + for( auto const &vehicle : test.vehicles ) { + export_as_text( Output, "test.vehicle", vehicle ); + } export_as_text( Output, "gfx.envmap.enabled", gfx_envmap_enabled ); export_as_text( Output, "gfx.postfx.motionblur.enabled", gfx_postfx_motionblur_enabled ); export_as_text( Output, "gfx.postfx.motionblur.shutter", gfx_postfx_motionblur_shutter ); diff --git a/utilities/Globals.h b/utilities/Globals.h index ad216cd96..872338b46 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "utilities/motiontelemetry.h" #include +#include #ifdef WITH_UART #include "utilities/uart.h" @@ -86,6 +87,20 @@ struct global_settings { std::string local_start_vehicle{ "EU07-424" }; std::string editor_enter_vehicle; // vehicle placed in the editor, to be entered when the driving goes on bool editor_session{ false }; // scenery was opened for editing (-edit): loader keeps track of scenery layers and hands over to the editor + // integration test mode (--test, eu07/maszyna#541); the limits can be set in the scenery's config block (test.*) + struct test_settings { + bool enabled{ false }; + double timeout{ 3600.0 }; // [s] of simulation time; no result by then fails the test + double standstill{ 300.0 }; // [s] the tested trains standing still this long ends the test; 0 = never + bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it + bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged + bool no_movement_before_pass{ true }; // a pass waits until the tested trains stand still; with false it ends the test at once + std::vector vehicles; // test.vehicle: the trains under test are the consists of these; none = every vehicle + bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it + std::optional wall_timeout; // [s] of real time since the start; none = test.timeout + time for the loading, 0 = no limit + bool wall_timeout_from_command_line{ false }; // --test-wall-timeout given, the scenery doesn't override it + }; + test_settings test; bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap int iConvertModels{ 0 }; // tworzenie plików binarnych int iConvertIndexRange{ 1000 }; // range of duplicate vertex scan @@ -260,6 +275,7 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; bool gui_trainingdefault = false; @@ -377,6 +393,7 @@ struct global_settings { bool ConfigParseNetwork(cParser& Parser, const std::string& token); bool ConfigParseHardware(cParser& Parser, const std::string& token); bool ConfigParseDebug(cParser& Parser, const std::string& token); + bool ConfigParseTest(cParser& Parser, std::string_view Token); bool ConfigParse_gfx( cParser &parser, std::string_view const Token ); // sends basic content of the class in legacy (text) format to provided stream void diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 38094d72e..e0949aba6 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -125,8 +125,8 @@ void LogService() if (log_scrollback.size() > 200) log_scrollback.pop_front(); - // log to console - if (Global.iWriteLogEnabled & 2) + // log to console; not in test mode, where the standard output carries the result of the test only + if ((Global.iWriteLogEnabled & 2) && false == Global.test.enabled) { if (isError) printf("\033[1;37;41m%s\033[0m\n", msg.c_str()); diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp index 0b877f2b4..eacd2ba0a 100644 --- a/utilities/Timer.cpp +++ b/utilities/Timer.cpp @@ -27,6 +27,17 @@ double fSoundTimer{ 0.0 }; double fSinceStart{ 0.0 }; double override_delta = -1.0f; +namespace { + +// when set (test mode), every frame lasts this long, see set_fixed_step() +double &fixed_step() +{ + static double step{0.0}; + return step; +} + +} // namespace + double GetTime() { return fSimulationTime; @@ -53,6 +64,11 @@ void set_delta_override(double t) override_delta = t; } +void set_fixed_step(double t) +{ + fixed_step() = t; +} + void ResetTimers() { UpdateTimers( Global.iPause != 0 ); @@ -76,10 +92,16 @@ void UpdateTimers(bool pause) fr = 1000000000; #endif DeltaRenderTime = double(count - oldCount) / double(fr); + auto const fixedstep{fixed_step()}; + if (fixedstep > 0.0) + { + // the frame lasts exactly as long as said, however long it took to compute; the time speed doesn't apply + DeltaRenderTime = fixedstep; + } fRenderTime += DeltaRenderTime; if (!pause) { - DeltaTime = Global.fTimeSpeed * DeltaRenderTime; + DeltaTime = (fixedstep > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime; fSoundTimer += DeltaTime; if (fSoundTimer > 0.1) fSoundTimer = 0.0; diff --git a/utilities/Timer.h b/utilities/Timer.h index 32e170a46..38a5d101e 100644 --- a/utilities/Timer.h +++ b/utilities/Timer.h @@ -19,6 +19,9 @@ double GetDeltaRenderTime(); void set_delta_override(double v); +// every frame advances the clocks by this many seconds, whatever the real time; 0 = real time (test mode) +void set_fixed_step(double v); + void ResetTimers(); void UpdateTimers(bool pause); @@ -64,6 +67,7 @@ struct subsystem_stopwatches { stopwatch sim_events; stopwatch sim_ai; stopwatch mainloop_total; + stopwatch mainloop_period; // start to start, the wait for fpslimit included }; extern subsystem_stopwatches subsystem; diff --git a/utilities/color.h b/utilities/color.h index be853a3d4..bbf17e096 100644 --- a/utilities/color.h +++ b/utilities/color.h @@ -15,9 +15,9 @@ glm::vec3 XYZtoRGB( glm::vec3 const &XYZ ) { // M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html - float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f }; +// float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f }; // m^-1 for sRGB: -// float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f }; + float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f }; return glm::vec3{ XYZ.x*mi[ 0 ][ 0 ] + XYZ.y*mi[ 1 ][ 0 ] + XYZ.z*mi[ 2 ][ 0 ], diff --git a/utilities/framepacer.h b/utilities/framepacer.h new file mode 100644 index 000000000..a0de0144d --- /dev/null +++ b/utilities/framepacer.h @@ -0,0 +1,59 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// paces the main loop to the frame time set by fpslimit in eu07.ini. +// the frames are scheduled on a fixed cadence rather than by sleeping off what is left of each frame, +// so a sleep that overshoots (the windows timer wakes up in steps of up to ~15.6 ms) is made up by +// a shorter wait in the next frame, and the frame rate averages to the limit. +// all the time arithmetic is done in the clock's integer ticks: a sleep_for() given a float duration +// adds it to now() as float nanoseconds, which after a few hours of system uptime rounds the wake-up +// time to tens of milliseconds and lets the limit fall through (eu07/maszyna#416) +class frame_pacer { + +public: + using clock = std::chrono::steady_clock; + + // called at the end of each frame. returns the point in time the next frame may start at, + // or nothing when it may start right away + [[nodiscard]] std::optional next_frame(clock::time_point const Now, std::chrono::duration const Frametime) { + return next_frame(Now, std::chrono::duration_cast(Frametime)); + } + [[nodiscard]] std::optional next_frame(clock::time_point const Now, clock::duration const Minframetime) { + if (Minframetime <= clock::duration::zero()) { + // no limit + m_framestart.reset(); + return std::nullopt; + } + if (!m_framestart) { + // first paced frame + m_framestart = Now; + return std::nullopt; + } + auto const nextframe{*m_framestart + Minframetime}; + if (Now >= nextframe + Minframetime) { + // a whole frame or more behind: start the cadence anew rather than run frames back to back to catch up + m_framestart = Now; + return std::nullopt; + } + m_framestart = nextframe; + if (Now >= nextframe) { + return std::nullopt; + } + return nextframe; + } + +private: + // the scheduled start of the current frame + std::optional m_framestart; +}; diff --git a/utilities/translation.cpp b/utilities/translation.cpp index c0dbeb1a0..e172eabf1 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -225,6 +225,10 @@ std::string locale::label_cab_control(std::string const &Label) { "coolingfans_sw:", STRN("cooling fans") }, { "main_off_bt:", STRN("line breaker") }, { "main_on_bt:", STRN("line breaker") }, + { "mainb_off_bt:", STRN("line breaker B") }, + { "mainb_on_bt:", STRN("line breaker B") }, + { "mainc_off_bt:", STRN("line breaker C") }, + { "mainc_on_bt:", STRN("line breaker C") }, { "security_reset_bt:", STRN("alerter") }, { "shp_reset_bt:", STRN("shp") }, { "releaser_bt:", STRN("independent brake releaser") }, @@ -270,7 +274,14 @@ std::string locale::label_cab_control(std::string const &Label) { "converterlocal_sw:", STRN("local converter") }, { "converteroff_sw:", STRN("converter") }, { "main_sw:", STRN("line breaker") }, + { "mainb_sw:", STRN("line breaker B") }, + { "mainc_sw:", STRN("line breaker C") }, { "radio_sw:", STRN("radio") }, + { "radioon_sw:", STRN("radio") }, + { "radiooff_sw:", STRN("radio") }, + { "radiofuse_sw:", STRN("radio fuse") }, + { "radiofuseon_sw:", STRN("radio fuse") }, + { "radiofuseoff_sw:", STRN("radio fuse") }, { "radiochannel_sw:", STRN("radio channel") }, { "radiochannelprev_sw:", STRN("radio channel") }, { "radiochannelnext_sw:", STRN("radio channel") }, diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 461c8d1af..4aa09683c 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "world/MemCell.h" #include "simulation/simulation.h" #include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" #include "world/Track.h" #include "world/station.h" #include "input/keyboardinput.h" @@ -767,6 +768,7 @@ void TController::TableCheck(double fDistance) { // aktualizacja rekordów z wyjątkiem ostatniego if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna { + auto const passedbefore { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) }; if (sSpeedTable[i].Update()) { if( Global.iWriteLogEnabled & 8 ) { @@ -793,6 +795,8 @@ void TController::TableCheck(double fDistance) // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy break; } + // a switch is a track, the update of a signal never ends the loop above + CheckSignalPassedAtDanger( sSpeedTable[ i ], passedbefore ); if (sSpeedTable[i].iFlags & spTrack) // jeśli odcinek { if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza @@ -816,7 +820,10 @@ void TController::TableCheck(double fDistance) } } } + auto const lastpassedbefore { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) }; sSpeedTable[iLast].Update(); // aktualizacja ostatniego + // a signal at stop often is the last, the scan doesn't go past it + CheckSignalPassedAtDanger( sSpeedTable[ iLast ], lastpassedbefore ); // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); if( sSpeedTable[ iLast ].fDist < fDistance ) { TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka @@ -827,8 +834,71 @@ void TController::TableCheck(double fDistance) } }; +namespace { + +// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop +bool is_signal_at_stop( TSpeedPos const &Point ) +{ + return TestFlag( Point.iFlags, spEvent ) + && TestFlag( Point.iFlags, spSemaphor ) + && false == TestFlag( Point.iFlags, spStopOnSBL ) + && std::abs( Point.fVelNext ) <= 0.0 + && Point.evEvent != nullptr; +} + +} // namespace + +void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point, bool const Passedbefore ) const +{ + if( false == Passedbefore + && TestFlag( Point.iFlags, spElapsed ) + && is_signal_at_stop( Point ) + && ( mvOccupied->CategoryFlag & 1 ) != 0 ) { // railway only + simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name ); + } +} + auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head +// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the +// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at +std::pair +TController::train_proximity_margins( bool const Passengerstop ) const { + + auto minproximity { 0.0 }; + auto maxproximity { 0.0 }; + if( Passengerstop ) { + // a stop point keeps the margins its W4 parameters (head or middle of the consist, + // platform length) were set up against + minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 ); + maxproximity = std::clamp( 10 + iVehicles, 15, 40 ); + } + else { + // a train stops 8-15 m short of the signal whatever its length; closer than the lower + // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out + minproximity = 8.0; + // the final approach begins far enough out to slow from the coasting speed down to the window, + // and at the same distance whether the train is moving or standing, so it does not flip + // between creeping closer and holding still when it comes to a stand short of the window + maxproximity = 50.0; + } + if( IsCargoTrain ) { + // start the final approach earlier for cargo trains, their brakes react more slowly + maxproximity += 10.0; + } + if( ( Global.FrictionWeatherFactor < 1.f ) + && ( iVehicles > 1 ) ) { + // take into account weather conditions + minproximity += 5.0; + maxproximity += 5.0; + } + if( mvOccupied->Vel < 0.1 ) { + // jak stanie za daleko, to niech nie dociąga paru metrów + maxproximity = std::max( maxproximity, 50.0 ); + } + return { minproximity, maxproximity }; +} + TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc) { // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy // fVelDes - prędkość zadana @@ -843,6 +913,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table eSignNext = nullptr; IsAtPassengerStop = false; + bStopTargetIsPassengerStop = false; IsScheduledPassengerStopVisible = false; mvOccupied->SecuritySystem.set_cabsignal_lock(false); // te flagi są ustawiane tutaj, w razie potrzeby @@ -962,6 +1033,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) fNext = v; // istotna jest prędkość na końcu tego odcinka fDist = d; // dlugość odcinka + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); } /* else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { @@ -976,6 +1048,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN fAcc = a; fNext = v; fDist = d; + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); } // potentially update our current speed limit if( v < VelLimitLastDist.first @@ -1152,14 +1225,20 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub return true; } + // the margins of a passenger stop, whether the train is already making for it or not: the present ones + // depend on this very flag, and a check against them would turn it on and off every other scan + auto const [ stopminproximity, stopmaxproximity ] { + is_train() ? + train_proximity_margins( true ) : + std::pair{ fMinProximityDist, fMaxProximityDist } }; IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance // Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, // przyjąć odległość fMinProximityDist && ((iDrivigFlags & moveStopCloser) != 0 ? - Point.fDist + fLength + (Point.fMoved - fMinProximityDist * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), - 2.0 * fMaxProximityDist + fLength) : // fmaxproximitydist typically equals ~50 m + Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), + 2.0 * stopmaxproximity + fLength) : Point.fDist < Signaldistance); if( !eSignNext ) { @@ -1880,7 +1959,8 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, << "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " << "MCP SCP BCP LBP Direction Command CVal1 CVal2 " << "Security Wheelslip " - << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]" + << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + << "VehicleVelocity[km/h]" << "\r\n"; LogFile << std::fixed << std::setprecision( 4 ); #endif @@ -2689,6 +2769,7 @@ bool TController::PrepareEngine() cue_action( driver_hint::batteryon ); cue_action( driver_hint::cabactivation); + cue_action( driver_hint::radiofuseon ); cue_action( driver_hint::radioon ); if( has_diesel_engine() ) { @@ -2931,6 +3012,77 @@ bool TController::ReleaseEngine() { return OK; } +// defined further down, with the braking demand it is used for +static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); + +// one step more of the train brake, sized from the consist brake table against the deceleration asked for +bool +TController::increase_train_brake() { + + // dodane dla towarowego + float pos_corr = 0; + + TDynamicObject *d; + d = pVehicles[0]; // pojazd na czele składu + while (d) + { // przeliczanie dodatkowego potrzebnego spadku ciśnienia + if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { + pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; + } + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + pos_corr = pos_corr / fMass * 2.5; + + if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + { + pos_corr += mvOccupied->Handle->GetCP()*0.2; + + } + if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); + deltaAcc > brake_increase_margin() ) + { + if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { + auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH + // HACK: stronger braking to overcome SA134 engine behaviour + if( is_dmu() + && VelNext == 0.0 + && fBrakeDist < 200.0 ) { + BrakeLevelAdd( + fBrakeDist / ActualProximityDist < 0.8 ? + 0.5 : + 1.0 ); + } + return OK; + } + auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH + // brake harder if the acceleration is much higher than desired + /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) + && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { + mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); + } GBH */ + if( deltaAcc > 2 * fBrake_a1[0] + && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { + /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); + } + return OK; + } + if( BrakeCtrlPosition > 0.0 + && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting + && ( fBrakeHeldTime > ( + mvOccupied->BrakeDelayFlag > bdelay_G ? + mvOccupied->BrakeDelay[ 1 ] : + mvOccupied->BrakeDelay[ 3 ] ) + // a train falling further behind needs no full fill time to be seen not to get enough + || ( ( fShortfall > 0.02 ) + && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { + // the table says the present position is enough, but the brake has had its full fill + // time since the handle last moved and the train is still not slowing down as asked: + // believe the train rather than the table + return BrakeLevelAdd( BrakingLevelIncrease ); + } + return false; +} + bool TController::IncBrake() { // zwiększenie hamowania auto OK { false }; @@ -3022,56 +3174,7 @@ bool TController::IncBrake() OK = false; } else { - // dodane dla towarowego - float pos_corr = 0; - - TDynamicObject *d; - d = pVehicles[0]; // pojazd na czele składu - while (d) - { // przeliczanie dodatkowego potrzebnego spadku ciśnienia - if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; - } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - pos_corr = pos_corr / fMass * 2.5; - - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - pos_corr += mvOccupied->Handle->GetCP()*0.2; - - } - double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); - - if( deltaAcc > fBrake_a1[0]) - { - if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { - OK = /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ); //GBH - // HACK: stronger braking to overcome SA134 engine behaviour - if( is_dmu() - && VelNext == 0.0 - && fBrakeDist < 200.0 ) { - BrakeLevelAdd( - fBrakeDist / ActualProximityDist < 0.8 ? - 0.5 : - 1.0 ); - } - } - else { - OK = /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); //GBH - // brake harder if the acceleration is much higher than desired - /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) - && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { - mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); - } GBH */ - if( deltaAcc > 2 * fBrake_a1[0] - && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { - /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); - } - } - } - else - OK = false; + OK = increase_train_brake(); } } if( /*GBH mvOccupied->BrakeCtrlPos*/ @@ -3109,6 +3212,14 @@ bool TController::IncBrake() mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać OK = true; } + else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) + && ( mvOccupied->EpForce <= 0.0 ) + && ( mvOccupied->EPBrakeControlPowered() ) ) { + // the handle already in the EP brake position, but the EP brake dropped out with the control's + // supply (e.g. the EP fuse off in the running brake test): switch it on again + mvOccupied->SwitchEPBrake( 1 ); + OK = ( mvOccupied->EpForce > 0.0 ); + } else OK = false; break; @@ -3188,7 +3299,19 @@ bool TController::DecBrake() { if( fBrake_a0[0] != 0.0 || fBrake_a1[0] != 0.0 ) { auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) }; - deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - pos_diff )*fBrake_a1[ 0 ] ); + // a distributor applied at all gives at least its minimum stage, about what the first position does, so + // a position short of the first one brakes no weaker than that + deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); + } + if( bUphillStart ) { + // starting uphill the train brake holds the train until the power does + break; + } + if( ( BrakeCtrlPosition > 0.0 ) + && ( uphill_stop_hold() ) ) { + // any release now raises the pipe, and a long train releases more than the handle is moved back, too late + // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it + break; } if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); @@ -3367,7 +3490,7 @@ bool TController::IncSpeed() mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && + auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : @@ -3722,6 +3845,7 @@ void TController::BrakeLevelSet(double b) if (BrakeCtrlPosition == b) return; // nie przeliczać, jak nie ma zmiany BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX); + fBrakeHeldTime = 0.0; } bool TController::BrakeLevelAdd(double b) @@ -4824,7 +4948,9 @@ void TController::PhysicsLog() << mvControlling->dizel_heat.Ts << " " << mvControlling->dizel_heat.To << " " << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 + << mvControlling->dizel_heat.temperatura2 << " " + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + << mvOccupied->V * 3.6 << "\r\n"; #endif #if LOGPRESS == 1 @@ -5860,6 +5986,7 @@ TController::update_timers( double dt ) { ElapsedTime += dt; WaitingTime += dt; fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca + fBrakeHeldTime += dt; if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) { // brake charging timeout starts after charging ends BrakeChargingCooldown += dt; @@ -5923,6 +6050,7 @@ TController::determine_consist_state() { IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false; IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; + auto doorclosure { door_closure_t::none }; ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> @@ -5930,6 +6058,8 @@ TController::determine_consist_state() { { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; + // starting uphill the power is applied against the train brake on purpose, until the power holds the train + auto const heldforstart { bUphillStart }; if (Ready) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; @@ -5938,7 +6068,9 @@ TController::determine_consist_state() { // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - Ready = false; + // ready all the same only at a standstill with the power going on against the brake on purpose; + // in motion a braking force left anywhere in the train (a hand brake) stops it as before + Ready = heldforstart && ( vehicle->Vel < 1.0 ); } // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy @@ -5956,7 +6088,7 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( bp, fReady ); // szukanie najbardziej zahamowanego + fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -5984,12 +6116,14 @@ TController::determine_consist_state() { IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit; IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit; } + doorclosure = std::max( doorclosure, vehicle->door_closure() ); } // measure lighting level // TBD: apply weight (multiplier) to partially lit vehicles? ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0; p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) } + DoorClosure = doorclosure; // calculate average amount of received sunlight ConsistShade /= iVehicles; @@ -6122,6 +6256,13 @@ TController::control_pantographs() { fActionTime = -2.0 - Random(10); } + // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none + // or the vehicle isn't shunting + auto const shuntpantographsetup { + ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) != 0 ? + mvOccupied->AIHintShuntPantstate : + 0 }; + // raise/lower pantographs as needed auto const useregularpantographlayout { pVehicle->Next(coupling::control) == nullptr // standalone @@ -6148,7 +6289,11 @@ TController::control_pantographs() { // jeśli nie trzeba opuszczać pantografów // TODO: check if faction alone reduces frequency enough if( fActionTime > 0.0 ) { - if( mvOccupied->AIHintPantstate == 0 ) { + if( shuntpantographsetup != 0 ) { + // shunting with the pantograph setup the .fiz suggests for it + control_pantographs_setup( shuntpantographsetup ); + } + else if( mvOccupied->AIHintPantstate == 0 ) { // jazda na tylnym if( iDirection >= 0 && useregularpantographlayout ) { // jak jedzie w kierunku sprzęgu 0 @@ -6201,6 +6346,12 @@ TController::control_pantographs() { } } } + else if( shuntpantographsetup != 0 ) { + // shunting with the suggested setup, also while standing, and without raising more pantographs when idling + if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) { + control_pantographs_setup( shuntpantographsetup ); + } + } else { if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) { @@ -6227,6 +6378,31 @@ TController::control_pantographs() { } } +// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once +// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way +void +TController::control_pantographs_setup( int const Setup ) { + + auto const front { ( Setup & 1 << 0 ) != 0 }; + auto const rear { ( Setup & 1 << 1 ) != 0 }; + if( front ) { + cue_action( driver_hint::frontpantographvalveon ); + } + if( rear ) { + cue_action( driver_hint::rearpantographvalveon ); + } + if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) }; + false == setuplive ) { + return; + } + if( false == front ) { + cue_action( driver_hint::frontpantographvalveoff ); + } + if( false == rear ) { + cue_action( driver_hint::rearpantographvalveoff ); + } +} + void TController::control_horns( double const Timedelta ) { // horn control @@ -6301,13 +6477,19 @@ TController::control_security_system( double const Timedelta ) { } } if( iEngineActive - && false == mvOccupied->Radio + && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse ) && false == mvOccupied->RadioStopFlag ) { // otherwise if it's safe to do so, turn the radio back on // arbitrary 5 sec delay before switching radio back on m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); if( m_radiocontroltime < 0.0 ) { - cue_action( driver_hint::radioon ); + // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply + if( false == mvOccupied->RadioFuse ) { + cue_action( driver_hint::radiofuseon ); + } + if( false == mvOccupied->Radio ) { + cue_action( driver_hint::radioon ); + } } else { m_radiocontroltime -= Timedelta; @@ -6663,32 +6845,9 @@ TController::determine_proximity_ranges() { // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody // jeśli pociąg if( is_train() ) { - fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 ); - fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 ); - - if( IsCargoTrain ) { - // increase distances for cargo trains to take into account slower reaction to brakes - fMinProximityDist += 10.0; - fMaxProximityDist += 10.0; -/* - if( IsHeavyCargoTrain ) { - // cargo trains with high braking threshold may require even larger safety margin - fMaxProximityDist += 20.0; - } -*/ - } - - if (Global.FrictionWeatherFactor < 1.f - && iVehicles > 1 ) { - // take into account weather conditions - fMinProximityDist += 5.0; - fMaxProximityDist += 5.0; - } - - if( mvOccupied->Vel < 0.1 ) { - // jak stanie za daleko, to niech nie dociąga paru metrów - fMaxProximityDist = 50.0; - } + auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) }; + fMinProximityDist = minproximity; + fMaxProximityDist = maxproximity; if( iDrivigFlags & moveLate ) { // jeśli spóźniony, to gna @@ -6914,8 +7073,14 @@ TController::UpdateConnect() { auto *vehicle { iCouplingVehicle.value().first }; auto const couplingend { iCouplingVehicle.value().second }; auto *vehicleparameters { vehicle->MoverParameters }; - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != iCoupler ) { - auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; + auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; + // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) + auto expectedcoupling { iCoupler }; + if( neighbour.vehicle != nullptr ) { + auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; + expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler ); + } + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { // check whether we need to attach coupler adapter auto coupleriscompatible{true}; @@ -6937,7 +7102,7 @@ TController::UpdateConnect() { } } // NOTE: no else as the preceeding block can potentially establish expected connection - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == iCoupler ) { + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { // jeżeli został podłączony CheckVehicles( Connect ); // sprawdzić światła nowego składu @@ -7196,6 +7361,61 @@ TController::handle_orders() { UpdateChangeDirection(); } +// the stages of uncoupling: each one sets the speed for the next +void +TController::set_velocity_for_uncoupling() { + + if( iVehicleCount < 0 ) { + // 4th stage: restore initial direction + if( ( iDrivigFlags & movePress ) != 0 ) { + SetVelocity( 0, 0, stopJoin ); + } + return; + } + // 3rd stage: compress buffers and uncouple + if( ( iDrivigFlags & movePress ) != 0 && iDirection == iDirectionOrder ) { + SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 + return; + } + // 1st stage: bring it to stop + // 2nd stage: apply consist brakes and change direction + SetVelocity( 0, 0, stopJoin ); +} + +// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released +// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it +// stands, and is applied for real if the train has started to roll back +void +TController::hold_train_coming_to_stand_uphill() { + + if( ( false == is_train() ) + || ( ( OrderCurrentGet() & Obey_train ) == 0 ) + || ( VelNext != 0.0 ) + || ( ActualProximityDist > fMaxProximityDist ) + || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { + return; + } + auto const vel { DirectionalVel() }; + if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) { + VelDesired = 0.0; + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + return; + } + if( ( vel < 0.0 ) + || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) + // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops: + // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any + // sooner and the brake takes off more of the distance than the stop was planned with + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) + // not for a train that is short of where it is to stop and is to pull up further + && ( AccDesired <= 0.0 ) + && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { + // the gradient alone already slows the train down nearly this much; ask for enough on top of it that + // the brake is applied for sure, not held back by the margin against small corrections + AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); + } +} + void TController::pick_optimal_speed( double const Range ) { @@ -7231,23 +7451,7 @@ TController::pick_optimal_speed( double const Range ) { } // uncoupling mode changes velocity/acceleration between stages if( ( OrderCurrentGet() & Disconnect ) != 0 ) { - if( iVehicleCount >= 0 ) { - // 3rd stage: compress buffers and uncouple - if( (iDrivigFlags & movePress) != 0 && iDirection == iDirectionOrder ) { - SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 - } - // 1st stage: bring it to stop - // 2nd stage: apply consist brakes and change direction - else { - SetVelocity( 0, 0, stopJoin ); - } - } - else { - // 4th stage: restore initial direction - if( ( iDrivigFlags & movePress ) != 0 ) { - SetVelocity( 0, 0, stopJoin ); - } - } + set_velocity_for_uncoupling(); } VelLimitLastDist = { VelDesired, -1 }; @@ -7300,6 +7504,9 @@ TController::pick_optimal_speed( double const Range ) { is_car() ? -2.0 : -0.9, is_car() ? 2.0 : 0.9 ); + // done last, so that none of the adjustments above, made for a train moving forward, can undo it + hold_train_coming_to_stand_uphill(); + // if the route ahead is blocked we might need to head the other way check_route_behind( 1000 ); // NOTE: legacy scan range value } @@ -7321,6 +7528,10 @@ TController::adjust_desired_speed_for_obstacles() { if( k - vel < 5 ) { // porównanie modułów prędkości [km/h] // zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej + if( Obstacle.distance < ActualProximityDist ) { + // the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of + bStopTargetIsPassengerStop = false; + } ActualProximityDist = std::min( ActualProximityDist, Obstacle.distance ); @@ -7465,6 +7676,211 @@ TController::adjust_desired_speed_for_limits() { } } +// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time +// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G +// is tens of seconds; never shorter than the look-ahead the AI has always used +static double +brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { + + auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; + if( Brakesystem == TBrakeSystem::Pneumatic ) { + // BrakeDelay holds the release and the application time in G, then the same two in P + auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 }; + auto const isrelease { Acceleration < 0.0 }; + horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] ); + } + return horizon; +} + +// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand +static double +uphill_stopping_distance( double const Velocity, double const Gravity ) { + return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); +} + +// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m] +static double +uphill_coasting_speed( double const Distance, double const Gravity ) { + return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); +} + +// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train +// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the +// consist brake table says it does (cast iron blocks grip harder as the train slows) +struct consist_brake_table { + double const *a0; // deceleration at handle position 1, by speed + double const *a1; // deceleration added by each quarter of a position, by speed + int size; // entries, up to the vehicle's top speed + double vmax; // the vehicle's top speed [km/h] + + // deceleration [m/s2] of a full service application at Kmh + double full_braking( double const Kmh ) const { + auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) }; + return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); } +}; + +static double +shaped_braking_demand( + double const Velocity, double const Target, double const Distance, double const Gravity, + consist_brake_table const &Table ) { + + auto const fullbraking = [&Table]( double const Kmh ) { + return Table.full_braking( Kmh ); }; + auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) { + auto const steps { 24 }; + auto const step { ( Velocity - Target ) / steps }; + auto distance { 0.0 }; + for( auto i { 0 }; i < steps; ++i ) { + auto const kmh { Target + ( i + 0.5 ) * step }; + auto const deceleration { Ratio * fullbraking( kmh ) - Gravity }; + if( deceleration <= 0.001 ) { + return std::numeric_limits::max(); + } + distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration; + } + return distance; }; + + auto low { 0.0 }; + auto high { 3.0 }; + if( travel( high ) > Distance ) { + return Gravity - high * fullbraking( Velocity ); + } + for( auto i { 0 }; i < 30; ++i ) { + auto const middle { 0.5 * ( low + high ) }; + ( travel( middle ) > Distance ? low : high ) = middle; + } + return Gravity - high * fullbraking( Velocity ); +} + +// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the +// direction of travel +void +TController::adjust_desired_speed_for_braking_curve( double const Vel ) { + + AccDesired = AccPreferred; + if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { + return; + } + // allow to coast at reasonably low speed + auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; + if( auto const slowdowndistance { ( + mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance + brakingdistance : + std::max( + (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0, + brakingdistance ) ) }; + brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { + // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good + return; + } + // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever + auto const brakingpointoffset = ( + ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? + stopping_margin() : // the same stopping point as the final approach + VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); + // a pneumatic brake acts on the state the train will be in once it has responded; while the + // train is still speeding up, plan the deceleration from there, so more is asked for at once + auto velocity { Vel }; + auto distance { ActualProximityDist }; + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( AbsAccS > 0.0 ) ) { + auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + velocity = Vel + 3.6 * horizon * AbsAccS; + distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon ); + } + auto const brakingroom { + std::max( + distance - brakingpointoffset, + std::min( + distance, + brakingpointoffset ) ) }; + auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) }; + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) { + // follow the shape of the consist brake force over speed rather than assume a constant + // deceleration, over the distance left once the brake has had time to fill (while the + // train is still speeding up, the prediction above has taken that off already) + auto room { brakingroom }; + if( ( AbsAccS <= 0.0 ) + && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const brakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + room = std::max( + 0.5 * brakingroom, + brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, brakea0 ) ); + } + deceleration = shaped_braking_demand( + velocity, VelNext, room + 0.1 / 25.92, fAccGravity, + { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ); + } + AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje + if( Vel <= VelNext ) { + return; + } + if( deceleration < fAccGravity - 0.001 ) { + // no power while still above the speed being braked for + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + } + else if( ( fAccGravity < -0.025 ) + && ( ( OrderCurrentGet() & Obey_train ) != 0 ) + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { + // uphill the gradient alone slows the train down more than it is asked to; + // keep it rolling at the present speed until that changes + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) ); + } +} + +// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel +void +TController::adjust_desired_speed_for_final_approach( double const Vel ) { + + if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) { + // for cars (and others) coast at low speed until we hit min proximity range + VelDesired = min_speed( VelDesired, 5.0 ); + return; + } + // trains + if( ( OrderCurrentGet() & ( Shunt | Connect ) ) + && ( Obstacle.distance < 50 ) ) { + // crude detection of edge case, if approaching another vehicle coast slowly until min distance + // this should allow to bunch up trainsets more on sidings + VelDesired = min_speed( 5.0, VelDesired ); + return; + } + // hamowanie tak, aby stanąć + if( ( OrderCurrentGet() & Obey_train ) == 0 ) { + VelDesired = VelNext; + AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); + AccDesired = std::min( AccDesired, fAccThreshold ); + return; + } + // a train keeps its desired speed until the lower edge of the stopping window (a desired + // speed of 0 here asks for hard braking whatever the distance left), aims at the middle + // of the window, and asks only for what that takes + auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) }; + AccDesired = ( + BrakeSystem == TBrakeSystem::Pneumatic ? + // cast iron blocks grip harder as the train comes to a stand + shaped_braking_demand( + Vel, VelNext, stoppingroom, fAccGravity, + { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : + ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); + if( ( fAccGravity < -0.025 ) + && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { + // uphill the gradient alone would bring the train to a stand short of the + // middle of the stopping window; keep it rolling at the present speed until that changes, + // but no faster than the gradient alone can take off by the middle of the window + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) ); + } +} + void TController::adjust_desired_speed_for_target_speed( double const Range ) { // ustalanie zadanego przyspieszenia @@ -7478,6 +7894,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) { // gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze // normalna jazda AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01; + fAccDesiredGravity = 0.0; auto const vel { DirectionalVel() }; @@ -7495,65 +7912,21 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) { AccDesired = AccPreferred; } } + else if( ( ActualProximityDist > fMinProximityDist ) + // only a stop has a final approach of its own inside the proximity range; a lower speed ahead + // keeps the braking curve below right up to where it begins, or the train would stop braking + // (and even take power) that far out + && ( VelNext == 0.0 ) + && ( ActualProximityDist < fMaxProximityDist ) ) { + // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko + // jak minął już maksymalny dystans po prostu hamuj (niski stopień) + // ma stanąć, a jest w drodze hamowania albo ma jechać + adjust_desired_speed_for_final_approach( vel ); + AccDesired = std::min( AccDesired, AccPreferred ); + } else if (ActualProximityDist > fMinProximityDist) { // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko - if (ActualProximityDist < fMaxProximityDist) { - // jak minął już maksymalny dystans po prostu hamuj (niski stopień) - // ma stanąć, a jest w drodze hamowania albo ma jechać -/* - VelDesired = min_speed( VelDesired, VelNext ); -*/ - if( VelNext == 0.0 ) { - if( mvOccupied->CategoryFlag & 1 ) { - // trains - if( OrderCurrentGet() & (Shunt | Connect) - && Obstacle.distance < 50 ) { - // crude detection of edge case, if approaching another vehicle coast slowly until min distance - // this should allow to bunch up trainsets more on sidings - VelDesired = min_speed( 5.0, VelDesired ); - } - else { - // hamowanie tak, aby stanąć - VelDesired = VelNext; - AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); - AccDesired = std::min( AccDesired, fAccThreshold ); - } - } - else { - // for cars (and others) coast at low speed until we hit min proximity range - VelDesired = min_speed( VelDesired, 5.0 ); - } - } - } - else { - // outside of max safe range - AccDesired = AccPreferred; - if( vel > min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { - // allow to coast at reasonably low speed - auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; - auto const slowdowndistance { ( - mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance - brakingdistance : - std::max( - (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0, - brakingdistance ) ) }; - if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) >= ActualProximityDist - fMaxProximityDist ) { - // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good - // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever - auto const brakingpointoffset = VelNext * braking_distance_multiplier( VelNext ); - AccDesired = std::min( - AccDesired, - ( VelNext * VelNext - vel * vel ) - / ( 25.92 - * std::max( - ActualProximityDist - brakingpointoffset, - std::min( - ActualProximityDist, - brakingpointoffset ) ) - + 0.1 ) ); // najpierw hamuje mocniej, potem zluzuje - } - } - } + adjust_desired_speed_for_braking_curve( vel ); AccDesired = std::min( AccDesired, AccPreferred ); } else { @@ -7636,35 +8009,58 @@ TController::adjust_desired_speed_for_current_speed() { if( fAccGravity > 0.025 ) { // going sharply downhill we may need to start braking sooner than usual // try to estimate increase of current velocity before engaged brakes start working - auto const speedestimate = vel + ( 1.0 - fBrake_a0[ 0 ] ) * 30.0 * AbsAccS; - if( speedestimate > VelDesired ) { - // jesli jedzie za szybko do AKTUALNEGO - if( VelDesired == 0.0 ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie - } - else { - // if it looks like we'll exceed maximum speed start thinking about slight slowing down - AccDesired = std::min( AccDesired, -0.05 + fAccThreshold ); - // HACK: for cargo trains with high braking threshold ensure we cross that threshold - if( true == IsCargoTrain - && fBrake_a0[0] > 0.2 ) { - AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ); - } - } + // look ahead for as long as the brake takes to respond, since that is how long the + // present acceleration will last whatever is done with the handle now; a pneumatic + // brake applies and releases on its own time scale, which in G is tens of seconds + auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + auto const speedestimate = vel + 3.6 * horizon * AbsAccS; + // already below a lower limit ahead, the train has no business speeding up towards it + auto holdlimit { VelDesired }; + if( ( VelNext > 0.0 ) + && ( VelNext < holdlimit ) + && ( vel <= VelNext + fVelPlus ) + && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) { + holdlimit = VelNext; + } + // hold a band just below the limit; the steeper the descent the harder the train pulls + // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille) + // an electro-pneumatic or electric brake responds at once and needs far less room + auto const holdspeed { holdlimit - ( + BrakeSystem == TBrakeSystem::Pneumatic ? + std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) : + std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) }; + // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a + // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as + // long to let go, and the train ends up well below the speed it was to hold + auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) }; + if( ( speedestimate > VelDesired ) + && ( VelDesired == 0.0 ) ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie } else { - // stop accelerating when close enough to target speed + // one continuous law on both sides of the target, proportional to the predicted + // difference: a demand that jumps to the braking threshold above the target and to + // full acceleration below it alternates, with a brake that responds in seconds, + // between a hard application and a full release AccDesired = std::min( AccDesired, // but don't override decceleration for VelNext - std::lerp( // ease off as you close to the target velocity - EU07_AI_NOACCELERATION, AccPreferred, - std::clamp( VelDesired - speedestimate, 0.0, fVelMinus ) / fVelMinus ) ); + std::clamp( + EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ), + -0.05 + fAccThreshold, + std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) ); + // HACK: for cargo trains with high braking threshold ensure we cross that threshold + auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit }; + AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 ); } // final tweaks if( vel > EU07_AI_NOMOVEMENT ) { // going downhill also take into account impact of gravity AccDesired -= fAccGravity; + // from here on AccDesired is what the brake alone has to deliver, which is what + // IncBrake() sizes the handle position for; AbsAccS already contains the gravity, + // so the comparisons with it have to add this part back + fAccDesiredGravity = fAccGravity; // HACK: if the max allowed speed was exceeded something went wrong; brake harder AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 ); } @@ -7731,6 +8127,10 @@ TController::adjust_desired_speed_for_braking_test() { if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? auto const vel { DirectionalVel() }; + // what the route ahead asks for; the test may brake harder than that, never softer + auto const routeaccdesired { AccDesired }; + auto const routeaccdesiredgravity { fAccDesiredGravity }; + auto const routeveldesired { VelDesired }; switch( DynamicBrakeTest ) { case 0: { @@ -7748,6 +8148,7 @@ TController::adjust_desired_speed_for_braking_test() { } case 1: { AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; VelDesired = DBT_VelocityBrake; if( ElapsedTime - DBT_BrakingTime > 1 ) { ForcePNBrake = true; @@ -7758,6 +8159,7 @@ TController::adjust_desired_speed_for_braking_test() { } case 2: { AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; VelDesired = DBT_VelocityBrake; if( ElapsedTime - DBT_BrakingTime > 2 ) { DBT_BrakingTime = ElapsedTime; @@ -7769,6 +8171,7 @@ TController::adjust_desired_speed_for_braking_test() { } case 3: { AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); + fAccDesiredGravity = 0.0; VelDesired = DBT_VelocityBrake; if( vel <= DBT_VelocityRelease ) { DynamicBrakeTest = 4; @@ -7794,6 +8197,14 @@ TController::adjust_desired_speed_for_braking_test() { break; } } + // a stop or a restriction coming up while the test runs takes precedence + if( ( DynamicBrakeTest >= 1 ) + && ( DynamicBrakeTest <= 3 ) + && ( routeaccdesired < AccDesired ) ) { + AccDesired = routeaccdesired; + fAccDesiredGravity = routeaccdesiredgravity; + VelDesired = std::min( VelDesired, routeveldesired ); + } } void @@ -7871,6 +8282,8 @@ void TController::control_motor_connectors() { void TController::control_tractive_force() { + control_uphill_start(); + auto const velocity { DirectionalVel() }; // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up @@ -7882,7 +8295,9 @@ void TController::control_tractive_force() { (ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance fMaxProximityDist) ? // other vehicle types keep wider margin true : - velocity + 1.0 < VelNext) ) { + velocity + 1.0 < VelNext + // uphill, a train told to hold its speed on the way to a stop needs the power to do it + || VelNext == 0.0 && (OrderCurrentGet() & Obey_train) != 0 && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like // ...to można przyspieszyć @@ -7897,9 +8312,7 @@ void TController::control_tractive_force() { cue_action( driver_hint::mastercontrollersetzerospeed ); } else if( velocity > VelDesired + SpeedCtrlMargin - || ( fAccGravity < -0.01 ? - AccDesired < 0.0 : - AbsAccS > AccDesired + 10.05 ) + || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 ) || IsAnyCouplerStretched ) { // jak za bardzo przyspiesza albo prędkość przekroczona // dodany wyjatek na "pelna w przod" @@ -7911,6 +8324,71 @@ void TController::control_tractive_force() { SpeedSet(); // ciągla regulacja prędkości } +bool TController::is_too_fast_uphill() const { + + if( AccDesired < 0.0 ) { return true; } + // holding the speed uphill on the way to a stop asks for no speeding up + return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ); +} + +// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the +// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train +// brake only once the power holds the train. releasing everything first lets the train roll back before the power is +// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous +// drives, the control pressure switch) +void TController::control_uphill_start() { + + auto const velocity { DirectionalVel() }; + if( auto const uphill { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && is_train() + && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; + false == uphill ) { + bUphillStart = false; + return; + } + if( false == bUphillStart ) { + if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + && ( AccDesired > EU07_AI_NOACCELERATION ) + && ( VelDesired > 0.0 ) + && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train + bUphillStart = true; + fUphillStartTime = ElapsedTime; + } + else { + return; + } + } + if( AccDesired <= EU07_AI_NOACCELERATION ) { + // no longer to start: the standing rules take over + bUphillStart = false; + return; + } + if( velocity < -0.5 ) { + // rolling back all the same: the rules for a train slipping back take over and apply the brakes + bUphillStart = false; + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + auto tractiveforce { 0.0 }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + // Ft is signed in the vehicle's own frame + tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + } + auto const holdingforce { fMass * -fAccGravity }; + if( ( velocity > 1.0 ) + || ( tractiveforce > 1.1 * holdingforce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillStart = false; + } +} + void TController::increase_tractive_force() { if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać @@ -7933,6 +8411,49 @@ void TController::increase_tractive_force() { cue_action( driver_hint::tractiveforceincrease ); } +// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower +// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand +// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough +double +TController::brake_increase_margin() const { + + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( VelNext > 0.0 ) + && ( VelNext < DirectionalVel() ) ) { + return 0.5 * fBrake_a1[ 0 ]; + } + return fBrake_a1[ 0 ]; +} + +// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be +// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the +// locomotive brake, which acts at once, helps to hold the train +bool +TController::uphill_stop_hold() const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( ( OrderCurrentGet() & Obey_train ) != 0 ) + && ( VelNext == 0.0 ) + && ( ActualProximityDist <= fMaxProximityDist ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( std::abs( DirectionalVel() ) < 10.0 ) + // not while the train is to be driven on + && ( AccDesired <= 0.0 ) ); +} + +// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist +// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the +// train stands with the brake on its way off instead +bool +TController::uphill_brake_committed( double const Velocity ) const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( BrakeCtrlPosition > 0.0 ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); +} + void TController::control_braking_force() { // don't touch the brakes when compressing buffers during coupling/uncoupling @@ -7946,6 +8467,23 @@ void TController::control_braking_force() { cue_action(driver_hint::brakingforcesetzero); } + // AbsAccS is the resultant acceleration, gravity included, so it is compared with the + // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent + auto const accdesiredresultant { AccDesired + fAccDesiredGravity }; + + // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake + // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a + // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve + if( ElapsedTime - fShortfallTime >= 3.0 ) { + auto const shortfall { AbsAccS - accdesiredresultant }; + iShortfallGrowth = ( + ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ? + iShortfallGrowth + 1 : + 0 ); + fShortfall = shortfall; + fShortfallTime = ElapsedTime; + } + if( is_emu() && !ForcePNBrake ) { // właściwie, to warunek powinien być na działający EP // Ra: to dobrze hamuje EP w EZT @@ -7956,14 +8494,15 @@ void TController::control_braking_force() { auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) }; auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? 0.05 : 0.0; - if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold - && ( AbsAccS > AccDesired + accmargin - || BrakeCtrlPosition < 0 ) ) { + if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold + && ( AbsAccS > accdesiredresultant + accmargin + || BrakeCtrlPosition < 0 ) ) + || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) cue_action( driver_hint::brakingforceincrease ); } else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca - if( AbsAccS < AccDesired - 0.05 ) { + if( AbsAccS < accdesiredresultant - 0.05 ) { // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo // TBD: check if the condition isn't redundant with the DecBrake() code if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) { @@ -7978,9 +8517,12 @@ void TController::control_braking_force() { } // type & dt_ezt else { // a stara wersja w miarę dobrze działa na składy wagonowe - if( (AccDesired < fAccGravity - 0.1 && AbsAccS > AccDesired + fBrake_a1[0] // regular braking - || fAccGravity < -0.05 && velocity < -0.1) && - (fBrakeTime < 0.0 || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { // also brake if uphill and slipping back + if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking + || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + (fBrakeTime < 0.0 + // the size of the brake demand decides whether to skip the reaction time, so the brake-only part + // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) + || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { // u góry ustawia się hamowanie na fAccThreshold // jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował // TODO: check whether brake delay variable still has any purpose @@ -7988,7 +8530,21 @@ void TController::control_braking_force() { // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy (3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 } - if ( AccDesired < fAccGravity - 0.05 && AccDesired - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { + else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( AccDesired < 0.0 ) + && ( BrakeCtrlPosition > 0.0 ) + && ( fShortfall > 0.02 ) + && ( iShortfallGrowth >= 2 ) + && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { + // the train has been falling further behind the demand for a while at a handle left alone for longer than + // the brake takes to respond: a small step now, while it still is small, rather than the deep one the + // margin above would allow only once the train is far behind + cue_action( driver_hint::brakingforceincrease ); + iShortfallGrowth = 0; + } + if ( (accdesiredresultant < fAccGravity - 0.05 + || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca @@ -7997,6 +8553,17 @@ void TController::control_braking_force() { cue_action(driver_hint::brakingforcedecrease, (mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 } + // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: + // put it on as the train comes to a stand, and at once if the train has started to roll back + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA < 1.0 ) + && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) + // a train that has slowed down short of where it is to stop and is to pull up further does not get it + && ( VelDesired <= std::abs( velocity ) + 0.5 ) + && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { + cue_action( driver_hint::independentbrakeapply ); + } // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry // instead of releasing the brakes and creeping into obstacle at 1-2 km/h if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) { @@ -8064,8 +8631,14 @@ void TController::control_releaser() { } } // wyluzuj lokomotywę, to szybciej ruszymy + // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent + // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it if( mvOccupied->BrakePress > 0.4 - && mvOccupied->Hamulec->GetCRP() > 4.9 ) { + && ( mvOccupied->Hamulec->GetCRP() > 4.9 + // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go + // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) + || bUphillStart ) + && mvOccupied->Vel < 1.0 ) { actuate = true; } // keep engine brakes released during coupling/uncoupling diff --git a/vehicle/Driver.h b/vehicle/Driver.h index f88e115ac..512d4b8cf 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -24,6 +24,7 @@ auto const EU07_AI_NOACCELERATION = -0.05; auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold +auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; enum TOrders @@ -311,6 +312,12 @@ private: double DirectionalVel() const { return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + double brake_increase_margin() const; + bool uphill_stop_hold() const; + bool uphill_brake_committed( double const Velocity ) const; + void control_uphill_start(); + std::pair train_proximity_margins( bool const Passengerstop ) const; + void update_timers( double const dt ); void update_logs( double const dt ); void determine_consist_state(); @@ -320,6 +327,7 @@ private: void scan_obstacles( double const Range ); void control_wheelslip(); void control_pantographs(); + void control_pantographs_setup( int const Setup ); void control_horns( double const Timedelta ); void control_security_system( double const Timedelta ); void control_handles(); @@ -344,6 +352,11 @@ private: void pick_optimal_speed( double const Range ); void adjust_desired_speed_for_obstacles(); void adjust_desired_speed_for_limits(); + void set_velocity_for_uncoupling(); + bool increase_train_brake(); + void hold_train_coming_to_stand_uphill(); + void adjust_desired_speed_for_final_approach( double const Vel ); + void adjust_desired_speed_for_braking_curve( double const Vel ); void adjust_desired_speed_for_target_speed( double const Range ); void adjust_desired_speed_for_current_speed(); void adjust_desired_speed_for_braking_test(); @@ -358,7 +371,14 @@ private: void control_motor_connectors(); void control_tractive_force(); void increase_tractive_force(); + bool is_too_fast_uphill() const; void control_braking_force(); + // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal, + // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before + double stopping_margin() const { + return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ? + fMinProximityDist + 3.5 : + 0.5 * fMinProximityDist; } void apply_independent_brake_only(); void check_route_ahead( double const Range ); void check_route_behind( double const Range ); @@ -393,6 +413,14 @@ private: double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj) double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie + double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego + bool bStopTargetIsPassengerStop = false; // the point the train is to stop at, found by the last scan of the route, is a passenger stop + double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2] + double fShortfallTime = 0.0; // when that was checked + int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown + bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does + double fUphillStartTime = 0.0; // when the uphill start began + double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie double VelLimit = -1.0; // predkość zadawana przez event jednokierunkowego ograniczenia prędkości // -1: brak ograniczenia prędkości @@ -519,6 +547,9 @@ private: bool TableNotFound( basic_event const *Event, double const Distance ) const; void TableTraceRoute( double fDistance, TDynamicObject *pVehicle ); void TableCheck( double fDistance ); + // called after TSpeedPos::Update() of a position of the speed table, with its spElapsed flag from before it: + // reports the head of the train going past it, if it's a signal showing stop + void CheckSignalPassedAtDanger( TSpeedPos const &Point, bool Passedbefore ) const; TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc ); bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ); bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ); @@ -618,6 +649,7 @@ private: bool IsAnyDoorOpen[ 2 ]; // state of door in the consist bool IsAnyDoorOnlyOpen[ 2 ]; // state of door in the consist regardless of step bool IsAnyDoorPermitActive[ 2 ]; // state of door permit in the consist + door_closure_t DoorClosure{ door_closure_t::none }; // state of the door closure signalling (SOD) of the consist bool IsAnyLineBreakerOpen{ false }; // state of line breaker in all powered vehicles under control bool IsAnyConverterOverloadRelayOpen{ false }; // state of converter overload relays in all vehicles under control bool IsAnyMotorOverloadRelayOpen{ false }; // state of motor overload relays in all vehicles under control diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 46aba815f..b9c55bfac 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" +#include "vehicle/lightsprogrammer.h" + #include "simulation/simulation.h" #include "rendering/lightarray.h" #include "vehicle/Camera.h" @@ -29,6 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "model/MdlMngr.h" #include "model/Model3d.h" +#include "vehicle/doorwings.h" #include "rendering/renderer.h" #include "application/uitranscripts.h" #include "input/messaging.h" @@ -557,20 +560,79 @@ void TDynamicObject::UpdateAxle(TAnim *pAnim) pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); }; +// angle of a slotted lever for given angle of the wheel, which drives the coupling rod with the pin +// all points of the coupling rod move along circles of crank radius, the lever follows the pin sliding in its slot +double TDynamicObject::slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ) { + // crank turned around X axis, the same way as the wheel + auto const wheelangle { glm::radians( Wheelangle ) }; + auto const crank { glm::dvec2( + Lever.crank.x * std::cos( wheelangle ) - Lever.crank.y * std::sin( wheelangle ), + Lever.crank.x * std::sin( wheelangle ) + Lever.crank.y * std::cos( wheelangle ) ) }; + auto const pin { Lever.pin - Lever.crank + crank }; + // angle relative to the pose of the lever in the model, which matches wheel angle 0 + return glm::degrees( std::atan2( pin.y, pin.x ) - std::atan2( Lever.pin.y, Lever.pin.x ) ); +} + +void TDynamicObject::update_slottedlevers() { + + for( auto const &lever : m_slottedlevers ) { + auto const wheelid { ( + ( lever.axle < iAnimType[ ANIM_WHEELS ] ) && ( lever.axle < static_cast( pAnimations.size() ) ) ? + pAnimations[ lever.axle ].dWheelAngle : + 1 ) }; // driving wheels and coupling rods by default + auto const angle { slottedlever_angle( lever, dWheelAngle[ wheelid ] ) }; + auto const futureangle { slottedlever_angle( lever, dWheelAngle[ wheelid ] + m_future_wheels_angle[ wheelid ] ) }; + lever.submodel->SetRotate( float3( 1, 0, 0 ), angle ); + lever.submodel->future_transform = glm::rotate( (float)glm::radians( std::remainder( futureangle - angle, 360.0 ) ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); + } +} + +namespace { + +// the position of the door the animated wing belongs to: its shift or angle from closed +float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { + + return Mover.Doors.instances[ ( + door_wings::on_right_side( Animation->iNumber ) ? + side::right : + side::left ) ].position; +} + +// the wing in the main model, and its namesake in the low poly interior; either can be missing +std::array wing_parts( TAnim const *Animation ) { + + return { Animation->smAnimated, Animation->smInterior }; +} + +// folding door: the smaller wing turns, the larger wing (its child) the other way, the step (child of that) under it +void fold_wing( TSubModel *Wing, door_wings::fold_angles const &Angles ) { + + if( Wing == nullptr ) { return; } + // skrzydło mniejsze + Wing->SetRotate( float3( 0, 0, 1 ), Angles.smaller ); + // skrzydło większe + auto *larger { Wing->ChildGet() }; + if( larger == nullptr ) { return; } + larger->SetRotate( float3( 0, 0, 1 ), Angles.larger ); + // podnóżek? + auto *step { larger->ChildGet() }; + if( step == nullptr ) { return; } + step->SetRotate( float3( 0, 1, 0 ), Angles.step ); +} + +} // namespace + // animacja drzwi - przesuw void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { + if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetTranslate( - glm::vec3{ - 0.0, - 0.0, - door.position } ); + auto const shift { door_wings::slide( door_position( *MoverParameters, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } }; // animacja drzwi - obrót @@ -578,14 +640,12 @@ void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetRotate( - float3(1, 0, 0), - door.position ); + auto const angle { door_position( *MoverParameters, pAnim ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetRotate( float3( 1, 0, 0 ), angle ); + } + } }; // animacja drzwi - obrót @@ -593,31 +653,10 @@ void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - // skrzydło mniejsze - pAnim->smAnimated->SetRotate( - float3(0, 0, 1), - door.position); - - // skrzydło większe - auto *sm = pAnim->smAnimated->ChildGet(); - if( sm == nullptr ) { return; } - - sm->SetRotate( - float3(0, 0, 1), - -door.position - door.position); - - // podnóżek? - sm = sm->ChildGet(); - if( sm == nullptr ) { return; } - - sm->SetRotate( - float3(0, 1, 0), - door.position); + auto const angles { door_wings::fold( door_position( *MoverParameters, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + fold_wing( wing, angles ); + } }; // animacja drzwi - odskokprzesuw @@ -625,20 +664,12 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetTranslate( - glm::vec3{ - std::min( - door.position * 2.f, - MoverParameters->Doors.range_out ), - 0.0, - std::max( - 0.f, - door.position - MoverParameters->Doors.range_out * 0.5f ) } ); + auto const shift { door_wings::plug( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range_out ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } } void TDynamicObject::UpdatePant(TAnim *pAnim) @@ -841,6 +872,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) animation.yUpdate( &animation ); } } + update_slottedlevers(); if( mdModel != nullptr && ObjSqrDist < 50 * 50 ) { @@ -1713,7 +1745,8 @@ TDynamicObject::couple( int const Side ) { if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::control ) ) { // ukrotnionko if( (coupler.AllowedFlag & othercoupler.AllowedFlag & coupling::control) == coupling::control - && coupler.control_type == othercoupler.control_type ) { + && coupler.control_type == othercoupler.control_type + && ( MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | coupling::control ) & coupling::control ) != 0 ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, @@ -2417,6 +2450,8 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" for( auto const &nameprefix : nameprefixes ) { init_sections( mdLowPolyInt, nameprefix, MoverParameters->CompartmentLights.start_type == start_t::manual ); } + // the inside of the door wings, if the interior has them + init_interior_doors(); } // destination sign if( mdModel ) { @@ -2561,6 +2596,26 @@ TDynamicObject::init_sections( TModel3d const *Model, std::string const &Namepre return sectioncount; } +// a door wing of the main model is seen from the outside, lit as the exterior. its namesake in the low poly interior, +// if the model has one, follows its moves and is lit with the interior, by its compartment section if it's in one +void +TDynamicObject::init_interior_doors() { + + if( mdLowPolyInt == nullptr ) { return; } + + for( auto &animation : pAnimations ) { + // the door animation is only set up for a wing found in the main model + if( false == door_wings::is_wing( animation.iFlags ) ) { continue; } + if( ( animation.yUpdate == nullptr ) || ( animation.smAnimated == nullptr ) ) { continue; } + + auto *interiorwing { mdLowPolyInt->GetFromName( animation.smAnimated->pName ) }; + if( ( interiorwing == nullptr ) || ( interiorwing == animation.smAnimated ) ) { continue; } + + interiorwing->WillBeAnimated(); + animation.smInterior = interiorwing; + } +} + bool TDynamicObject::init_destination( TModel3d *Model ) { @@ -5740,6 +5795,35 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } + else if( token == "animslottedlever:" ) { + // lever with a slot, turned by a pin on the coupling rod (e.g. speedometer drive) + // parameters: submodel name, number of axle (from animwheelprefix) driving the coupling rod, crank radius [m], + // pin position relative to the lever axis [m] and crank angle [deg] for wheel angle 0, in local (Y, Z) plane of the lever + // angle is measured from Y axis towards Z axis, i.e. in the direction of rotation around X axis + slottedlever_data lever; + int axle { 1 }; + double crankradius { 0.0 }; + double crankangle { 0.0 }; + parser.getTokens( 6, false ); + parser + >> asAnimName + >> axle + >> crankradius + >> lever.pin.x + >> lever.pin.y + >> crankangle; + lever.submodel = GetSubmodelFromName( mdModel, asAnimName ); + if( lever.submodel != nullptr ) { + lever.submodel->WillBeAnimated(); + lever.axle = std::max( 0, axle - 1 ); + lever.crank = crankradius * glm::dvec2( std::cos( glm::radians( crankangle ) ), std::sin( glm::radians( crankangle ) ) ); + m_slottedlevers.emplace_back( lever ); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); + } + } + else if( token == "animdoorprefix:" ) { // nazwa animowanych drzwi int i, j; @@ -7198,7 +7282,8 @@ void TDynamicObject::RadioStop() if( Mechanik ) { // o ile ktoś go prowadzi if( MoverParameters->SecuritySystem.radiostop_available() - && MoverParameters->Radio ) { + && MoverParameters->Radio + && MoverParameters->RadioFuse ) { // jeśli pojazd ma RadioStop i jest on aktywny // HACK cast until math types unification glm::dvec3 pos = static_cast(vPosition); @@ -7290,26 +7375,22 @@ void TDynamicObject::SetLights() { auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 }; int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers ? light::redmarker_left + light::redmarker_right : 0 }; - int const front { ( isfrontcaboccupied ? end::front : end::rear ) }; - int const rear { 1 - front }; auto const lightpos { MoverParameters->LightsPos - 1 }; - auto const frontlights { automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ front ][ lightpos ] }; - auto const rearlights { automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ rear ][ lightpos ] }; + std::array const cablights { + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ], + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; + // the custom position keeps the lights lit at coupled ends as well + auto const ignorecouplings { MoverParameters->LightsPos == 18 }; auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, coupling::control ) }; while( vehicle != nullptr ) { // set lights on given side if there's no coupling with another vehicle, turn them off otherwise - auto const *frontvehicle{(isfrontcaboccupied ? vehicle->Prev(coupling::coupler) : vehicle->Next(coupling::coupler))}; - auto const *rearvehicle{(isfrontcaboccupied ? vehicle->Next(coupling::coupler) : vehicle->Prev(coupling::coupler))}; - - if (MoverParameters->LightsPos == 18) - { - frontvehicle = nullptr; - rearvehicle = nullptr; - } - - vehicle->RaLightsSet( - frontvehicle == nullptr ? frontlights : 0, - rearvehicle == nullptr ? rearlights : 0 ); + auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { + return false == ignorecouplings + && ( vehicle->MoverParameters->Couplers[ Side ].CouplingFlag & coupling::coupler ) != 0 + && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; + auto const lights { lights_programmer::vehicle_lights( + cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; + vehicle->RaLightsSet( lights.head, lights.rear ); vehicle = isfrontcaboccupied ? vehicle->Next(coupling::control) : vehicle->Prev(coupling::control); } }; @@ -7351,9 +7432,7 @@ void TDynamicObject::RaLightsSet(int head, int rear) bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej if (Controller == Humandriver) { - int ¤tDimPos = MoverParameters->modernDimmerPosition; - auto &dimmerPositions = MoverParameters->dimPositions; - TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; + auto const dps{MoverParameters->currentDimPosition()}; // domyślnie HighBeamLights = false; @@ -7415,9 +7494,7 @@ void TDynamicObject::SetLightDimmings() if (Controller == Humandriver) { - int ¤tDimPos = MoverParameters->modernDimmerPosition; - auto &dimmerPositions = MoverParameters->dimPositions; - TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; + auto const dps{MoverParameters->currentDimPosition()}; // domyślnie HighBeamLights = false; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 577f0f020..bfd477c4f 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -157,6 +157,9 @@ public: float fMaxDist; // do jakiej odległości wykonywana jest animacja NOTE: square of actual distance float fSpeed; // parametr szybkości animacji int iNumber; // numer kolejny obiektu + // door wings only: the submodel of the same name in the low poly interior, if it has one, posed along with + // smAnimated, so the inside of the door can be part of the interior and lit with it + TSubModel *smInterior { nullptr }; TUpdate yUpdate; // metoda TDynamicObject aktualizująca animację /* @@ -316,6 +319,16 @@ private: TSubModel *sm_summer_variant {}; // submodel letniego wariantu TSubModel *sm_autumn_variant {}; // submodel jesiennego wariantu double fWahaczeAmp; + // levers with a slot, turned by a pin on the coupling rod sliding in the slot (e.g. speedometer drive of 401Da) + struct slottedlever_data { + TSubModel *submodel { nullptr }; // lever, turned around its local X axis like the wheels + int axle { 0 }; // index of the axle animation, whose crank drives the coupling rod + glm::dvec2 pin { 0.0 }; // pin position relative to the lever axis for wheel angle 0, in local (Y, Z) plane [m] + glm::dvec2 crank { 0.0 }; // crank vector for wheel angle 0, in local (Y, Z) plane [m] + }; + std::vector m_slottedlevers; + static double slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ); + void update_slottedlevers(); // Winger 160204 - pantografy double pantspeedfactor; // animacje typu przesuw @@ -694,6 +707,8 @@ private: float Load, std::string LoadType, bool Reversed, std::string); int init_sections( TModel3d const *Model, std::string const &Nameprefix, bool const Overrideselfillum ); bool init_destination( TModel3d *Model ); + // pairs the animated door wings with their namesakes in the low poly interior + void init_interior_doors(); void create_controller( std::string const Type, bool const Trainset ); void AttachNext(TDynamicObject *Object, int iType = 1); bool UpdateForce(double dt); diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index af8e9a060..b212dc641 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Gauge.h" #include "vehicle/gaugepositions.h" +#include "vehicle/gaugeduplicates.h" #include "utilities/parser.h" #include "model/Model3d.h" #include "vehicle/DynObj.h" @@ -109,6 +110,14 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu endvalue = -1; bool interpolatescale { false }; + // the control as defined so far in this cab, which a definition marked as its duplicate adds a copy to + // rather than replacing it (eu07/maszyna#527) + std::optional original; + if( gauge_duplicates::adds_copy( true, m_sourcemodel, Owner->mdKabina, Owner->mdLowPolyInt ) ) { + original = *this; + } + scratch_data scratchpad; + Parser.getTokens(); if( Parser.peek() != "{" ) { // old fixed size config @@ -148,7 +157,6 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } // new, variable length section { - scratch_data scratchpad; while( true == Load_mapping( Parser, scratchpad ) ) { // all work done by while() } @@ -190,17 +198,20 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu endscale *= static_cast(mul); } TSubModel *submodel { nullptr }; + m_sourcemodel = nullptr; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { if( source != nullptr && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { // got what we wanted, bail out + m_sourcemodel = source; break; } // there's a possibility the default submodel was named with _off suffix if( source != nullptr && ( submodel = source->GetFromName( submodelname + "_off" ) ) != nullptr ) { // got what we wanted, bail out + m_sourcemodel = source; break; } } @@ -230,6 +241,14 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu Init( submodel, submodelon, type, scale, offset, friction, 0, endvalue, endscale, interpolatescale ); + if( scratchpad.duplicate && original ) { + // a duplicate submodel of the control already defined: the control stays as it was, with one more copy + // animated along with it. the duplicate's own sounds, if any, are left out so the control isn't heard twice + auto duplicate { MirrorCopy() }; + *this = std::move( *original ); + m_mirrors.emplace_back( std::move( duplicate ) ); + } + // return md2 != nullptr; // true, gdy podany model zewnętrzny, a w kabinie nie było }; @@ -240,7 +259,12 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { auto const key { Input.getToken( true, "\n\r\t ,;" ) }; if( true == key.empty() || key == "}" ) { return false; } // if not block end then the key is followed by assigned value or sub-block - if( key == "type:" ) { + if( key == "duplicate:" ) { + // the definition is another submodel of the control defined before it, rather than its replacement + auto const duplicate { Input.getToken( true, "\n\r\t ,;" ) }; + Scratchpad.duplicate = gauge_duplicates::is_duplicate( duplicate ); + } + else if( key == "type:" ) { using enum TGaugeType; auto const gaugetype { Input.getToken( true, "\n\r\t ,;" ) }; m_type = gaugetype == "push" ? push : @@ -249,6 +273,7 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { gaugetype == "delayed" ? push_delayed : gaugetype == "pushtoggle" ? pushtoggle : toggle; // "toggle" and default + m_typedeclared = true; } else if( key == "soundinc:" ) { m_soundfxincrease.deserialize( Input, sound_type::single ); @@ -376,6 +401,22 @@ void TGauge::Update( bool const Power ) { else { m_soundfxoff.play(); } } m_state = state; + UpdateVisibility(); + // update submodel animations + UpdateAnimation( SubModel ); + UpdateAnimation( SubModelOn ); + // the copies follow the control's value and state, each with its own animation + for( auto &mirror : m_mirrors ) { + mirror.m_value = m_value; + mirror.m_targetvalue = m_targetvalue; + mirror.m_state = m_state; + mirror.UpdateVisibility(); + mirror.UpdateAnimation( mirror.SubModel ); + mirror.UpdateAnimation( mirror.SubModelOn ); + } +}; + +void TGauge::UpdateVisibility() const { // toggle submodel visibility only if the active state submodel is present, // keep the default model always visible otherwise if( SubModelOn != nullptr ) { @@ -384,10 +425,26 @@ void TGauge::Update( bool const Power ) { SubModel->iVisible = !m_state; } } - // update submodel animations - UpdateAnimation( SubModel ); - UpdateAnimation( SubModelOn ); -}; +} + +TGauge TGauge::MirrorCopy() const { + + TGauge mirror; + mirror.SubModel = SubModel; + mirror.SubModelOn = SubModelOn; + mirror.m_animation = m_animation; + mirror.m_friction = m_friction; + mirror.m_targetvalue = m_targetvalue; + mirror.m_value = m_value; + mirror.m_offset = m_offset; + mirror.m_scale = m_scale; + mirror.m_endscale = m_endscale; + mirror.m_endvalue = m_endvalue; + mirror.m_interpolatescale = m_interpolatescale; + mirror.m_state = m_state; + mirror.m_sourcemodel = m_sourcemodel; + return mirror; +} void TGauge::AssignFloat(float *fValue) { diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index fdef9c58e..1218c66c2 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -55,9 +55,15 @@ public: void AssignBool(bool *bValue); void UpdateValue(); void AssignState( bool const *State ); + // copies of the control animated along with it, from its definitions marked duplicate: yes + std::vector const &mirrors() const { + return m_mirrors; } // returns offset of submodel associated with the button from the model centre glm::vec3 model_offset() const; TGaugeType type() const; + // whether the definition of the control declared its type, rather than left it at the default + bool type_declared() const { + return m_typedeclared; } inline bool is_push() const { return ( static_cast( type() ) & static_cast( TGaugeType::push ) ) != 0; } @@ -74,6 +80,7 @@ private: // types struct scratch_data { std::optional< std::array > soundproofing; + bool duplicate { false }; // the definition is a duplicate submodel of the control defined before }; // methods // imports member data pair from the config file @@ -83,10 +90,17 @@ private: GetScaledValue() const; void UpdateAnimation( TSubModel *Submodel ) const; + // shows the default or the active state submodel as the state says + void + UpdateVisibility() const; + // the copy of this control's submodels and animation, without its sounds and bindings + TGauge + MirrorCopy() const; // members TGaugeAnimation m_animation { TGaugeAnimation::gt_Unknown }; // typ ruchu TGaugeType m_type { TGaugeType::toggle }; // switch type + bool m_typedeclared { false }; // the type was given with type: in the definition float m_friction { 0.f }; // hamowanie przy zliżaniu się do zadanej wartości float m_targetvalue { 0.f }; // wartość docelowa float m_value { 0.f }; // wartość obecna @@ -95,7 +109,7 @@ private: float m_endscale { -1.f }; // scale applied to the value at the end of accepted value range float m_endvalue { -1.f }; // end value of accepted value range bool m_interpolatescale { false }; - char m_datatype; // typ zmiennej parametru: f-float, d-double, i-int + char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { // wskaźnik na parametr pokazywany przez animację float *fData; @@ -112,6 +126,8 @@ private: sound_source m_soundfxincrease { m_soundtemplate }; // sound associated with increasing control's value sound_source m_soundfxdecrease { m_soundtemplate }; // sound associated with decreasing control's value std::map m_soundfxvalues; // sounds associated with specific values + TModel3d const *m_sourcemodel { nullptr }; // the 3d model the submodel was found in by Load() + std::vector m_mirrors; // duplicate submodels of the control (duplicate: yes), animated along with it }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 201b8972f..d388573e4 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Train.h" #include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" #include "utilities/Globals.h" #include "simulation/simulation.h" @@ -59,6 +61,11 @@ void control_mapper::insert(TGauge const &Gauge, std::string const &Label) { m_controlnames.try_emplace(Gauge.SubModelOn, Label); } + // the duplicate submodels of a control (duplicate: yes) work the control as well (eu07/maszyna#527) + for (auto const &mirror : Gauge.mirrors()) + { + insert(mirror, Label); + } m_names.emplace(Label); } @@ -337,6 +344,12 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::linebreakertoggle, &TTrain::OnCommand_linebreakertoggle}, {user_command::linebreakeropen, &TTrain::OnCommand_linebreakeropen}, {user_command::linebreakerclose, &TTrain::OnCommand_linebreakerclose}, + {user_command::linebreakertoggleb, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenb, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakercloseb, &TTrain::OnCommand_linebreakercloseremote}, + {user_command::linebreakertogglec, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenc, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakerclosec, &TTrain::OnCommand_linebreakercloseremote}, {user_command::fuelpumptoggle, &TTrain::OnCommand_fuelpumptoggle}, {user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable}, {user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable}, @@ -485,6 +498,9 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease}, {user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease}, {user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset}, + {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle}, + {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable}, + {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable}, {user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward}, {user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward}, {user_command::generictoggle0, &TTrain::OnCommand_generictoggle}, @@ -716,7 +732,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); dict->insert("lights_front", mvOccupied->iLights[end::front]); dict->insert("lights_rear", mvOccupied->iLights[end::rear]); - dict->insert("off_from_dimmer", mvOccupied->dimPositions[mvOccupied->modernDimmerPosition].isOff); + dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); if (Dynamic()->Mechanik) { @@ -785,6 +801,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const } } dict->insert("radio", mvOccupied->Radio); + dict->insert("radio_fuse", mvOccupied->RadioFuse); dict->insert("radio_channel", RadioChannel()); dict->insert("radio_volume", m_radiovolume); dict->insert("door_lock", mvOccupied->Doors.lock_enabled); @@ -2235,7 +2252,9 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const // visual feedback Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113 && Train->mvControlled->EpFuse == true) + // the EP fuse is the cab car's (Ctrl+Z switches mvOccupied's), checked by SwitchEPBrake with the rest of + // the control's supply + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113) { Train->mvOccupied->SwitchEPBrake(1); } @@ -3646,22 +3665,42 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data } } +namespace +{ +// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) +bool is_hold_coil_lever(TGauge const &Button) +{ + return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); +} +} // namespace + void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { // press or hold... - if (Train->m_linebreakerstate == 0) + // a single two-state lever stays where it was put, also when the line breaker gets knocked out + auto const latchinglever{Train->ggMainOnButton.SubModel == nullptr && Train->ggMainOffButton.SubModel == nullptr && Train->ggMainButton.SubModel != nullptr && + Train->ggMainButton.type() == TGaugeType::toggle}; + switch (linebreaker::pressed(Train->m_linebreakerstate, latchinglever, Train->ggMainButton.GetDesiredValue() > 0.5)) { + case linebreaker::toggle::close: // ...to close the circuit + if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) + { + // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close + Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); + } // NOTE: bit of a dirty shortcut here OnCommand_linebreakerclose(Train, Command); - } - else if (Train->m_linebreakerstate == 1) - { - // ...to open the circuit + break; + case linebreaker::toggle::open: + // ...to open the circuit, or to put the lever off if the circuit was already opened OnCommand_linebreakeropen(Train, Command); + break; + default: + break; } } else if (Command.action == GLFW_RELEASE) @@ -3694,7 +3733,18 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // visual feedback - if (Train->ggMainOffButton.SubModel != nullptr) + if (is_hold_coil_lever(Train->ggMainOffButton)) + { + // the bistable lever goes over to its other position and stays there + auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; + Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch); + if (false == hold_coil_lever::cuts_off(position)) + { + // the hold coil is fed again, which by itself doesn't close the line breaker + return; + } + } + else if (Train->ggMainOffButton.SubModel != nullptr) { Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -3702,13 +3752,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman { Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); } - else if (Train->ggMainOnButton.SubModel != nullptr) + else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly()) { // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); return; } + // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again // play sound immediately when the switch is hit, not after release Train->fMainRelayTimer = 0.0f; @@ -3717,9 +3768,21 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman return; } // already in the desired state - if (true == Train->mvControlled->MainSwitch(false)) + if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) { Train->m_linebreakerstate = 0; + if (Train->mvControlled->MainSwitchRange() != range_t::local) + { + // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on + // they'd start them again after the delay + for (auto &controls : Train->m_remotelinebreakers) + { + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + controls.main_switch.UpdateValue(0.0); + } + } + } } } else if (Command.action == GLFW_RELEASE) @@ -3731,8 +3794,9 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman { Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); } - if (Train->ggMainOffButton.SubModel != nullptr) + if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton)) { + // (the bistable hold coil lever stays where it was put) Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); } // and the two-state switch too, for good measure @@ -3792,13 +3856,157 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) { // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true) ? 1 : 0; + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? 1 : 0; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; } } +namespace +{ + +// which of the switches of the other vehicles in multiple a command works: 0 the second vehicle's, 1 the third one's +std::size_t remote_linebreaker_index(user_command const Command) +{ + using enum user_command; + return (Command == linebreakertogglec || Command == linebreakeropenc || Command == linebreakerclosec) ? 1 : 0; +} + +// the impulse switches of another vehicle's line breaker spring back when let go, whichever way they were pressed +void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optional &Sound) +{ + if (Controls.on_button.SubModel != nullptr) + { + Controls.on_button.UpdateValue(0.0, Sound); + } + if (Controls.off_button.SubModel != nullptr) + { + Controls.off_button.UpdateValue(0.0, Sound); + } + if (Controls.main_switch.SubModel != nullptr && Controls.main_switch.type() != TGaugeType::toggle) + { + Controls.main_switch.UpdateValue(0.5, Sound); + } + Controls.held_without_switch = false; +} + +} // namespace + +TMoverParameters *TTrain::remote_engine(std::size_t const Index) const +{ + return engine_start::engine(*mvOccupied, *mvControlled, static_cast(Index) + 2); +} + +void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // a two-state switch goes the other way than it stands, an impulse one the other way than the engine is + bool close{false}; + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + close = controls.main_switch.GetDesiredValue() < 0.5; + } + else + { + auto const *engine{Train->remote_engine(index)}; + close = engine == nullptr || false == engine_start::remote_switch::is_running(*engine); + } + if (close) + { + OnCommand_linebreakercloseremote(Train, Command); + } + else + { + OnCommand_linebreakeropenremote(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (controls.on_button.SubModel != nullptr || controls.main_switch.type() != TGaugeType::toggle) + { + // only impulse switches react to release events + release_remote_linebreaker(controls, Train->dsbSwitch); + } + controls.held_without_switch = false; + } +} + +void TTrain::OnCommand_linebreakeropenremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (controls.off_button.SubModel != nullptr) + { + controls.off_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(0.0, Train->dsbSwitch); + } + controls.held_without_switch = false; + if (auto *engine{Train->remote_engine(index)}; engine != nullptr) + { + engine_start::remote_switch::open(*engine); + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_linebreakercloseremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback; the line breaker closes in the train update, once the switch was held long enough + if (controls.on_button.SubModel != nullptr) + { + controls.on_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // no switch in the cab, the command alone holds it + controls.held_without_switch = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::update_remote_linebreakers(double const Deltatime) +{ + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &controls{m_remotelinebreakers[index]}; + auto *engine{remote_engine(index)}; + auto const closeheld{controls.held_without_switch || (controls.main_switch.SubModel != nullptr && controls.main_switch.GetDesiredValue() > 0.95) || + (controls.on_button.SubModel != nullptr && controls.on_button.GetDesiredValue() > 0.95)}; + auto const openheld{controls.off_button.SubModel != nullptr && controls.off_button.GetDesiredValue() > 0.95}; + // as with the cab's own switch, an electric locomotive's impulse switch closes the line breaker when let go + auto const closesonrelease{engine != nullptr && controls.on_button.SubModel != nullptr && engine->EngineType == TEngineType::ElectricSeriesMotor}; + controls.state.update(engine, closeheld, openheld, Deltatime, closesonrelease); + } +} + void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command) { @@ -5152,6 +5360,39 @@ void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Co } } +// the cab interior light set by the light preset just selected, if the preset sets one (eu07/maszyna#529). +// the cab light switch (cablight_sw:) is bound to the light state and follows it by itself +void TTrain::set_cab_light_from_lights_preset() +{ + auto const cablight{mvOccupied->LightsPresetCabLight(mvOccupied->LightsPos)}; + if (false == cablight.has_value()) + { + return; + } + auto const set{[&cablight](TCab &Cab) { + Cab.bLight = cablight->light; + Cab.bLightDim = cablight->dim; + }}; + if (false == DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + set(Cabine[iCabn]); + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Cabine) + { + set(cab); + } + } + // the dimmer switch is driven by commands only, move it along + if (ggCabLightDimButton.SubModel != nullptr) + { + ggCabLightDimButton.UpdateValue(cablight->dim ? 1.f : 0.f); + } +} + void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) { @@ -5173,6 +5414,7 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos + 1 : 1; // wrap mode Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { @@ -5210,6 +5452,7 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos - 1 : Train->mvOccupied->LightsPosNo; // wrap mode Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { @@ -5234,15 +5477,37 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + + if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) { - // turn on - OnCommand_headlightenableleft(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableleft(Train, Command); + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableleft(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 && + (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left) + { + // switch to red + OnCommand_redmarkerenableleft(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableleft(Train, Command); + } } } } @@ -5317,15 +5582,37 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + + if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) { - // turn on - OnCommand_headlightenableright(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableright(Train, Command); + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableright(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 && + (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right) + { + // switch to red + OnCommand_redmarkerenableright(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableright(Train, Command); + } } } } @@ -5852,14 +6139,9 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // update modern dimmer state - - auto &dimPos = Train->mvOccupied->modernDimmerPosition; - if (auto dimCount = Train->mvOccupied->dimPositions.size(); dimPos + 1 < dimCount) - dimPos++; - else if (Train->mvOccupied->modernDimmerCanCycle) - dimPos = 0; // return to 0 - else - return; // już na minimum i nie można cyklicznie + if (false == Train->mvOccupied->stepDimmerPosition(1)) + return; // już na maksimum i nie można cyklicznie + auto const dimPos = Train->mvOccupied->modernDimmerPosition; // update lightning // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -5876,18 +6158,9 @@ void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { - auto &dimPos = Train->mvOccupied->modernDimmerPosition; - auto dimCount = Train->mvOccupied->dimPositions.size(); - - if (dimCount == 0) - return; - - if (dimPos > 0) - dimPos--; - else if (Train->mvOccupied->modernDimmerCanCycle) - dimPos = static_cast(dimCount - 1); // ostatnia pozycja - else + if (false == Train->mvOccupied->stepDimmerPosition(-1)) return; // już na minimum i nie można cyklicznie + auto const dimPos = Train->mvOccupied->modernDimmerPosition; // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -6128,7 +6401,7 @@ void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Co Train->DynamicObject->DimHeadlights = true; */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = 1; // ustawiamy modern dimmer na flage przyciemnienia + Train->DynamicObject->MoverParameters->modernDimmerPosition = Train->DynamicObject->MoverParameters->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia Train->DynamicObject->SetLightDimmings(); } } @@ -7994,41 +8267,101 @@ void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->Radio) - { - // turn on - OnCommand_radioenable(Train, Command); - } - else - { - // turn off - OnCommand_radiodisable(Train, Command); - } + // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons + Train->mvOccupied->Radio = (false == Train->mvOccupied->Radio); } void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) { - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->mvOccupied->Radio) + if (Command.action == GLFW_PRESS) { Train->mvOccupied->Radio = true; + // visual feedback + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } } } void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->Radio = false; + // visual feedback + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the +// radio-stop flag included +void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command) { if (Command.action != GLFW_PRESS) { return; } - if (Train->mvOccupied->Radio) + // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the + // radiofuseon_sw:/radiofuseoff_sw: buttons + Train->mvOccupied->RadioFuse = (false == Train->mvOccupied->RadioFuse); +} + +void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) { - Train->mvOccupied->Radio = false; + Train->mvOccupied->RadioFuse = true; + // visual feedback + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->RadioFuse = false; + // visual feedback + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } } } @@ -8365,6 +8698,20 @@ bool TTrain::Update(double const Deltatime) // because the state of the line breaker isn't changed to match, we need to do it here manually m_linebreakerstate = 0; } + if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) + { + if (true == mvControlled->Mains) + { + // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: + // put the lever back on to match, like the line breaker state above + ggMainOffButton.UpdateValue(0.0); + } + else if (m_linebreakerstate == 2) + { + // the hold coil was cut off while the closing button was held, the line breaker won't close on its release + m_linebreakerstate = 0; + } + } if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 || @@ -8397,8 +8744,10 @@ bool TTrain::Update(double const Deltatime) if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) { // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true) ? 1 : 0; + m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? 1 : 0; } + // the switches of the other vehicles in multiple + update_remote_linebreakers(Deltatime); // door permits for (auto idx = 0; idx < 2; ++idx) { @@ -8992,6 +9341,7 @@ bool TTrain::Update(double const Deltatime) btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); + btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started // boczniki // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos @@ -9053,9 +9403,9 @@ bool TTrain::Update(double const Deltatime) // KURS90 btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); - btLampkaRadio.Turn(mvOccupied->Radio); + btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioStopFlag); + btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) @@ -9063,7 +9413,17 @@ bool TTrain::Update(double const Deltatime) btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); } - btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); + if (DynamicObject->Mechanik != nullptr) + { + // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole + // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. + // without it, the lock of the vehicle's own doors, as before + btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); + } + else + { + btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); + } btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym @@ -9151,6 +9511,7 @@ bool TTrain::Update(double const Deltatime) btLampkaSprezarka.Turn(false); btLampkaSprezarkaOff.Turn(false); btLampkaFuelPumpOff.Turn(false); + btLampkaOilPump.Turn(false); btLampkaBezoporowa.Turn(false); btLampkaHamowanie1zes.Turn(false); btLampkaHamienie.Turn(false); @@ -9498,6 +9859,12 @@ bool TTrain::Update(double const Deltatime) ggMainOffButton.Update(); ggMainOnButton.Update(); ggMainButton.Update(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Update(); + remotelinebreaker.on_button.Update(); + remotelinebreaker.off_button.Update(); + } ggSecurityResetButton.Update(); ggSHPResetButton.Update(); ggReleaserButton.Update(); @@ -9523,6 +9890,10 @@ bool TTrain::Update(double const Deltatime) ggRadioVolumeSelector.Update(); ggRadioVolumePrevious.Update(); ggRadioVolumeNext.Update(); + ggRadioOnButton.Update(); + ggRadioOffButton.Update(); + ggRadioFuseOnButton.Update(); + ggRadioFuseOffButton.Update(); ggDepartureSignalButton.Update(); /* ggPantFrontButton.Update(); @@ -10991,6 +11362,13 @@ void TTrain::clear_cab_controls() ggMaxCurrentCtrl.Clear(); ggMainOffButton.Clear(); ggMainOnButton.Clear(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Clear(); + remotelinebreaker.on_button.Clear(); + remotelinebreaker.off_button.Clear(); + remotelinebreaker.held_without_switch = false; + } ggSecurityResetButton.Clear(); ggSHPResetButton.Clear(); ggReleaserButton.Clear(); @@ -11063,6 +11441,10 @@ void TTrain::clear_cab_controls() ggRadioVolumeSelector.Clear(); ggRadioVolumePrevious.Clear(); ggRadioVolumeNext.Clear(); + ggRadioOnButton.Clear(); + ggRadioOffButton.Clear(); + ggRadioFuseOnButton.Clear(); + ggRadioFuseOffButton.Clear(); ggDoorLeftPermitButton.Clear(); ggDoorRightPermitButton.Clear(); ggDoorPermitPresetButton.Clear(); @@ -11184,6 +11566,7 @@ void TTrain::clear_cab_controls() btLampkaSprezarkaOff.Clear(); btLampkaSprezarkaBOff.Clear(); btLampkaFuelPumpOff.Clear(); + btLampkaOilPump.Clear(); btLampkaNapNastHam.Clear(); btLampkaOporyB.Clear(); btLampkaStycznB.Clear(); @@ -11221,6 +11604,7 @@ void TTrain::clear_cab_controls() ggLeftEndLightButton.Clear(); ggRightEndLightButton.Clear(); ggLightsButton.Clear(); + ggCompressorListButton.Clear(); // hunter-230112 ggRearLeftLightButton.Clear(); ggRearRightLightButton.Clear(); @@ -11242,6 +11626,22 @@ void TTrain::set_cab_controls(int const Cab) { // instead of single main button there can be on/off pair ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate > 0 ? 1.f : 0.f); } + // line breakers of the other vehicles in multiple + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &mainswitch{m_remotelinebreakers[index].main_switch}; + if (mainswitch.SubModel == nullptr) + { + continue; + } + if (mainswitch.type() == TGaugeType::push) + { + mainswitch.PutValue(0.5f); + continue; + } + auto const *engine{remote_engine(index)}; + mainswitch.PutValue(engine != nullptr && engine_start::remote_switch::is_running(*engine) ? 1.f : 0.f); + } if (ggModernLightDimSw.SubModel != nullptr) { @@ -11606,6 +12006,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-compressoroff:", btLampkaSprezarkaOff}, {"i-compressorboff:", btLampkaSprezarkaBOff}, {"i-fuelpumpoff:", btLampkaFuelPumpOff}, + {"i-oilpump:", btLampkaOilPump}, {"i-voltbrake:", btLampkaNapNastHam}, {"i-resistorsb:", btLampkaOporyB}, {"i-contactorsb:", btLampkaStycznB}, @@ -11733,6 +12134,12 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"maxcurrent_sw:", ggMaxCurrentCtrl}, {"main_off_bt:", ggMainOffButton}, {"main_on_bt:", ggMainOnButton}, + {"mainb_sw:", m_remotelinebreakers[0].main_switch}, + {"mainb_off_bt:", m_remotelinebreakers[0].off_button}, + {"mainb_on_bt:", m_remotelinebreakers[0].on_button}, + {"mainc_sw:", m_remotelinebreakers[1].main_switch}, + {"mainc_off_bt:", m_remotelinebreakers[1].off_button}, + {"mainc_on_bt:", m_remotelinebreakers[1].on_button}, {"security_reset_bt:", ggSecurityResetButton}, {"shp_reset_bt:", ggSHPResetButton}, {"releaser_bt:", ggReleaserButton}, @@ -11805,6 +12212,10 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"radiovolume_sw:", ggRadioVolumeSelector}, {"radiovolumeprev_sw:", ggRadioVolumePrevious}, {"radiovolumenext_sw:", ggRadioVolumeNext}, + {"radioon_sw:", ggRadioOnButton}, + {"radiooff_sw:", ggRadioOffButton}, + {"radiofuseon_sw:", ggRadioFuseOnButton}, + {"radiofuseoff_sw:", ggRadioFuseOffButton}, /* { "pantfront_sw:", ggPantFrontButton }, { "pantrear_sw:", ggPantRearButton }, @@ -11962,6 +12373,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled}, {"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled}, {"radio_sw:", &mvOccupied->Radio}, + {"radiofuse_sw:", &mvOccupied->RadioFuse}, {"cablight_sw:", &Cabine[iCabn].bLight}, {"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate}, {"couplingdisconnect_sw:", &m_couplingdisconnect}, diff --git a/vehicle/Train.h b/vehicle/Train.h index 009b349b4..dd077e366 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "vehicle/Button.h" #include "vehicle/Gauge.h" +#include "vehicle/enginestart.h" #include "audio/sound.h" #include "scripting/PyInt.h" #include "input/command.h" @@ -189,6 +190,8 @@ class TTrain { // sets cabin controls based on current state of the vehicle // NOTE: we can get rid of this function once we have per-cab persistent state void set_cab_controls( int const Cab ); + // sets the cab interior light as the selected light preset says, if it says anything (eu07/maszyna#529) + void set_cab_light_from_lights_preset(); // initializes a gauge matching provided label. returns: true if the label was found, false otherwise bool initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex); // initializes a button matching provided label. returns: true if the label was found, false otherwise @@ -214,6 +217,10 @@ class TTrain { void change_pantograph_selection( int const Change ); // helper, common part of pantograh valves state update methods void update_pantograph_valves(); + // the Index-th other vehicle in multiple whose engine the cab starts with its own switches (0: mainb_*, 1: mainc_*) + TMoverParameters *remote_engine( std::size_t const Index ) const; + // the switches starting the engines of the other vehicles in multiple, for Deltatime seconds + void update_remote_linebreakers( double const Deltatime ); // update function subroutines void update_sounds( double const Deltatime ); void update_sounds_runningnoise( sound_source &Sound ); @@ -338,6 +345,9 @@ class TTrain { static void OnCommand_linebreakertoggle( TTrain *Train, command_data const &Command ); static void OnCommand_linebreakeropen( TTrain *Train, command_data const &Command ); static void OnCommand_linebreakerclose( TTrain *Train, command_data const &Command ); + static void OnCommand_linebreakertoggleremote( TTrain *Train, command_data const &Command ); + static void OnCommand_linebreakeropenremote( TTrain *Train, command_data const &Command ); + static void OnCommand_linebreakercloseremote( TTrain *Train, command_data const &Command ); static void OnCommand_fuelpumptoggle( TTrain *Train, command_data const &Command ); static void OnCommand_fuelpumpenable( TTrain *Train, command_data const &Command ); static void OnCommand_fuelpumpdisable( TTrain *Train, command_data const &Command ); @@ -489,6 +499,9 @@ class TTrain { static void OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command); static void OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command); static void OnCommand_radiovolumeset(TTrain *Train, command_data const &Command); + static void OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command); + static void OnCommand_radiofuseenable(TTrain *Train, command_data const &Command); + static void OnCommand_radiofusedisable(TTrain *Train, command_data const &Command); static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command ); static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command ); static void OnCommand_generictoggle( TTrain *Train, command_data const &Command ); @@ -570,6 +583,15 @@ public: // reszta może by?publiczna TGauge ggMainOffButton; TGauge ggMainOnButton; TGauge ggMainButton; // EZT + // the line breaker / engine start switches of the second and the third vehicle in multiple (mainb_*, mainc_*) + struct remote_linebreaker { + TGauge main_switch; // mainb_sw: + TGauge on_button; // mainb_on_bt: + TGauge off_button; // mainb_off_bt: + bool held_without_switch{ false }; // closed by a command, in a cab without a switch for it + engine_start::remote_switch state; + }; + std::array m_remotelinebreakers; TGauge ggSecurityResetButton; TGauge ggSHPResetButton; TGauge ggReleaserButton; @@ -595,6 +617,10 @@ public: // reszta może by?publiczna TGauge ggRadioVolumeSelector; TGauge ggRadioVolumePrevious; TGauge ggRadioVolumeNext; + TGauge ggRadioOnButton; + TGauge ggRadioOffButton; + TGauge ggRadioFuseOnButton; + TGauge ggRadioFuseOffButton; TGauge ggUpperLightButton; TGauge ggLeftLightButton; TGauge ggRightLightButton; @@ -760,6 +786,7 @@ public: // reszta może by?publiczna TButton btLampkaSprezarkaOff; TButton btLampkaSprezarkaBOff; TButton btLampkaFuelPumpOff; + TButton btLampkaOilPump; TButton btLampkaBocznik1; TButton btLampkaBocznik2; TButton btLampkaBocznik3; diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h new file mode 100644 index 000000000..07286aac8 --- /dev/null +++ b/vehicle/doorwings.h @@ -0,0 +1,52 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include + +// the poses of the animated door wings of a vehicle, for the door position of the mover. a wing is posed alike +// in the main model and, when the low poly interior has a submodel of the same name, in the interior as well +namespace door_wings { + +// whether the animation with the given flags (TAnim::iFlags, the kind of animation in bits 4-7) moves a door wing +inline bool is_wing(int const Flags) { + return (Flags & 0xF0) == 0x10; +} + +// odd numbered wings (door1, door3...) are on the left side of the vehicle, even numbered on the right +inline bool on_right_side(int const Number) { + return (Number & 1) == 0; +} + +// sliding door (type 1): shifted along the vehicle +inline glm::vec3 slide(float const Position) { + return {0.f, 0.f, Position}; +} + +// plug door (type 4): pushed out first, up to Rangeout, then slid along the vehicle +inline glm::vec3 plug(float const Position, float const Rangeout) { + return {std::min(Position * 2.f, Rangeout), 0.f, std::max(0.f, Position - Rangeout * 0.5f)}; +} + +// folding door (type 3): the angles of the smaller wing, of the larger wing (its child) and of the step (the +// child of the larger wing) +struct fold_angles { + float smaller; + float larger; + float step; +}; + +inline fold_angles fold(float const Position) { + return {Position, -Position - Position, Position}; +} + +} // namespace door_wings diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp new file mode 100644 index 000000000..feb4445ce --- /dev/null +++ b/vehicle/enginestart.cpp @@ -0,0 +1,109 @@ +/* +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 "vehicle/enginestart.h" + +#include "McZapkie/MOVER.h" +#include "utilities/utilities.h" + +namespace engine_start { + +namespace { + +// whether the vehicle has an engine the cab can start, the same test the tachometers of the vehicles in multiple make +bool has_engine(TMoverParameters const &Vehicle) { + return Vehicle.Power > 0.01; +} + +// walks from Start through its coupler Side along the control cable, and returns the Number-th vehicle with an engine +// other than Skipped it meets; Number is lowered by the ones it met when it doesn't get that far +TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMoverParameters const &Skipped, int &Number) { + auto const *vehicle{&Start}; + auto side{Side}; + // a train can't loop back on itself, the limit only guards against a broken chain of couplers + for (auto steps = 0; steps < 1000; ++steps) { + auto const &coupler{vehicle->Couplers[side]}; + if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, coupling::control)) { + return nullptr; + } + // onwards through the other end of the next vehicle, whichever way round it stands + side = 1 - coupler.ConnectedNr; + vehicle = coupler.Connected; + if (vehicle == &Skipped || false == has_engine(*vehicle)) { + continue; + } + --Number; + if (Number == 0) { + return coupler.Connected; + } + } + return nullptr; +} + +} // namespace + +TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number) { + if (Number < 1) { + return nullptr; + } + if (Number == 1) { + return &Controlled; + } + // the cab's own vehicle is the first one + auto others{Number - 1}; + // behind the cab is the rear end of a vehicle driven from its front cab, and the other way round + int const behind{Occupied.CabOccupied < 0 ? end::front : end::rear}; + if (auto *found{find_along(Occupied, behind, Controlled, others)}; found != nullptr) { + return found; + } + return find_along(Occupied, 1 - behind, Controlled, others); +} + +void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool const Openheld, double const Deltatime, bool const Closesonrelease) { + if (Engine != m_engine) { + // another vehicle under the switch, after a change in the train + m_engine = Engine; + m_heldtime = 0.0; + m_ready = false; + } + if (Engine == nullptr) { + return; + } + if (Openheld || is_running(*Engine)) { + // the switch opening the circuit is held down, or there's nothing left to start + m_heldtime = 0.0; + m_ready = false; + return; + } + if (Closeheld && Engine->MainSwitchCheck()) { + m_heldtime += Deltatime; + } + if (m_heldtime > Engine->InitialCtrlDelay) { + m_ready = true; + } + if (m_ready && false == (Closesonrelease && Closeheld)) { + Engine->MainSwitch(true, range_t::local); + m_ready = false; + m_heldtime = 0.0; + } + if (false == Closeheld) { + m_heldtime = 0.0; + } +} + +bool remote_switch::open(TMoverParameters &Engine) { + return Engine.MainSwitch(false, range_t::local); +} + +bool remote_switch::is_running(TMoverParameters const &Engine) { + return Engine.Mains || Engine.dizel_startup; +} + +} // namespace engine_start diff --git a/vehicle/enginestart.h b/vehicle/enginestart.h new file mode 100644 index 000000000..77b6a2d93 --- /dev/null +++ b/vehicle/enginestart.h @@ -0,0 +1,46 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +class TMoverParameters; + +// starting the engines (closing the line breakers) of the vehicles in multiple from the cab (eu07/maszyna#80). in +// vehicles like the ST43, the SP32 or the SN61 every engine of the train has its own switches in the cab: main_* work +// the vehicle the cab controls (TTrain::mvControlled: the cab's own vehicle, on an EMU its motor car), mainb_* the +// second one and mainc_* the third one under its control. Engine:JointEngineStart=No in the .fiz of the controlled +// vehicle (on an EMU the motor car's, not the one of the car with the cab) keeps main_* to that vehicle alone +// (TMoverParameters::MainSwitchRange()); by default it works all of them, as before. +namespace engine_start { + +// the Number-th vehicle with an engine under the cab's control: 1 is Controlled, the cab's own; then the others +// connected through the control cable, those behind the cab of Occupied first, the nearest first, then those in front +// of it. nullptr when there are fewer of them +TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number); + +// the switch starting the engine of another vehicle in multiple. like the cab's own switch, it has to be held closed +// for the vehicle's InitialCtrlDelay, with the vehicle ready for it, before the engine starts (the line breaker closes) +class remote_switch { +public: + // one step of Deltatime seconds of the switch of Engine, with the switch held closed (Closeheld) or open (Openheld). + // with Closesonrelease, the line breaker closes when the switch is let go after the delay, as the impulse switch + // of an electric locomotive with series motors does + void update(TMoverParameters *Engine, bool Closeheld, bool Openheld, double Deltatime, bool Closesonrelease); + // opens the line breaker / stops the engine of Engine, the vehicle alone; returns whether it was running + static bool open(TMoverParameters &Engine); + // whether the line breaker of Engine is closed or its engine starting or running + static bool is_running(TMoverParameters const &Engine); + +private: + TMoverParameters const *m_engine{nullptr}; // the vehicle the switch worked the last step + double m_heldtime{0.0}; // how long the switch is held closed with the vehicle ready to start + bool m_ready{false}; // held long enough, the line breaker closes now or when the switch is let go +}; + +} // namespace engine_start diff --git a/vehicle/gaugeduplicates.h b/vehicle/gaugeduplicates.h new file mode 100644 index 000000000..3a20c9306 --- /dev/null +++ b/vehicle/gaugeduplicates.h @@ -0,0 +1,30 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// cab controls with more than one submodel (eu07/maszyna#527): a definition of a control in the .mmd marked +// "duplicate: yes" adds a copy of the control already defined in the cab, instead of replacing it +namespace gauge_duplicates { + +// whether the value of the duplicate: key marks the definition as a duplicate +inline bool is_duplicate(std::string_view const Value) { + return Value == "yes" || Value == "true" || Value == "1"; +} + +// whether a definition adds a copy to the control rather than replacing it: it is marked as a duplicate, and the +// control is already loaded from one of the 3d models of the cab being loaded (Cab, Lowpoly). a control left over +// from another cab, or not loaded at all (Loadedfrom null), has nothing in this cab to add the copy to +template bool adds_copy(bool const Duplicate, Model_ const *Loadedfrom, Model_ const *Cab, Model_ const *Lowpoly) { + return Duplicate && Loadedfrom != nullptr && (Loadedfrom == Cab || Loadedfrom == Lowpoly); +} + +} // namespace gauge_duplicates diff --git a/vehicle/holdcoillever.h b/vehicle/holdcoillever.h new file mode 100644 index 000000000..005bccbd5 --- /dev/null +++ b/vehicle/holdcoillever.h @@ -0,0 +1,34 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the lever of the line breaker's hold coil (eu07/maszyna#364), as on the ET22 and the EP09: the cab's main_off_bt +// control declared with "type: toggle" stays in the position it's put in. Position 0 keeps the hold coil fed, so the +// line breaker can be closed; position 1 cuts the coil off, which opens the line breaker and keeps it from closing +// until the lever is put back. Without the declared type main_off_bt stays the push button it always was, which +// opens the line breaker and springs back. +namespace hold_coil_lever { + +// whether the main_off_bt control is the bistable lever, from the type its definition declares, if it declares one +inline bool is_bistable(bool const Typedeclared, bool const Toggletype) { + return Typedeclared && Toggletype; +} + +// whether the lever in the given position cuts off the hold coil +inline bool cuts_off(float const Position) { + return Position > 0.5f; +} + +// the position the lever goes to when it's operated: the other one +inline float operated(float const Position) { + return cuts_off(Position) ? 0.f : 1.f; +} + +} // namespace hold_coil_lever diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h new file mode 100644 index 000000000..9ae8c2ab0 --- /dev/null +++ b/vehicle/lightsprogrammer.h @@ -0,0 +1,41 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "McZapkie/MOVER.h" + +// the lights the light preset selector (programmer) of the occupied cab gives one vehicle of the consist +namespace lights_programmer { + +// the lights for the vehicle's two ends, in the terms of TDynamicObject::RaLightsSet(): head is the end +// towards the head of the consist (TDynamicObject::Prev()), rear the end towards its tail (Next()) +struct consist_lights { + int head; + int rear; +}; + +// Cablights: the selector's lights for the occupied cab's front and back (Lights[end::front / end::rear]). +// Cabfacinghead: the occupied cab faces the head of the consist. +// Direction: the vehicle's iDirection, 1 when its end::front is towards the head of the consist. +// Coupled: whether another vehicle is coupled at the vehicle's end::front / end::rear; an end with a coupled +// vehicle stays dark +inline consist_lights vehicle_lights(std::array const &Cablights, bool const Cabfacinghead, int const Direction, std::array const &Coupled) { + auto const headlights{Cablights[Cabfacinghead ? end::front : end::rear]}; + auto const rearlights{Cablights[Cabfacinghead ? end::rear : end::front]}; + // the head lights go to the vehicle's end towards the head of the consist whichever way the cab faces, + // so the coupling which keeps them dark is the one at that same end (eu07/maszyna#395) + auto const headend{Direction > 0 ? end::front : end::rear}; + auto const rearend{Direction > 0 ? end::rear : end::front}; + return {Coupled[headend] ? 0 : headlights, Coupled[rearend] ? 0 : rearlights}; +} + +} // namespace lights_programmer diff --git a/vehicle/linebreaker.cpp b/vehicle/linebreaker.cpp new file mode 100644 index 000000000..97eae0325 --- /dev/null +++ b/vehicle/linebreaker.cpp @@ -0,0 +1,26 @@ +/* +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 "vehicle/linebreaker.h" + +namespace linebreaker { + +toggle pressed(int const Breakerstate, bool const Latchinglever, bool const Leveron) { + if (Breakerstate == 1) { + return toggle::open; + } + if (Breakerstate != 0) { + return toggle::none; + } + // the line breaker is open; a lever left on goes off first + return Latchinglever && Leveron ? toggle::open : toggle::close; +} + +} // namespace linebreaker diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h new file mode 100644 index 000000000..370e992cc --- /dev/null +++ b/vehicle/linebreaker.h @@ -0,0 +1,28 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the line breaker (main switch, WS) controls of the cab +namespace linebreaker { + +enum class toggle : int { + none, // the press does nothing + close, // the control goes to its on position, and the line breaker closes if it can + open // the control goes to its off position, and the line breaker opens +}; + +// what a press of the line breaker toggle does. Breakerstate is the state the cab keeps of the line +// breaker (0: open, 1: closed, 2: freshly closed). Latchinglever is a single two-state switch which +// stays where it was put, Leveron that it stands in its on position. such a lever doesn't follow the +// line breaker: knocked out (by the converter overload relay, say) the breaker opens with the lever +// left on, and the lever has to go off before it can be put on again (eu07/maszyna#394) +toggle pressed(int Breakerstate, bool Latchinglever, bool Leveron); + +} // namespace linebreaker diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp index b6e923222..f5f64bef0 100644 --- a/vehicle/smoke.cpp +++ b/vehicle/smoke.cpp @@ -34,7 +34,7 @@ double engine_load(TMoverParameters const &Mover) { } // namespace float vehicle_spawn_count(TMoverParameters const &Mover, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { - if (false == Ontracks) { + if (false == Ontracks || Mover.dizel_FiringCountdown > 0.0) { return 0.f; } // the steady rate of the source, the way a source of the scenery spawns... diff --git a/vehicle/smoke.h b/vehicle/smoke.h index e9dac2622..dbcc131ae 100644 --- a/vehicle/smoke.h +++ b/vehicle/smoke.h @@ -25,6 +25,7 @@ struct spawn_rate { // number of particles the smoke source of a vehicle has to spawn after Timedelta seconds: the steady rate of the // source, plus a share which grows with the work of its engine. a vehicle taken off the tracks (Ontracks false: gone through a portal, or waiting in the pool of the road // traffic) puffs no more, the particles it already let out fade away as usual +// an engine the starter turns but which hasn't fired yet (TMoverParameters::dizel_FiringCountdown) lets out no smoke either float vehicle_spawn_count(TMoverParameters const &Mover, bool Ontracks, spawn_rate const &Rate, double Timedelta); } // namespace smoke diff --git a/vr/openvr_imp.cpp b/vr/openvr_imp.cpp index 15467d006..b3af171b2 100644 --- a/vr/openvr_imp.cpp +++ b/vr/openvr_imp.cpp @@ -495,6 +495,18 @@ std::unordered_map vr_openvr::m_buttonb { "main_on_bt:",{ user_command::linebreakerclose, user_command::none } }, + { "mainb_off_bt:", { + user_command::linebreakeropenb, + user_command::none } }, + { "mainb_on_bt:", { + user_command::linebreakercloseb, + user_command::none } }, + { "mainc_off_bt:", { + user_command::linebreakeropenc, + user_command::none } }, + { "mainc_on_bt:", { + user_command::linebreakerclosec, + user_command::none } }, { "security_reset_bt:", { user_command::alerteracknowledge, user_command::none } }, @@ -660,6 +672,12 @@ std::unordered_map vr_openvr::m_buttonb { "main_sw:", { user_command::linebreakertoggle, user_command::none } }, + { "mainb_sw:", { + user_command::linebreakertoggleb, + user_command::none } }, + { "mainc_sw:", { + user_command::linebreakertogglec, + user_command::none } }, { "radio_sw:", { user_command::radiotoggle, user_command::none } }, @@ -669,6 +687,15 @@ std::unordered_map vr_openvr::m_buttonb { "radiooff_sw:", { user_command::radiodisable, user_command::none } }, + { "radiofuse_sw:", { + user_command::radiofusetoggle, + user_command::none } }, + { "radiofuseon_sw:", { + user_command::radiofuseenable, + user_command::none } }, + { "radiofuseoff_sw:", { + user_command::radiofusedisable, + user_command::none } }, { "radiochannel_sw:", { user_command::radiochannelincrease, user_command::radiochanneldecrease } }, diff --git a/world/Event.cpp b/world/Event.cpp index fa752078b..624cdd714 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1025,13 +1025,42 @@ whois_event::run_() { auto *targetcell { static_cast( std::get( target ) ) }; if( targetcell == nullptr ) { continue; } // event effect code + // +48: station after the next one, unused, stop there or passthrough // +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value) // +32: vehicle name // +24: vehicle type, consist brake level, obstacle distance // +16: load type, load amount, max load amount // +8: destination, direction, engine power // +0: train name, station count, stop on next station - if( m_input.flags & flags::whois_name ) { + if( ( m_input.flags & ( flags::whois_name | flags::whois_load | flags::mode_alt ) ) + == ( flags::whois_name | flags::whois_load ) ) { + // +48 (the whois_name | whois_load combination was unused; +56, same with mode_alt + // set, stays free for a future mode) + // the timetable entry one past the next stop, and whether the train stops there + auto const *owner { ( + m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ? + m_activator->Mechanik : + m_activator->ctOwner ) }; + auto const *entry { ( + owner != nullptr ? + &owner->TrainTimetable().TimeTableEntryAhead( 1 ) : + nullptr ) }; + auto const aheadname { ( entry != nullptr ? entry->StationName : "none" ) }; + auto const aheadstop { ( entry != nullptr && entry->Ah >= 0 ? 1 : 0 ) }; + + targetcell->UpdateValues( + aheadname, // station after the next one + 0, // unused + aheadstop, // stop there or passthrough + m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); + + WriteLog( + "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " + + "[station after next: " + aheadname + "], " + + "[X], " + + "[stop there: " + ( aheadstop != 0 ? "yes" : "no" ) + "]" ); + } + else if( m_input.flags & flags::whois_name ) { // +32 or +40 // next station name if( m_input.flags & flags::mode_alt ) { diff --git a/world/mtable.cpp b/world/mtable.cpp index b69cacfb9..123ae00f6 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -77,6 +77,15 @@ bool TTrainParameters::IsLastStop() const { return StationIndex >= StationCount; } +TMTableLine const &TTrainParameters::TimeTableEntryAhead( int Offset ) const +{ // wpis rozkladu Offset pozycji za aktualnym (bez pomijania przelotow); + // poza zakresem 1..StationCount zwraca techniczny wpis zerowy + int const idx { StationIndex + Offset }; + if( ( idx < 1 ) || ( idx > StationCount ) ) + return TimeTable[0]; + return TimeTable[idx]; +} + bool TTrainParameters::IsMaintenance() const { if( StationIndex <= StationCount ) diff --git a/world/mtable.h b/world/mtable.h index 44cda7311..841fea815 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -70,6 +70,9 @@ class TTrainParameters std::string ShowRelation() const; double WatchMTable(double DistCounter) const; std::string NextStop() const; + // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount + // zwraca techniczny wpis zerowy (TimeTable[0], StationName=="nowhere", Ah==-1) + TMTableLine const &TimeTableEntryAhead( int Offset ) const; sound_source next_stop_sound() const; sound_source last_stop_sound() const; bool IsStop() const;