From af3d5d9b9fefcc7a2c9d3b40818cc08c0054cc8a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 08:06:04 +0100 Subject: [PATCH 01/22] CI: one pin of each GitHub Action in all workflows, Dependabot updates for them (#331) * ci: one pin of actions/checkout and actions/download-artifact in all workflows build.yml moves from actions/checkout v5.1.0 to the v6.1.0 pin build_bin.yml already uses, and the two unpinned actions/download-artifact@v4 in the publish job of build_bin.yml get the v4.3.0 hash sonar.yml already uses (the commit the v4 tag points at today, so nothing changes at run time). * ci: Dependabot updates for the GitHub Actions One grouped pull request a week for all actions, so the hash pins and their version comments move together in every workflow. --- .github/dependabot.yml | 13 +++++++++++++ .github/workflows/build.yml | 2 +- .github/workflows/build_bin.yml | 8 ++++---- 3 files changed, 18 insertions(+), 5 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..0a520876d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Keeps the GitHub Actions used by the workflows up to date. The actions are pinned by commit hash, with the +# version in a comment; Dependabot updates both. One pull request a week for all of them, so the workflows +# stay on the same versions. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + patterns: + - "*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 758b4c8d5..7eaf891fe 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,7 +31,7 @@ jobs: env: BUILD_WRAPPER_OUT_DIR: bw-output steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 12c5c5866..230e814cf 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -583,25 +583,25 @@ jobs: steps: # the AVX2 build keeps the old name of the download, so the links already handed out still work - name: Download Windows build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64-noavx2 - name: Download Linux build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64-noavx2 From 040e600bf63d52b76c1d521dd725cdbcb791cdc6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:31:47 +0100 Subject: [PATCH 02/22] Test the 6Dg's power demand in steps of 5% on its real definition (#336) * test: the 6Dg's power demand in steps of 5% on its real definition The 6Dg's definition from the game data (6dg_v1/6dg.fiz, converted alone with test_fiz.cpp; SVN r9630 gave its UCList line CtrlValStep=0.05) joins the real vehicles of tests/unit/data/fiz. On it: - the key loads as shipped, and the demand of the universal controller (eimic) moves by 0.05 per tap or per step of the held raise and lower positions, 20 steps from 0 to 1 and back, never in between nor past the ends of the table; - with the engine running, the engine revolutions, generator power, tractive force and speed reached grow with the demand (0.25 to 1); - without the key the demand moves continuously, as before #273. * test: no empty loop bodies and emplace_back in the 6Dg power steps test (Sonar S1116, S6003) --- tests/unit/test_6dg_power_steps.cpp | 219 ++++++++++++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 tests/unit/test_6dg_power_steps.cpp diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp new file mode 100644 index 000000000..d8444d7e5 --- /dev/null +++ b/tests/unit/test_6dg_power_steps.cpp @@ -0,0 +1,219 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "drive.h" + +#include +#include + +// the 6Dg shunter as the game ships it (data/fiz/6dg_v1/6dg.json): the power demand of its universal controller +// (EIMCtrlType 3, UCList) moves in steps of 5% (UCList CtrlValStep=0.05, eu07/maszyna#412), and its diesel-electric +// drive follows the demand. the controller's positions in the 6Dg's table: 3 holds no power, 4 lowers the power +// to 0, 5 holds it, 6 raises it to 1, each at 0.15 a second after IniCDelay (0.5 s) + +using test::definition; +using test::vehicle; + +namespace { + +constexpr int no_power{3}; +constexpr int lower{4}; +constexpr int hold{5}; +constexpr int raise{6}; + +definition shipped() { + return definition::fiz("6dg_v1/6dg"); +} + +void move_to(vehicle &Loco, int const Position) { + // one notch at a time, as far as the controller goes + while (Loco->MainCtrlPos < Position) { + if (false == Loco->IncMainCtrl(1)) { + break; + } + } + while (Loco->MainCtrlPos > Position) { + if (false == Loco->DecMainCtrl(1)) { + break; + } + } + REQUIRE(Loco->MainCtrlPos == Position); +} + +// the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power +void get_ready(vehicle &Loco, test::track const &Track) { + auto driven{test::driving(Loco)}; + REQUIRE(test::start_up(driven, Track)); + test::release_brakes(driven.cab); + move_to(Loco, no_power); + for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { + Loco->DirectionForward(); + } + REQUIRE(Loco->DirActive > 0); + // the brake pipe was charged during the start-up: the brakes release slowly (about a minute), and the pressure + // switch keeps the line contactors open while the brake cylinders hold over 2 bar + for (int second = 0; second < 180 && Loco->BrakePress > 0.1; ++second) { + test::drive(driven, Track, 1.0); + } + REQUIRE(Loco->BrakePress <= 0.1); + // the line contactors close on the first position past the ones with no power, as the driver passes it + move_to(Loco, lower); + test::drive(driven, Track, 1.0); + move_to(Loco, hold); + test::drive(driven, Track, 5.0); + REQUIRE(Loco->Mains); // the engine running + REQUIRE(Loco->StLinFlag); // the line contactors closed + REQUIRE(false == Loco->SpeedCtrlUnit.IsActive); // the demand of the controller drives, not the speed control + REQUIRE(Loco->eimic == doctest::Approx(0.0)); +} + +// a tap of the controller onto the given position and back onto holding, then a second of running +void tap(vehicle &Loco, int const Position, test::track const &Track) { + move_to(Loco, Position); + Loco.step(Track); + move_to(Loco, hold); + test::drive(test::driving(Loco), Track, 1.0); +} + +// the changes of the demand while the controller stays on the given position for Seconds +std::vector changes_held(vehicle &Loco, int const Position, double const Seconds, test::track const &Track) { + std::vector changes; + move_to(Loco, Position); + auto previous{Loco->eimic}; + for (int i = 0; i < std::lround(Seconds / 0.01); ++i) { + if (Loco->SecuritySystem.is_blinking()) { + Loco->SecuritySystemReset(); // the driver acknowledging the vigilance + } + Loco.step(Track); + if (std::abs(Loco->eimic - previous) > 1e-9) { + changes.push_back(Loco->eimic - previous); + previous = Loco->eimic; + } + } + return changes; +} + +} // namespace + +TEST_CASE("6Dg: the shipped definition sets the controller's power demand in steps of 5%") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped(), 0.0, "test", 1}; + // the key as the game data has it, on the controller it acts on + REQUIRE(loco->EIMCtrlType == 3); + CHECK(loco->UniCtrlValStep == doctest::Approx(0.05)); + // the ends of the table: raising goes up to 1, lowering down to 0, 20 steps of 0.05 between them + auto const top{loco->UniCtrlList[raise].SetCtrlVal}; + auto const bottom{loco->UniCtrlList[lower].SetCtrlVal}; + REQUIRE(top == doctest::Approx(1.0)); + REQUIRE(bottom == doctest::Approx(0.0)); + REQUIRE(loco->UniCtrlList[raise].MaxCtrlVal == doctest::Approx(top)); + REQUIRE(loco->UniCtrlList[lower].MinCtrlVal == doctest::Approx(bottom)); + auto const steps{static_cast(std::lround((top - bottom) / 0.05))}; + CHECK(steps == 20); + get_ready(loco, line); + + SUBCASE("tapped: every tap moves the demand by one step, up to the top and down to the bottom, and no further") { + auto changed{0}; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, raise, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::min(top, before + 0.05))); + CHECK(loco->eimic <= top + 1e-9); + CHECK(loco->eimic_real == doctest::Approx(loco->eimic)); // the demand reaching the drive + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(top)); + + changed = 0; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, lower, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::max(bottom, before - 0.05))); + CHECK(loco->eimic >= bottom - 1e-9); + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(bottom)); + } + + SUBCASE("held: the demand goes over the whole range in steps of 0.05, never in between nor past the ends") { + // 20 steps of 0.05 at 0.15 a second take under 7 s, after the initial delay + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() == static_cast(steps)); + for (auto const change : up) { + CHECK(change == doctest::Approx(0.05)); + } + CHECK(loco->eimic == doctest::Approx(top)); + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() == static_cast(steps)); + for (auto const change : down) { + CHECK(change == doctest::Approx(-0.05)); + } + CHECK(loco->eimic == doctest::Approx(bottom)); + } +} + +TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { + test::track const line{0.15, 0.0}; + struct reading { + double demand; + double revolutions; // of the engine, after the demand is set + double force; // tractive + double power; // of the generator + double speed; // reached after the same time + }; + std::vector readings; + for (auto const taps : {5, 10, 15, 20}) { + CAPTURE(taps); + test::reseed_random(); + vehicle loco{shipped(), 0.0, "test", 1}; + get_ready(loco, line); + for (int i = 0; i < taps; ++i) { + move_to(loco, raise); + loco.step(line); + move_to(loco, hold); + loco.step(line); + } + REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); + REQUIRE(loco->eimic_real == doctest::Approx(0.05 * taps)); + test::drive(test::driving(loco), line, 10.0); + readings.emplace_back(loco->eimic_real, loco->enrot, std::abs(loco->Ft), loco->EnginePower, std::abs(loco.speed())); + } + // at 0.25, 0.5, 0.75 and 1: the engine at 897, 1198, 1499 and (still running up to) 1800 rpm as the WWList table + // gives, about 28, 37, 48 and 59 kN, 87, 261, 445 and 663 kW, 14, 24, 28 and 30 km/h + for (std::size_t i = 1; i < readings.size(); ++i) { + CAPTURE(i); + INFO("demand " << readings[i].demand << ": " << readings[i].revolutions * 60.0 << " rpm, " << readings[i].force << " N, " << readings[i].power << " kW, " << readings[i].speed + << " km/h; before it " << readings[i - 1].revolutions * 60.0 << " rpm, " << readings[i - 1].force << " N, " << readings[i - 1].power << " kW, " + << readings[i - 1].speed << " km/h"); + CHECK(readings[i].demand > readings[i - 1].demand); + CHECK(readings[i].revolutions > readings[i - 1].revolutions); + CHECK(readings[i].force > readings[i - 1].force); + CHECK(readings[i].power > readings[i - 1].power); + CHECK(readings[i].speed > readings[i - 1].speed); + } +} + +TEST_CASE("6Dg: without CtrlValStep the demand moves continuously between the rows of the table, as before") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped().remove("UCList", "CtrlValStep"), 0.0, "test", 1}; + REQUIRE(loco->UniCtrlValStep == 0.0); + get_ready(loco, line); + // a tap moves it by 0.01 only + tap(loco, raise, line); + CHECK(loco->eimic == doctest::Approx(0.01)); + // held, it goes on at the row's 0.15 a second after the initial delay, a little every step + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() > 100); + for (auto const change : up) { + CHECK(change > 0.0); + CHECK(change < 0.05 - 1e-6); + } + CHECK(loco->eimic == doctest::Approx(1.0)); // up to the top of the table, as with the steps + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() > 100); + CHECK(loco->eimic == doctest::Approx(0.0)); +} From 791281b306f8d549a4ee7046b5a9159978e2bee5 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:06 +0100 Subject: [PATCH 03/22] Refactor/mover long functions (#239) * test: real vehicles and golden traces in the unit tests The game's own vehicles (dynamic/ of the release used for the tests) as JSON of what the game's vehicle loader reads of their .fiz files, includes expanded: test_fiz.cpp converts them on demand and checks the loader reads the same sections, values and rows as of the game's file (fiz.h). Chosen to cover every engine type, brake valve, brake handle, local brake, coupler type, door type and brake delay set the game data uses. Golden traces (golden.h) characterise the simulation, compared within a relative tolerance or exactly, re-recorded with EU07_UNIT_TESTS_UPDATE_GOLDEN=1: - the parameters of every real vehicle as loaded, - the brakes of every real vehicle through charge, service steps, release, overcharge and emergency, on every brake delay setting, - every position of every driver's and local brake handle, - every powered vehicle started up the way the AI does it, driven to full power and braked to a stop (drive.h), - the real electric units and a locomotive with wagons driven whole, as trains of coupled vehicles stepped the way the game steps them (consist.h), - scenarios of the controls (scenario.h): doors, reversing and cab change, slip and sand, emergency stops, releasers, the ep and the electrodynamic brake, heating, loading, a collision, and frames of several physics iterations. * test: commands passed between vehicles Every command RunCommand knows run on every real vehicle and recorded, commands travelling through a train with a vehicle facing backwards, a coupling without the control cable, and loading and unloading by commands. * test: every switch of the cab, sent to the next vehicle Each switch sending its state to the train, each way and to each range, with the controllers and direction among them, on every real vehicle driving another of its kind, recorded for both. * test: the switches of the cab worked on a pair under the catenary The same switches with two seconds for the vehicles to act on each, so the pantographs rise, the main switch closes and the auxiliaries start. * test: gauges of trains in multiple and the damage descriptions The ammeters and the brake force the AI expects, recorded on the electric units and locomotives in multiple driven, the damage described on the driver's panel and ammeters showing the current of controlled vehicles. * test: give load commands their place, as the game does The loading test set its commands with SetInternalCommand, which leaves TCommand::Location as it is: uninitialised in a fresh vehicle, so the distance check of Load= and UnLoad= read garbage and the test failed now and then. The game gives them through PutCommand with the place of the platform, and so do the tests now. * test: brake valves and handles no vehicle of the game data has Fitted to a wagon and to an EU07: the valve variants and handles the loader knows that no real vehicle uses, the CV1 ones and the test handle among them, and a name the loader doesn't know. * test: braking from speed with the automatic ED brake, and a draisine Trains with the EP09, the E6ACT and the EW58 braked by ep, light and full service applications from speed, and the draisine pumped from rest and rolling. Only the E6ACT brings its electrodynamic brake in here. * test: the EP09's electrodynamic brake in service braking held to a stop start_up() took a vehicle for ready once its line breaker was closed and its reservoir full, which a train made already moving is at once: the EP09's manually started converter was never switched on, so there was no 110 V and no electrodynamic brake. It now waits for the converter. The EP09 with wagons is braked from 120 km/h by light, medium, high and full service applications held to a stop: the motors brake, the air of its cylinders is let out and given back as the train slows down. The flag of the electrodynamic brake stays on at a standstill below 2.1 bar. C strings given to CAPTURE are shown as text. * test: the converter switched on before a train is ready, the EW58's ep-staged electrodynamic brake start_up() called a train ready as soon as its line breaker closed and the air was there, so the converter of a unit having it in another car than the cab (the EW58's middle car) was never switched on, and its electrodynamic brake, gated by the 110 V, never came in. The converter and the compressor now always get switched on first. The EW58 brakes electrically by the stages of the ep brake, not by the pipe alone. * test: the ET42 and the 214M railbus among the real vehicles The ET42's halves (its own series motor branch: the motors in series at the high current setting) and the 214MA, a diesel railbus with the hydraulic torque converter, the retarder and the controller of an induction motor drive, converted from the game data and recorded in every sweep of the real vehicles. * test: the wagons' hand brakes released with the train's brakes; the 754, SM31 and SU46 release_brakes() released the hand brake of the driver's vehicle only, so every wagon set up braked kept its hand brake on and got dragged along. It now releases the hand and spring brakes of the whole train, as TController::AutoRewident() does when the AI takes it over, and the traces of the trains with wagons are recorded anew. The 754, the SM31 and the SU46 join the real vehicles for the kinds of the diesel-electrics' field shunting relays the others lack (RelayType 0, 1 and 46). * test: traction on a lost and too high catenary voltage, the ET42, the diesel-electrics' shunting relays The line breaker opened by the voltage relays of a series motor locomotive and by the limits of an induction motor one. The ET42 at the high current setting, which keeps its halves' motors in series, and its switched electrodynamic brake, whose current trips the overload relay from the top speed of the low setting. The field shunting of the diesel-electrics through each kind of their relays, at full power and notched back. * test: the EW58's electrodynamic brake stages, the EU47's speed control and braking at the voltage's limit The stages of the EW58's motor brake set by the positions of its ep handle, the first one alone over 100 km/h. The EU47's second controller holding, raising and lowering the speed set, its local brake setting the flag of the electrodynamic brake without the motors braking, and its brake feeding back less current into a catenary over the drive's MaxV. * test: diesel engines too cold and too hot to start, the 214M railbus's controller and retarder The heat of the diesel engines: at -10 degrees the ones with the lowest water temperature set don't start until the heater warms them, at 88 degrees the ones with a second water circuit don't start while it cools, and the SM42 run hot at full power is kept under its highest temperature by its fans and shutters. The 214M railbus's controller from the air brake through the retarder and neutral to power, its torque converter's lock-up and its gearbox. The controller helpers of the traction tests (full power, waiting for the line contactors, and notching back) move to test::scenario. * test: couplers coupled, uncoupled, broken and colliding; loads assigned, loaded and unloaded Coupling by hand touching or apart and of the same kind or not, with the sounds of what changes; uncoupling a screw coupler pressed together, stretched, with the hoses alone or broken; the automatic couplers of electric units coupling on contact, without the control cable between two kinds; a coupler broken with its brake hose; collisions over 15 km/h derailing. The pantographs set up by the pantstate load, a load of one kind at a time up to the capacity, and the steps of loading and unloading. * test: the battery drained and charged, the pantographs' tank and pressure switch, the 214M's speed control The EU07's battery drained without the converter by the lights and the small compressor until it opens the line breaker and nothing starts, charged by the converter, and switched off. The pantographs on their own leaking tank until the pressure switch opens the line breaker, and the small compressor pumping it up and priming the switch. The 214M railbus's speed control set by its buttons, steps and power limit, braking down with the retarder, and standing by. * test: the MHZ handles' buttons, the valves at speed, every brake material, the NESt3's relays The overload and the high pressure buttons of the MHZ handles. The KE and the LSt at speed in the R and P settings, under the anti-slip request and the releaser button. Every material of the brake shoes and disks the loader takes, braking a wagon from speed, the ones no game vehicle has among them. The CV1_R and the Oerlikon valve's relays set by its name (-ED, AL2 without ESt3) fitted to a wagon. * test: the loader's lists and lines: the 218M, SA134 and 22WEc, a compressor list, Pmax by speed, skipped lines The 218M (V2NList), the SA134 (HTCList) and the Elf 22WEc (ffBrakeList) join the real vehicles for the lists the others lack. Definitions made by the tests for what no game file has: a compressor list, whose table of whole numbers reads a factor of 0.9 as 0; the compressor's limits apart for the rear cab; the highest power of an induction motor drive by the speed, extrapolated past the table; and the lines the loader skips or trims (comments, a hash anywhere, leading spaces, carriage returns). * test: what the cab and the AI call on a vehicle: gauges of the train, the split ED brake, spring brake, cut-off The engine rotation of up to three vehicles in multiple and the lamps of the overload relay and the starting resistors read through the control cable; the engine's idle speed and the ET42's second controller shown in its dynamic brake; the controller of the electrodynamic brake apart from the local brake, which no game vehicle has yet; the spring brake shut off and released, the ep brake's fuse and the handle stepped by the AI; damaged motors cut off; the cab activated by itself; a road vehicle moved across a road, for which the tests' track gets a width; and the lamps and the buzzer of the security system left unattended. * test: the EP05 and its camshaft among the real vehicles, the headlights' colour and brightness The EP05, whose camshaft closes the line breaker and the line contactors by the camshaft's own position, converted from the game data and recorded in every sweep of the real vehicles. The Headlights section, which only the 214M's own file has, in a definition made by the test. * test: what the unit tests reach of the simulation core, what's dead or left, and what they found COVERAGE.md: the blocks of Mover.cpp, hamulce.cpp, Oerlikon_ESt.cpp and friction.cpp the tests run, the code nothing in the game runs, the code only data no game vehicle has would run, what's reachable and left, and the behaviour the tests found that may deserve a look. * test: check invariants of the physics on every step of every golden trace Rules any vehicle keeps whatever a test does (no NaN, cylinders and pipes within their limits, no current with the line breaker or contactors open, no force without power, distance as the speed runs, no acceleration over 5 g), checked on every step, with no comparison to a recorded file. The traces where a test or a game vehicle breaks one are excused with the reason; the vehicles' cases are in the findings of COVERAGE.md. * test: key figures of every golden trace, per part of the run Duration, speeds, distance, time to stop, the brake pipe's lowest pressure and time to recover, the peaks of the cylinders, the motor current and the tractive force, for each part between two events, in data/golden/.figures. Compared within 0.5% or the last decimal, so they hold on any compiler, and an intended change of behaviour shows in a few readable lines. Traces sampled by hand keep none. * test: keep the golden samples out of the repository, recorded on the code before a change The samples of the golden traces are 29 MB and only mean something against the code before the change they check, so they're recorded locally before it (EU07_UNIT_TESTS_UPDATE_GOLDEN=1) and compared after it, and ignored by git. The key figures and the invariants stay, and are what the CI checks. Without samples recorded a trace compares only its key figures, but with EU07_UNIT_TESTS_GOLDEN_EXACT=1, the check of a change which shouldn't alter anything, it fails, so the check can't pass by having nothing to compare. * fix: draw the noise of the control pipe pressure in one order on every compiler The order of the two Random(10) calls in 'Random(10) - Random(10)' is unspecified: GCC draws them the other way round than MSVC Release, which mirrored the control pipe pressure around 5 bar and failed 32 unit tests on the Linux CI. The draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. * test: count the start-up rounds with an integer, not a double (SonarCloud S2193) * test: behaviour in CHECKs, the key figures out of the repository The key figures of the golden traces are recorded with their samples on the code before a change, and compared after it, instead of being kept: a trace without them checks the invariants and its test's CHECKs, which is what the CI runs. The scenarios of the controls state what they show in CHECKs, and the runs of every real vehicle what holds for each of them. Writing them showed scenarios which didn't do what they were named for: the cab change stopped in the engine room, the slip runs put the controller to full power at once and never got the line contactors closed, and the train stopped by the alarm chain never got its pipe charged again. They do it now; the rest went to the findings. * refactor: TractionForce split into its parts and a function per kind of engine TractionForce() makes the engine's revolutions, the ventilators, the engine power and the voltage relays in turn, then the tractive force of its kind of engine, each in a function of its own: the dumb, wheels driven, series motor (with its dynamic brake by stages), diesel, diesel-electric (with the shunt field relays) and induction motor drives (its speed control, brake blending, motor model and the drive without power). The blocks moved line for line; the golden traces of the unit tests, recorded on the code before, compare bit for bit. * refactor: the shunt field relays of types 45 and 46 in functions of their own * refactor: RunCommand split by the area of its commands The controllers, the brakes, the auxiliaries, the power, the doors and the load each in a function of its own; RunCommand() asks them in turn. The branches moved line for line, and the commands are distinct, so the order of the groups changes nothing; the golden traces compare bit for bit. * refactor: the line loop of LoadFIZ_Parse split into table ends, sections and table rows Each part returns where the loop went on to the next line; the dimmer list's row, which never did, still falls through to the next table. The blocks moved line for line, continue became return; every real vehicle loads the same parameters. * refactor: CheckEIMIC split by the kind of the integrated controller The controller, the steps, the four positions and the universal controller each in a function of its own, besides the TRAXX local brake and the limit of the value. The blocks moved line for line; the golden traces compare bit for bit. * refactor: update_doors split into the requests, the movement and the timers of the doors The blocks moved line for line; the golden traces, the doors of the units and wagons among them, compare bit for bit. * refactor: UpdatePipePressure split into its valves The local brake valve, the driver's handle with the pipe lock, the emergency valve, the settings of the distributor and the ep brake of the FVel6 handles each in a function of its own. The blocks moved line for line; the golden traces compare bit for bit. * refactor: PowerCouplersCheck split into the local voltage, the voltages and the currents of the couplers The circuit of a coupler for the coupling being checked comes from TCoupling::power() instead of a nested conditional repeated five times. The blocks moved line for line; the golden traces compare bit for bit. * refactor: CheckLocomotiveParameters split into the brake parts it creates and the state it starts in The distributor valve, the handles, the pipes, and the vehicle ready to depart or braked each in a function of its own; the main pipe's starting pressure comes from InitialScndPipePress() instead of a nested conditional. The blocks moved line for line; every real vehicle loads and runs the same, bit for bit. * refactor: AutoRelayCheck split into the steps of the shunt field, the main relays and the line contactors Each step returns whether it moved, as OK was; the early returns of the main relays' step give false as before, so the relay timer isn't reset after them either. The blocks moved line for line; the golden traces compare bit for bit. * refactor: LoadFIZ_Cntrl and LoadFIZ_Engine split into their parts Cntrl. into the brakes, the controllers and the starts of the devices; Engine: into the diesel, diesel-electric and induction motor parts and what both diesels share. The blocks moved line for line; every real vehicle loads the same, and the golden traces compare bit for bit. * refactor: the steps of the main controller by the kind of the engine in functions of their own IncMainCtrl() and DecMainCtrl() keep the conditions common to all, the switch on the engine moved line for line to IncMainCtrlByEngine() and DecMainCtrlByEngine(). An early return false there gives OK false, after which nothing else happened before either. The golden traces compare bit for bit. * refactor: dizel_AutoGearCheck and Current split into their parts The automatic gearbox's shift and its clutch; the series motors' dynamic brake flag, their current when connected and their failures. The blocks moved line for line; the golden traces compare bit for bit. * refactor: dizel_fillcheck split into the integrated controller's fill and the governor The blocks moved line for line; the golden traces compare bit for bit. * refactor: the diesel-electric's generator and the camshaft's run-down in functions of their own DieselElectricTractionForce() keeps the tractive force, the generator's current and voltage and the shunting mode's power limit moved out; AutoRelayLineContactorsStep() keeps the line contactors, the camshaft's run back to zero moved out, which only ever sets OK. The blocks moved line for line; the golden traces compare bit for bit. * refactor: the battery's drain in a function of its own UpdateBatteryVoltage() takes the drop BatteryDrain() sums up as it did. The blocks moved line for line; the golden traces, the drained battery's among them, compare bit for bit. * refactor: the speed control's regulator, and the couplers' stretch and automatic coupling, in functions of their own CheckSpeedCtrl() keeps the standby and the turn-off, its PI regulator moved out; CouplerForce() keeps the forces, the breaking of a stretched coupler and the coupling on contact moved out. The blocks moved line for line; the golden traces, the couplers tests' among them, compare bit for bit. * refactor: the pantographs' pressure switch and the torque converter in functions of their own UpdatePantVolume() keeps the pantographs' air, its pressure switch moved out; dizel_Momentum() keeps the engine's and clutches' moments, the converter's fill and lockup and its moments moved out. The blocks moved line for line; the golden traces compare bit for bit. * test: the SonarCloud findings in the unit tests std::format for the texts put together, emplace_back, const references, string_view parameters, std::array and std::vector for the C arrays, the ranges algorithms, names no longer shadowing the coupler ends, comments in the empty loops; start_up(), trace::check() and the converter of the definitions split up. BrakeForceR() is const, which it always was in effect, so the gauges test needs no const_cast. The golden traces compare bit for bit. * refactor: the simple SonarCloud findings in Mover.cpp const where the functions change nothing of the vehicle, using enum, a const reference, init-statements, a value never read and an unused parameter dropped, the never read lines of the definition kept in a map with a transparent comparator, the cooling power's default set before it's read. The golden traces compare bit for bit. * refactor: the command groups and the sections of the definition split further RunCommand() asks the pumps, the blowers, the cab and the brake equipment as groups of their own; the doors' permit and remote opening and closing are functions of their own, the latter one for both; LoadFIZ_Section() keeps the sections of values, those opening tables moved to LoadFIZ_TableSection(). No section name begins another, so the order of the checks changes nothing. The golden traces compare bit for bit. * refactor: the doors' requests and the main relays' steps split further update_door_requests() asks door_open_request(), door_close_request(), doors_powered(), door_step_folding() and door_open_duration() for what its nested expressions worked out; AutoRelayMainStep() asks AutoRelayMainUp(), AutoRelayMainNotchUp() and AutoRelayMainDown(), and is indented as it should be. The golden traces compare bit for bit. * refactor: the battery's drain by its state, and the series motors' notches, in functions of their own BatteryDrain() asks BatteryDrainCharged(), BatteryDrainLow() and BatteryDrainSwitchedOff(), each summing the drains as before; the series motors' cases of IncMainCtrlByEngine() and DecMainCtrlByEngine() moved out, and the condition of a notch down by one which was true either way made plain. The golden traces compare bit for bit. * refactor: the universal controller's brake, the clutch, the EN57's camshaft and the driver's handle's supply in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the induction motors' speed control, brake blending and drive split further The speed control by time and by position, the electrodynamic brake's flag and share, the motors' force limits and the inverters' frequency each in a function of its own. The blocks moved line for line; the golden traces compare bit for bit. * refactor: the diesel-electric's characteristic in a function of its own The straight part and the hyperbola of the tractive force, worked out the same way for the integrated controller and the train mode, in DieselElectricForce(). The golden traces compare bit for bit. * refactor: the resistor blowers, the diesel-electric's target revolutions, the gearbox's request and the governor's revolutions in functions of their own The blocks moved line for line, and the governor's body is indented as it should be; the golden traces compare bit for bit. * refactor: the series motors' driving current, the pressure switch's trip, the shunt relays, the Cntrl. train brake and the couplers' current split further The blocks moved line for line; the anti-slip brake's kinds read without the nested conditions, the circuit's current picked by PowerCircuitCurrent() instead of a nested conditional, and the couplers' voltage summed through TCoupling::power(). The golden traces compare bit for bit. * refactor: the nesting Sonar found left in the series motors' current, the pressure switch and the diesel-electric The series motors' dynamic brake without the condition every braking vehicle passed, the pressure switch's priming as an else-if, the integrated controller's force of the diesel-electric in a function of its own. The golden traces compare bit for bit. * refactor: the GetPF() of the EStED and LSt valves split into their state, releaser and cylinders The blocks moved line for line; the golden traces of every real vehicle's brakes compare bit for bit. * refactor: the KE valve's cylinders and its held state in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the FV4a handle's chambers, wave and reductor in functions of their own The blocks moved line for line; the golden traces of every handle position compare bit for bit. * refactor: the MHZ_EN57 handle's time reservoir and supply pressure in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the EP2 valve's state and the ESt valve's held state in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the relays' commands and the diesel-electric's shunting force split out The blocks moved line for line; the golden traces compare bit for bit. * test: the SonarCloud findings in the unit tests std::format for the texts put together, emplace_back, const references, string_view parameters, std::array and std::vector for the C arrays, the ranges algorithms, names no longer shadowing the coupler ends, comments in the empty loops; start_up(), trace::check() and the converter of the definitions split up. BrakeForceR() is const, which it always was in effect, so the gauges test needs no const_cast. The golden traces compare bit for bit. * refactor: the SonarCloud findings left in Mover.cpp and hamulce.cpp The EStED's intermediate flow is computed by a const function and its caller fills the reservoir; the anti-slip brake's kind is read from a string_view; the doors' remote command no longer shadows the enumerator control; the diesel-electric's tractive force and the camshaft's run-down nest less. The golden traces compare bit for bit. * refactor: the door helpers aren't const, the door they change is the vehicle's own * refactor: the power couplers' voltage and current return early for a coupling which isn't a power one --- McZapkie/MOVER.h | 169 + McZapkie/Mover.cpp | 7639 +++++++++++++++++++++++------------------- McZapkie/hamulce.cpp | 732 ++-- McZapkie/hamulce.h | 31 + 4 files changed, 4844 insertions(+), 3727 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index ad9f34271..e34dbc252 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "hamulce.h" #include "couplerphysics.h" #include "derailment.h" @@ -1292,6 +1293,35 @@ struct TCoupling power_coupling power_high; power_coupling power_110v; power_coupling power_24v; + // the circuit of the power coupling given, nullptr for a coupling which isn't one + power_coupling *power(coupling const Coupling) + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } + power_coupling const *power(coupling const Coupling) const + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end @@ -2559,6 +2589,10 @@ class TMoverParameters bool CurrentSwitch(bool const State); bool IsMotorOverloadRelayHighThresholdOn() const; void UpdateBatteryVoltage(double dt); + double BatteryDrain(double dt, bool converteractive) const; + double BatteryDrainCharged(double dt, bool converteractive) const; + double BatteryDrainLow(double dt, bool converteractive) const; + double BatteryDrainSwitchedOff(double dt) const; double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana @@ -2583,6 +2617,20 @@ class TMoverParameters bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); double GetExternalCommand(std::string &Command) const; bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + // the parts of RunCommand(), by the area of the commands + bool RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunCabCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + void DoorPermitCommand(double CValue1, double CValue2); + void DoorRemoteCommand(bool Open, double CValue1, double CValue2); + bool RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); bool RunInternalCommand(); void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); bool CabActivisation(bool const Enforce = false); @@ -2594,6 +2642,11 @@ class TMoverParameters /*! glowny nastawnik:*/ bool IncMainCtrl(int CtrlSpeed); bool DecMainCtrl(int CtrlSpeed); + // the parts of IncMainCtrl() and DecMainCtrl() which depend on the kind of the engine + bool IncMainCtrlByEngine(int CtrlSpeed); + bool IncMainCtrlSeriesMotor(int CtrlSpeed); + bool DecMainCtrlByEngine(int CtrlSpeed); + bool DecMainCtrlSeriesMotor(int CtrlSpeed); bool IsMainCtrlActualNoPowerPos() const; // whether the master controller is actually set to position which won't generate any extra power bool IsMainCtrlNoPowerPos() const; // whether the master controller is set to position which won't generate any extra power bool IsMainCtrlMaxPowerPos() const; @@ -2674,8 +2727,18 @@ class TMoverParameters /*pomocnicze funkcje dla ukladow pneumatycznych*/ void UpdateBrakePressure(double dt); void UpdatePipePressure(double dt); + // the parts of UpdatePipePressure() + void UpdateLocalBrakeValve(double dt); + void UpdateMainValve(double dt); + double MainValveSupply(); + double MainValveHandlePosition() const; + void UpdateEmergencyValve(double dt); + void UpdateDistributorSettings(); + void UpdateEPBrake(); void CompressorCheck(double dt); /*wlacza, wylacza kompresor, laduje zbiornik*/ void UpdatePantVolume(double dt); // Ra + void PantPressureSwitchCheck(); + void PantPressureSwitchTrip(); void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); @@ -2691,6 +2754,42 @@ class TMoverParameters void ComputeTotalForce(double dt); double Adhesive(double staticfriction) const; double TractionForce(double dt); + // the parts of TractionForce(), in the order it makes them + double UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment); + double DieselElectricTargetRevolutions(); + void UpdateVentilators(double dt); + void UpdateResistorBlowers(double dt); + double UpdateEnginePower(); + void VoltageRelaysCheck(); + void DumbTractionForce(double PosRatio); + void WheelsDrivenTractionForce(double dt); + void SeriesMotorTractionForce(double dt); + void SeriesMotorDynamicBrake(double dt); + void DieselEngineTractionForce(double dt, double dmoment, double dtrans); + void DieselElectricTractionForce(double tmp); + void DieselElectricShuntForce(double tmpV, double &tmp); + double DieselElectricDigitalForce(double tmpV, double &tempUmax, double &tempImax); + double DieselElectricForce(double tmpV, double LinePower, double Ratio, double HyperbolaPower) const; + void DieselElectricShuntPower(double tmp); + void DieselElectricGenerator(double tmp, double tempUmax, double tempImax); + void ShuntFieldRelaysCheck(double tmpV, double PosRatio, double tmp); + void ShuntFieldRelaysType2(double tmp); + void ShuntFieldRelaysType41(double tmpV); + void ShuntFieldRelaysType45(); + void ShuntFieldRelaysType46(); + void ShuntFieldRelaysType46Up(); + void ShuntFieldRelaysType46Down(); + void InductionMotorTractionForce(double dt); + void InductionMotorSpeedControl(double dt); + void SpeedControlByTime(double dt); + void SpeedControlByPosition(double dt); + void InductionMotorBrakeBlending(double ActiveInverters, double &PosRatio, double &tmp); + void InductionMotorDynamicBrakeFlag(); + double InductionMotorBrakeRatio(double ActiveInverters, double edBCP); + void InductionMotorDrive(double dt); + void InductionMotorForceLimits(); + void UpdateInverterFrequency(); + void InductionMotorOff(); // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed void update_dieselelectric_dynamic_brake(double dt); double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for @@ -2702,6 +2801,7 @@ class TMoverParameters double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); + void CouplerStretchCheck(int End, double CF, double dt); // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all bool coupler_physics_at(int const End) const; @@ -2840,6 +2940,11 @@ class TMoverParameters void LowVoltagePowerCheck(double const Deltatime); void MainsCheck(double const Deltatime); void PowerCouplersCheck(double const Deltatime, coupling const Coupling); + // the parts of PowerCouplersCheck() + double LocalPowerVoltage(coupling Coupling); + void PowerCouplersVoltage(coupling Coupling, double abslocalvoltage, bool localpowersource); + void PowerCouplersCurrent(coupling Coupling, bool localpowersource); + double *PowerCircuitCurrent(coupling Coupling); void ConverterCheck(double const Timestep); // przetwornica void HeatingCheck(double const Timestep); void WaterPumpCheck(double const Timestep); @@ -2864,6 +2969,11 @@ class TMoverParameters /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ double v2n(void); double Current(double n, double U); + // the parts of Current() + void UpdateSeriesMotorDynamicBrakeFlag(); + double SeriesMotorCurrent(double n, double U, double R, double Mn) const; + double SeriesMotorDrivingCurrent(double n, double U, double Rz, double Mn, int SP) const; + void MotorFailuresCheck(double n); double Momentum(double I) const; double MomentumF(double I, double Iw, int SCP) const; @@ -2873,6 +2983,15 @@ class TMoverParameters bool MinCurrentSwitch(bool State); // przelacznik pradu automatycznego rozruchu bool AutoRelaySwitch(bool State); // przelacznik automatycznego rozruchu bool AutoRelayCheck(); // symulacja automatycznego rozruchu + // the parts of AutoRelayCheck() + bool AutoRelayShuntStep(bool ARFASI2); + bool AutoRelayMainStep(bool ARFASI); + bool AutoRelayMainUp(bool ARFASI); + bool AutoRelayMainNotchUp(); + bool AutoRelayMainDown(); + bool AutoRelayLineContactorsStep(bool motorconnectorsoff); + bool CamshaftRunDown(); + bool CamshaftRunDownEMU(); bool MotorConnectorsCheck(); bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX @@ -2881,10 +3000,19 @@ class TMoverParameters bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania + // the parts of CheckEIMIC(), by the kind of the controller + void EIMICFromController(double brakeDemand, double offset, double multiplier); + void EIMICFromSteps(double dt); + void EIMICFromFourPositions(double dt); + void EIMICFromUniversalController(double dt, double brakeDemand); + void UniversalControllerTrainBrake(); + void EIMICTraxxLocalBrake(double dt); + void EIMICLimit(); // whether the holding brake (StopBrakeDecc) lets go at the power demand (eimic, above 0 when power is demanded) of this step of // Dt seconds: once the demand has stayed above 0 for StopBrakeReleaseDelay. a demand of 0 or less starts the count again bool UpdateStopBrakeRelease(double Demand, double Dt); void CheckSpeedCtrl(double dt); + void SpeedCtrlRegulator(double dt, double accfactor); // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) bool IsSpeedCtrlSeparate() const; @@ -2903,8 +3031,18 @@ class TMoverParameters bool dizel_EngageSwitch(double state); bool dizel_EngageChange(double dt); bool dizel_AutoGearCheck(void); + bool dizel_GearShiftCheck(double VelUp, double VelDown); + bool dizel_GearShiftRequest(double VelUp, double VelDown); + void dizel_ClutchCheck(); + void dizel_ClutchByController(); + void dizel_ClutchByIntegratedController(); double dizel_fillcheck(int mcp, double dt); + double dizel_DigitalFill(double dt); + double dizel_GovernorFill(int mcp, double realfill) const; + double dizel_GovernorRevolutions(int mcp, double &realfill) const; double dizel_Momentum(double dizel_fill, double n, double dt); + void hydro_TCFillCheck(double dt); + void hydro_TCTorque(); double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera void dizel_HeatSet(float const Value); void dizel_Heat(double const dt); @@ -2927,6 +3065,16 @@ class TMoverParameters // 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; + // the parts of update_doors() + // not const: the door they change is one of Doors.instances + void update_door_requests(basic_door &door, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); + void move_door(basic_door &door, double Deltatime); + bool door_open_request(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + bool door_close_request(basic_door const &door, bool localclosecontrol, bool remoteclosecontrol) const; + bool doors_powered() const; + bool door_step_folding(basic_door const &door) const; + float door_open_duration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + void update_door_timers(double Deltatime); /* funkcje dla samochodow*/ bool ChangeOffsetH(double DeltaOffset); @@ -2935,12 +3083,24 @@ class TMoverParameters bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); + // the parts of CheckLocomotiveParameters() + void CreateBrakeValve(); + void CreateBrakeHandles(); + void CreateBrakePipes(); + double InitialScndPipePress(double HosePressure) const; + void SetReadyToDepart(); + void SetBraked(); 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 + // the parts of LoadFIZ_Parse(), for a line of the definition + bool LoadFIZ_TableEnd(std::string const &inputline) const; + bool LoadFIZ_Section(std::string const &inputline, std::map> &fizlines); + bool LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines); + void LoadFIZ_TableRow(std::string const &inputline); void LoadFIZ_Param(std::string const &line); void LoadFIZ_Load(std::string const &line); void LoadFIZ_Dimensions(std::string const &line); @@ -2950,6 +3110,11 @@ class TMoverParameters void LoadFIZ_BuffCoupl(std::string const &line, int const Index); void LoadFIZ_TurboPos(std::string const &line); void LoadFIZ_Cntrl(std::string const &line); + void LoadFIZ_CntrlBrakes(std::string const &line); + void LoadFIZ_CntrlTrainBrake(std::string const &line); + void LoadFIZ_CntrlAntiSlipBrake(std::string_view asb); + void LoadFIZ_CntrlControllers(std::string const &line); + void LoadFIZ_CntrlStarts(std::string const &line); void LoadFIZ_Blending(std::string const &line); void LoadFIZ_DCEMUED(std::string const &line); void LoadFIZ_SpringBrake(std::string const &line); @@ -2959,6 +3124,10 @@ class TMoverParameters void LoadFIZ_Power(std::string const &Line); void LoadFIZ_SpeedControl(std::string const &Line); void LoadFIZ_Engine(std::string const &Input); + void LoadFIZ_EngineDiesel(std::string const &Input); + void LoadFIZ_EngineDieselElectric(std::string const &Input); + void LoadFIZ_EngineInductionMotor(std::string const &Input); + void LoadFIZ_EngineDieselShared(std::string const &Input); void LoadFIZ_Switches(std::string const &Input); void LoadFIZ_MotorParamTable(std::string const &Input); void LoadFIZ_Circuit(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 0af76eb81..b4ba8478d 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -333,44 +333,10 @@ double TMoverParameters::Current(double n, double U) double R; double MotorCurrent; - double Rz; - double Delta; - double Isf; double Mn; // przujmuje int, ale dla poprawnosci obliczeń double Bn; - int SP = 0; - double U1; // napiecie z korekta - MotorCurrent = 0; - // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) - { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; - } - if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) - { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; - } - - // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... - - // BrakeSubsystem = ss_LSt; - // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); - // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) - { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy - //- WriteLog("A"); - } - else - { - Hamulec->SetED(0); - //- WriteLog("B"); - } + UpdateSeriesMotorDynamicBrakeFlag(); ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); @@ -408,65 +374,7 @@ double TMoverParameters::Current(double n, double U) } else { // wlaczone... - SP = ScndCtrlActualPos; - - if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal - { - if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) - { - SP = RList[MainCtrlActualPos].ScndAct; - } - - Rz = Mn * WindingRes + R; - - if (DynamicBrakeFlag) // hamowanie - { - if (DynamicBrakeType > 1) - { - // if DynamicBrakeType<>dbrake_automatic then - // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} - /* begin - U:=0; - Isf:=Isat; - Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; - MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) - end*/ - if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) - { // z Megapacka - Rz = WindingRes + R; - MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} - } - } - else - MotorCurrent = 0; // odciecie pradu od silnika - } - else - { - U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; - // writepaslog("U1 ", FloatToStr(U1)); - // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); - // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); - Isf = Sign(U1) * motor_param(SP).Isat; - // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 - // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; - // writepaslog("Delta ", FloatToStr(Delta)); - // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); - // writepaslog("U ", FloatToStr(U)); - if (MainCircuitPowered()) - { - if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); - else - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); - } - else - MotorCurrent = 0; - } // else DBF - - } // 255 - else - MotorCurrent = 0; + MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); @@ -481,6 +389,125 @@ double TMoverParameters::Current(double n, double U) EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; + MotorFailuresCheck(n); + + return Im; +} + +// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it +void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() +{ + // i dzialanie hamulca ED w EP09 + if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) + { + if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) + DynamicBrakeFlag = true; + DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; + } + if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) + { + DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; + } + + // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... + + // BrakeSubsystem = ss_LSt; + // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); + // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna + if (DynamicBrakeFlag) + { + Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + //- WriteLog("A"); + } + else + { + Hamulec->SetED(0); + //- WriteLog("B"); + } +} + +// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of +// Mn motors in series +double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +{ + double MotorCurrent{0.0}; + double Rz; + int SP = ScndCtrlActualPos; + + if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal + { + if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) + { + SP = RList[MainCtrlActualPos].ScndAct; + } + + Rz = Mn * WindingRes + R; + + if (DynamicBrakeFlag) // hamowanie + { + // if DynamicBrakeType<>dbrake_automatic then + // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} + /* begin + U:=0; + Isf:=Isat; + Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; + MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) + end*/ + // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) + if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) + { // z Megapacka + Rz = WindingRes + R; + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + } + } + else + { + MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); + } // else DBF + + } // 255 + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in +// series, by the motor parameters of the shunt field SP +double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +{ + double MotorCurrent; + double Delta; + double Isf; + double U1; // napiecie z korekta + U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; + // writepaslog("U1 ", FloatToStr(U1)); + // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); + // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); + Isf = Sign(U1) * motor_param(SP).Isat; + // writepaslog("Isf ", FloatToStr(Isf)); + Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; + // writepaslog("Delta ", FloatToStr(Delta)); + // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); + // writepaslog("U ", FloatToStr(U)); + if (MainCircuitPowered()) + { + if (U > 0) + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); + else + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); + } + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the line breaker opened, and the motors damaged, by too high revolutions or current +void TMoverParameters::MotorFailuresCheck(double const n) +{ + double MotorCurrent; // awarie MotorCurrent = abs(Im); // zmienna pomocnicza @@ -495,8 +522,6 @@ double TMoverParameters::Current(double n, double U) EventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } - - return Im; } // ************************************************************************************************* @@ -932,55 +957,7 @@ void TMoverParameters::UpdatePantVolume(double dt) if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != dt_EZT) - { - // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) - { - // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); - } - } - else - { - // specialized variant for EMU -- pwr system disables converter and heating, - // and prevents their activation until pressure switch is set again - PantPressLockActive = true; - // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle - ConverterSwitch(false, range_t::unit); - } - // mark the pressure switch as spent - PantPressSwitchActive = false; - } - } - else - { - if (PantPress >= 4.6) - { - // NOTE: we require active low power source to prime the pressure switch - // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) - { - // prime the pressure switch - PantPressSwitchActive = true; - // turn off the subsystems lock - PantPressLockActive = false; - } - - if (PantPress >= 4.8) - { - // Winger - automatyczne wylaczanie malej sprezarki - // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; - } - } - } + PantPressureSwitchCheck(); } else { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze @@ -988,80 +965,78 @@ void TMoverParameters::UpdatePantVolume(double dt) } }; +// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; +// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 +void TMoverParameters::PantPressureSwitchCheck() +{ + if (PantPress < EnginePowerSource.CollectorParameters.MinPress) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (true == PantPressSwitchActive) + { + PantPressureSwitchTrip(); + } + } + else if (PantPress >= 4.6) + { + // NOTE: we require active low power source to prime the pressure switch + // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate + if (true == Power24vIsAvailable || true == Power110vIsAvailable) + { + // prime the pressure switch + PantPressSwitchActive = true; + // turn off the subsystems lock + PantPressLockActive = false; + } + + if (PantPress >= 4.8) + { + // Winger - automatyczne wylaczanie malej sprezarki + // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) + PantCompFlag = false; + } + } +} + +// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from +// elsewhere, or the converter of a unit locked; spent until primed again +void TMoverParameters::PantPressureSwitchTrip() +{ + // opuszczenie pantografów przy niskim ciśnieniu + if (TrainType != dt_EZT) + { + // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage + if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) + { + // TODO: check whether line breaker should be open EMU-wide + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + } + } + else + { + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + PantPressLockActive = true; + // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle + ConverterSwitch(false, range_t::unit); + } + // mark the pressure switch as spent + PantPressSwitchActive = false; +} + void TMoverParameters::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii - double sn1 = 0.0; - double sn2 = 0.0; - double sn3 = 0.0; - double sn4 = 0.0; - double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN - if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && NominalBatteryVoltage > 0) + using enum TEngineType; + if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) { // HACK: allow to draw power also from adjacent converter, applicable for EMUs // TODO: expand power cables system to include low voltage power transfers // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == TEngineType::DieselElectric && true == Mains) || (EngineType == TEngineType::DieselEngine && true == Mains)}; + auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - if (!converteractive) - sn1 = dt * 2.0; // szybki spadek do ok 90V - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 2.0); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.05; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... - sn4 = dt * 0.003; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.001; - else - sn5 = 0; - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - if (PantCompFlag) - sn1 = dt * 0.0046; - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 50); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.001; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu - sn4 = dt * 0.0030; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.0010; - else - sn5 = 0; - } - if (!Battery) - { - if (NominalBatteryVoltage / BatteryVoltage < 1.22) - sn1 = dt * 50; - else - sn1 = 0; - sn2 = dt * 0.000001; - sn3 = dt * 0.000001; - sn4 = dt * 0.000001; - sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - } - BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) + BatteryVoltage -= BatteryDrain(dt, converteractive); + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia if (BatteryVoltage > NominalBatteryVoltage) BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V @@ -1075,6 +1050,105 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) } }; +// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it +double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const +{ + if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) + { // 110V + return BatteryDrainCharged(dt, converteractive); + } + if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) + { // 90V + return BatteryDrainLow(dt, converteractive); + } + if (!Battery) + { + return BatteryDrainSwitchedOff(dt); + } + return 0.0; +} + +// the drain of a battery at its voltage, the converter charging it +double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (!converteractive) + sn1 = dt * 2.0; // szybki spadek do ok 90V + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 2.0); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.05; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... + sn4 = dt * 0.003; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.001; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery run down to 90 V, the converter charging it +double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (PantCompFlag) + sn1 = dt * 0.0046; + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 50); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.001; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu + sn4 = dt * 0.0030; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.0010; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery switched off, very slow +double TMoverParameters::BatteryDrainSwitchedOff(double dt) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (NominalBatteryVoltage / BatteryVoltage < 1.22) + sn1 = dt * 50; + else + sn1 = 0; + sn2 = dt * 0.000001; + sn3 = dt * 0.000001; + sn4 = dt * 0.000001; + sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach + return sn1 + sn2 + sn3 + sn4 + sn5; +} + /* Ukrotnienie EN57: 1 //układ szeregowy 2 //układ równoległy @@ -2543,10 +2617,41 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c return; } + auto const localvoltage{LocalPowerVoltage(Coupling)}; + + auto const abslocalvoltage{std::abs(localvoltage)}; + auto const localpowersource{(abslocalvoltage > 1.0)}; + + // przekazywanie napiec + PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); + + // przekazywanie pradow + PowerCouplersCurrent(Coupling, localpowersource); +} + +// the current the vehicle draws from the circuit of the power coupling given +double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) +{ + switch (Coupling) + { + case coupling::highvoltage: + return &TotalCurrent; + case coupling::power110v: + return &PowerCircuits[1].second; + case coupling::power24v: + return &PowerCircuits[0].second; + default: + return nullptr; + } +} + +// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too +double TMoverParameters::LocalPowerVoltage(coupling const Coupling) +{ auto localvoltage{0.0}; // local power sources - // TODO: make local voltage calculations a separate method, store results in PowerCircuit fields + // the results could be kept in the PowerCircuit fields switch (Coupling) { @@ -2615,10 +2720,17 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; + return localvoltage; +} - // przekazywanie napiec +// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source +void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) +{ + if (Couplers[end::front].power(Coupling) == nullptr) + { + // not a power coupling, there's no voltage to pass + return; + } for (auto side = 0; side < 2; ++side) { @@ -2662,14 +2774,8 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; - auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : - Coupling == coupling::power110v ? &oppositecoupler.power_110v : - Coupling == coupling::power24v ? &oppositecoupler.power_24v : - nullptr; + auto const *coupling = thiscoupler.power(Coupling); + auto *oppositecoupling = oppositecoupler.power(Coupling); // start with base voltage oppositecoupling->voltage = abslocalvoltage; @@ -2679,10 +2785,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c if (thiscoupler.Connected != nullptr) { auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - auto const *connectedcoupling = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : - Coupling == coupling::power110v ? &connectedcoupler.power_110v : - Coupling == coupling::power24v ? &connectedcoupler.power_24v : - nullptr; + auto const *connectedcoupling = connectedcoupler.power(Coupling); auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; @@ -2694,43 +2797,24 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled; } } +} - // przekazywanie pradow - auto couplervoltage{0}; - switch (Coupling) +// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own +void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) +{ + auto const *frontcoupling{Couplers[end::front].power(Coupling)}; + auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; + auto *totalcurrent{PowerCircuitCurrent(Coupling)}; + if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) { - case coupling::highvoltage: - { - couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); - break; + // not a power coupling, there's no current to share + return; } - case coupling::power110v: - { - couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); - break; - } - case coupling::power24v: - { - couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); - break; - } - default: - { - break; - } - } - - auto *totalcurrent = Coupling == coupling::highvoltage ? &TotalCurrent : - Coupling == coupling::power110v ? &PowerCircuits[1].second : - Coupling == coupling::power24v ? &PowerCircuits[0].second : - nullptr; + auto const couplervoltage{static_cast(frontcoupling->voltage + rearcoupling->voltage)}; for (auto &thiscoupler : Couplers) { - auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; + auto *coupling = thiscoupler.power(Coupling); coupling->current = 0.0; @@ -2740,10 +2824,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : - Coupling == coupling::power110v ? &connectedothercoupler.power_110v : - Coupling == coupling::power24v ? &connectedothercoupler.power_24v : - nullptr; + auto const *connectedothercoupling = connectedothercoupler.power(Coupling); auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; if (false == localpowersource) @@ -3177,114 +3258,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) bool OK = false; if (MainCtrlPos < MainCtrlPosNo) { - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_ET40) - { - break; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? - } - while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) - { - // all work is done in the loop header - } - OK = false; // shouldn't this be part of the loop above? - // if (TrainType=dt_ET40) then - // while Abs (Im)>IminHi do - // dec(MainCtrlPos); - // OK:=false ; - } - else - { // CtrlSpeed == 1 - ++MainCtrlPos; - OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) - { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == dt_ET42) - { - --MainCtrlPos; - OK = false; - } - } - // - // if (TrainType == "et40") - // if (Abs(Im) > IminHi) - // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu - // OK = false; - // } - //} - } - - if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of + OK = IncMainCtrlByEngine(CtrlSpeed); } else { // MainCtrlPos>=MainCtrlPosNo @@ -3328,6 +3302,130 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) return OK; } +// a notch up, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed > 1) + { + OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? + break; + } + ++MainCtrlPos; + OK = true; + if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = IncMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed > 1) + { + while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + ++MainCtrlPos; + } + CompressorAllow = MainCtrlPowerPos() > 0; + OK = true; + break; + } + + case TEngineType::WheelsDriven: + { + OK = AddPulseForce(CtrlSpeed); + break; + } + default: + break; + } // switch EngineType of + return OK; +} + +// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; +// returns whether it moved as asked +bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (DirActive == 0) + { + return false; + } + + if (CtrlSpeed > 1) + { + // szybkie przejœcie na bezoporow¹ + if (TrainType == dt_ET40) + { + return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? + } + while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) + { + // all work is done in the loop header + } + OK = false; // shouldn't this be part of the loop above? + // if (TrainType=dt_ET40) then + // while Abs (Im)>IminHi do + // dec(MainCtrlPos); + // OK:=false ; + } + else + { // CtrlSpeed == 1 + ++MainCtrlPos; + OK = true; + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) + { + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( SoundFlag, sound::relay ); + } + */ + if (TrainType == dt_ET42) + { + --MainCtrlPos; + OK = false; + } + } + // + // if (TrainType == "et40") + // if (Abs(Im) > IminHi) + // { + // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // OK = false; + // } + //} + } + + if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + { + MainCtrlPos = 20; + OK = false; + } + return OK; +} + // ***************************************************************************** // Q: 20160710 // zmniejszenie nastawnika @@ -3358,70 +3456,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) OK = true; } else - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if ((CtrlSpeed == 1 && EngineType != TEngineType::DieselElectric) || (CtrlSpeed == 1 && EngineType == TEngineType::DieselElectric)) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ - { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then - // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and - // (TrainType<>dt_EP05) then - // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) - OK = true; - } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ - { - OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] - DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) - ; // takie chamskie, potem poprawie} - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType + OK = DecMainCtrlByEngine(CtrlSpeed); } } else if (EngineType == TEngineType::WheelsDriven) @@ -3451,6 +3486,85 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) return OK; } +// a notch down, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else if (CtrlSpeed > 1) + OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = DecMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + } + else if (CtrlSpeed > 1) + { + while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) + DecMainCtrl(1); + OK = true; + } + break; + } + default: + break; + } // switch EngineType + return OK; +} + +// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors +bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ + { + MainCtrlPos--; + // if (MainCtrlPos=0) and (ScndCtrlPos=0) and + // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then + // StLinFlag:=false; + // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and + // (TrainType<>dt_EP05) then + // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) + OK = true; + } + else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ + { + OK = true; + if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] + DecMainCtrl(1); + while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) + ; // takie chamskie, potem poprawie} + } + return OK; +} + bool TMoverParameters::IsMainCtrlActualNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems @@ -5358,100 +5472,181 @@ void TMoverParameters::UpdatePipePressure(double dt) if (BrakeCtrlPosNo > 1) { - // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it - if (EngineType != TEngineType::ElectricInductionMotor) - { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) - { - lbpa = std::max(0.0, -eimic_real); - } - if (SpeedCtrlUnit.Parking) - { - lbpa = std::max(lbpa, StopBrakeDecc); - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - else - { - // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm - // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake - // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). - double lbpa; - if (LocHandleTimeTraxx) - { - lbpa = eim_localbrake; - } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. - { - lbpa = LocalBrakePosA; - } - else - { - lbpa = 0.0; - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; - - if (lock_old || lock_new) - { - temp = PipePress + 0.00001; - } - else - { - temp = ScndPipePress; - } - Handle->SetReductor(BrakeCtrlPos2); - - if (PulleeMode) - { - // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows - dpMainValve = 0; - } - else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) - { - - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) - { - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) - { - pos = Handle->GetPos(bh_NP); - if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); - if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); - } - dpMainValve = Handle->GetPF(pos, PipePress, temp, dt, EqvtPipePress); - } - else - { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); - } - } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) - { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); - } - - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 - { - if (Compressor > ScndPipePress) - { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); - } - else - Pipe2->Flow(dpMainValve); - } + UpdateLocalBrakeValve(dt); + UpdateMainValve(dt); } + UpdateEmergencyValve(dt); + + // 0.2*Spg + Pipe->Flow(-dpMainValve); + Pipe->Flow(-PipePress * 0.001 * dt); + // if Heating then + // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); + // if ConverterFlag then + // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); + dpMainValve = dpMainValve / (Dim.L * Spg * 20); + + CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza + + // if (Hamulec is typeid(TWest)) return 0; + + UpdateDistributorSettings(); + + if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) + { + UpdateEPBrake(); + } + 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(); + if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + temp = 0.0; // odetnij + else + temp = 1.0; // połącz + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; + + if (ASBType == 128) + Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + + dpPipe = 0; + + // yB: jednokrokowe liczenie tego wszystkiego + Pipe->Act(); + PipePress = Pipe->P(); + + dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; + + if (PipePress < -1.0) + { + PipePress = -1.0; + Pipe->CreatePress(-1.0); + Pipe->Act(); + } + + if (CompressedVolume < 0.0) + CompressedVolume = 0.0; +} + +// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking +void TMoverParameters::UpdateLocalBrakeValve(double dt) +{ + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it + if (EngineType != TEngineType::ElectricInductionMotor) + { + double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; + if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) + { + lbpa = std::max(0.0, -eimic_real); + } + if (SpeedCtrlUnit.Parking) + { + lbpa = std::max(lbpa, StopBrakeDecc); + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } + else + { + // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm + // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake + // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. + // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). + double lbpa; + if (LocHandleTimeTraxx) + { + lbpa = eim_localbrake; + } + else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + { + lbpa = LocalBrakePosA; + } + else + { + lbpa = 0.0; + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } +} + +// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air +void TMoverParameters::UpdateMainValve(double dt) +{ + auto const temp{MainValveSupply()}; + Handle->SetReductor(BrakeCtrlPos2); + + if (PulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + dpMainValve = 0; + } + else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + { + + if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) + { + dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); + } + else + { + dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); + } + } + else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) + { + dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); + } + + if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { + if (Compressor > ScndPipePress) + { + CompressedVolume = CompressedVolume + dpMainValve / 1500.0; + Pipe2->Flow(dpMainValve / 3.0); + } + else + Pipe2->Flow(dpMainValve); + } +} + +// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked +double TMoverParameters::MainValveSupply() +{ + LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); + bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz + bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions + && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; + + if (lock_old || lock_new) + { + return PipePress + 0.00001; + } + return ScndPipePress; +} + +// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets +double TMoverParameters::MainValveHandlePosition() const +{ + double pos = BrakeCtrlPosR; + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) + { + pos = Handle->GetPos(bh_NP); + if (SpeedCtrlUnit.BrakeInterventionBraking) + pos = Handle->GetPos(bh_FB); + if (SpeedCtrlUnit.BrakeInterventionUnbraking) + pos = Handle->GetPos(bh_RP); + } + return pos; +} + +void TMoverParameters::UpdateEmergencyValve(double dt) +{ // ulepszony hamulec bezp. EmergencyValveFlow = 0.0; @@ -5469,20 +5664,11 @@ void TMoverParameters::UpdatePipePressure(double dt) EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; } dpMainValve += EmergencyValveFlow; +} - // 0.2*Spg - Pipe->Flow(-dpMainValve); - Pipe->Flow(-PipePress * 0.001 * dt); - // if Heating then - // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); - // if ConverterFlag then - // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - dpMainValve = dpMainValve / (Dim.L * Spg * 20); - - CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza - - // if (Hamulec is typeid(TWest)) return 0; - +// what the distributor valve gets of the local brake and the load, by its kind +void TMoverParameters::UpdateDistributorSettings() +{ switch (BrakeValve) { @@ -5588,64 +5774,29 @@ void TMoverParameters::UpdatePipePressure(double dt) break; } } // switch +} - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); - else - EpForce = 0.0; - - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - - double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(EpForce); - TUHEX_Active = TUHEX_StageActual > 0; - // 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(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony - temp = 0.0; // odetnij +// the ep brake of the FVel6 and FVE408 handles, passed along the unit +void TMoverParameters::UpdateEPBrake() +{ + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - + // temp = (Handle as TFVel6).GetCP + EpForce = Handle->GetEP(); else - temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); - // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - PipeCouplersPending = true; + EpForce = 0.0; - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - dpPipe = 0; - - // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); - - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - - if (PipePress < -1.0) - { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); - } - - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; + double temp1 = EpForce; + if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + temp1 = 0; + if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + temp1 = 0; + Hamulec->SetEPS(temp1); + TUHEX_StageActual = static_cast(EpForce); + TUHEX_Active = TUHEX_StageActual > 0; + // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach + SendCtrlToNext("Brake", EpForce, CabActive); } // ************************************************************************************************* @@ -6388,7 +6539,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada @@ -6464,21 +6615,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (std::abs(CF) > thiscoupler.FmaxC) - { - // coupler is stretched with excessive force, may break - thiscoupler.stretch_duration += static_cast(dt); - // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks - // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) - { - damage_coupler(End); - } - } - else - { - thiscoupler.stretch_duration = 0.f; - } + CouplerStretchCheck(End, CF, dt); } if (newdistance < 0) { @@ -6517,6 +6654,27 @@ double TMoverParameters::CouplerForce(int const End, double dt) return CF; } +// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on +void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) +{ + auto &thiscoupler{Couplers[End]}; + if (std::abs(CF) > thiscoupler.FmaxC) + { + // coupler is stretched with excessive force, may break + thiscoupler.stretch_duration += static_cast(dt); + // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks + // (arbitrary) chance to break grows from 10-100% over 10 sec period + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) + { + damage_coupler(End); + } + } + else + { + thiscoupler.stretch_duration = 0.f; + } +} + bool TMoverParameters::coupler_physics_at(int const End) const { if (false == Global.coupler_physics) @@ -6695,14 +6853,91 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - double PosRatio; - double dmoment; - double dtrans; - double tmp; - + using enum TEngineType; Ft = 0; - dtrans = 0; - dmoment = 0; + double dtrans{0.0}; + double dmoment{0.0}; + auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; + + eAngle += enrot * dt; + if (eAngle > M_PI * 2.0) + eAngle = std::fmod(eAngle, M_PI * 2.0); + /* + while (eAngle > M_PI * 2.0) + // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? + eAngle -= M_PI * 2.0; + */ + // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) + // wentylatory rozruchowe + // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + UpdateVentilators(dt); + auto const PosRatio{UpdateEnginePower()}; + VoltageRelaysCheck(); + + if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + + if (DirActive != 0) + switch (EngineType) + { + case Dumb: + { + DumbTractionForce(PosRatio); + break; + } + case WheelsDriven: + { + WheelsDrivenTractionForce(dt); + break; + } + case ElectricSeriesMotor: + { + SeriesMotorTractionForce(dt); + break; + } + case DieselEngine: + { + DieselEngineTractionForce(dt, dmoment, dtrans); + break; + } + case DieselElectric: // youBy + { + DieselElectricTractionForce(revolutions); + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(dt); + } + break; + } + case ElectricInductionMotor: + { + InductionMotorTractionForce(dt); + break; + } + case None: + default: + { + break; + } + } // case EngineType + + if (EngineType == DieselElectric) + { + // rough approximation of extra effort to overcome friction etc + EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + } + + return Ft; +} + +// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. +// for a diesel engine, the ratio of the transmission and the engine's moment +double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +{ + double tmp{0.0}; // youBy switch (EngineType) { @@ -6710,19 +6945,7 @@ double TMoverParameters::TractionForce(double dt) { if (true == Mains && true == FuelPump.is_active) { - - if (EIMCtrlType > 0) // sterowanie cyfrowe - tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; - else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) - { - // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); - } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + tmp = DieselElectricTargetRevolutions(); } else { @@ -6758,17 +6981,32 @@ double TMoverParameters::TractionForce(double dt) } } - eAngle += enrot * dt; - if (eAngle > M_PI * 2.0) - eAngle = std::fmod(eAngle, M_PI * 2.0); - /* - while (eAngle > M_PI * 2.0) - // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; - */ - // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) - // wentylatory rozruchowe - // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + return tmp; +} + +// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke +double TMoverParameters::DieselElectricTargetRevolutions() +{ + double tmp; + + if (EIMCtrlType > 0) // sterowanie cyfrowe + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; + else + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + + if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) + { + // bump engine revolutions up if needed, when heating is on + tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); + } + // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + return tmp; +} + +// the starting resistors' blowers, and the diesels' radiator fans +void TMoverParameters::UpdateVentilators(double dt) +{ switch (EngineType) { @@ -6776,50 +7014,7 @@ double TMoverParameters::TractionForce(double dt) { if (MainCircuitPowered()) { - switch (RVentType) - { - - case 1: - { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case 2: - { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; - if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) - { - - RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) - { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (RVentForceOn) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - default: - { - break; - } - } // rventtype + UpdateResistorBlowers(dt); } // mains else { @@ -6868,7 +7063,61 @@ double TMoverParameters::TractionForce(double dt) break; } } +} +// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current +void TMoverParameters::UpdateResistorBlowers(double dt) +{ + switch (RVentType) + { + + case 1: + { // manual + if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case 2: + { // automatic + auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; + if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) + { + + RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) + { + RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (RVentForceOn) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + default: + { + break; + } + } // rventtype +} + +// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to +double TMoverParameters::UpdateEnginePower() +{ + double PosRatio{0.0}; switch (EngineType) { case TEngineType::Dumb: @@ -6899,6 +7148,12 @@ double TMoverParameters::TractionForce(double dt) } } + return PosRatio; +} + +// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric +void TMoverParameters::VoltageRelaysCheck() +{ switch (EngineType) { @@ -6950,832 +7205,924 @@ double TMoverParameters::TractionForce(double dt) break; } } +} - if (EngineType == TEngineType::DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) +void TMoverParameters::DumbTractionForce(double const PosRatio) +{ + if (Mains && CabActive != 0) { - update_dieselelectric_dynamic_brake(dt); + if (Vel > 0.1) + { + Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; + } + else + { + Ft = Ftmax * PosRatio; + } + Ft = Ft * DirAbsolute; // DirActive*CabActive; + } + else + { + Ft = 0; + } +} + +void TMoverParameters::WheelsDrivenTractionForce(double dt) +{ + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + PulseForceTimer = PulseForceTimer + dt; + if (PulseForceTimer > CtrlDelay) + { + PulseForce = 0; + if (PulseForceCount > 0) + PulseForceCount--; + } + EnginePower = Ft * (1.0 + Vel); +} + +void TMoverParameters::SeriesMotorTractionForce(double dt) +{ + // enrot:=Transmision.Ratio*nrot; + // yB: szereg dwoch sekcji w ET42 + if (TrainType == dt_ET42 && Imax == ImaxHi) + EngineVoltage = EngineVoltage / 2.0; + Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + + if (TrainType == dt_ET42) + { + if (Imax == ImaxHi) + EngineVoltage = EngineVoltage * 2; + if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp + FuseOff(); + } + if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + { + SeriesMotorDynamicBrake(dt); } - if (DirActive != 0) - switch (EngineType) + if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił + + if (abs(Im) > Imax) + Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN + else + Vhyp = 0; + if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony + FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow + + if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) + Itot = Im * 2; // 2x2 silniki w EP09 + else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + Itot = Im; + else + Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles; // sila trakcyjna +} + +// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) +void TMoverParameters::SeriesMotorDynamicBrake(double dt) +{ + if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne + { + if (Vel > 100) + TUHEX_StageActual = std::min(TUHEX_StageActual, 1); + switch (TUHEX_StageActual) { - case TEngineType::Dumb: - { - if (Mains && CabActive != 0) + case 1: + TUHEX_Sum = TUHEX_Sum1; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 2: + TUHEX_Sum = TUHEX_Sum2; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 3: + TUHEX_Sum = TUHEX_Sum3; + if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) + TUHEX_ResChange = true; + if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) { - if (Vel > 0.1) - { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; - } - else - { - Ft = Ftmax * PosRatio; - } - Ft = Ft * DirAbsolute; // DirActive*CabActive; - } - else - { - Ft = 0; + TUHEX_ResChange = false; + DynamicBrakeRes = DynamicBrakeRes2; } break; - } // Dumb - - case TEngineType::WheelsDriven: - { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; - PulseForceTimer = PulseForceTimer + dt; - if (PulseForceTimer > CtrlDelay) - { - PulseForce = 0; - if (PulseForceCount > 0) - PulseForceCount--; - } - EnginePower = Ft * (1.0 + Vel); - break; - } // WheelsDriven - - case TEngineType::ElectricSeriesMotor: - { - // enrot:=Transmision.Ratio*nrot; - // yB: szereg dwoch sekcji w ET42 - if (TrainType == dt_ET42 && Imax == ImaxHi) - EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - - if (TrainType == dt_ET42) - { - if (Imax == ImaxHi) - EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp - FuseOff(); - } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - { - if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne - { - if (Vel > 100) - TUHEX_StageActual = std::min(TUHEX_StageActual, 1); - switch (TUHEX_StageActual) - { - case 1: - TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 2: - TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 3: - TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) - TUHEX_ResChange = true; - if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) - { - TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; - } - break; - default: - DynamicBrakeRes = DynamicBrakeRes1; - TUHEX_Sum = 0; - break; - } - } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) - { - Vadd -= 500.0 * dt; - if (Vadd < TUHEX_MinIw) - { - Vadd = 0; - DynamicBrakeFlag = false; - } - } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) - { - Vadd += 70.0 * dt; - Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); - } - if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); - } - - if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku - Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił - - if (abs(Im) > Imax) - Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN - else - Vhyp = 0; - if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony - FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) - Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie - Itot = Im; - else - Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles; // sila trakcyjna - break; - } - - case TEngineType::DieselEngine: - { - Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) - Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; - Ft = Fw * NPoweredAxles; // sila trakcyjna - Ft = Ft * DirAbsolute; // DirActive*CabActive; - break; - } - - case TEngineType::DieselElectric: // youBy - { - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; - auto tempUmax = 0.0; - auto tempImax = 0.0; - auto tempPmax = 0.0; - // jazda manewrowa - if (EIMCtrlType > 0) // sterowanie cyfrowe - { - auto eimic_positive = std::max(0.0, eimic_real); - auto const rpmratio{EngineRPMRatio()}; - tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; - tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); - tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - tmp = tempPmax; - if (true == StLinFlag) - { - - if (tmpV < Vhyp * tempPmax / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = - (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * eimic_positive; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tempPmax / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tempPmax / DElist[MainCtrlPosNo].GenPower; - } - else if (true == ShuntMode) - { - if (true == StLinFlag) - { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); - Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); - } - else - { - EngineVoltage = 0; - Ft = 0; - } - PosRatio = 1; - } - else // jazda ciapongowa - { - auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) - { - power -= HeatingPower; - } - if (power < 0.0) - { - power = 0.0; - } - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; - - tmp = std::min(power, currentgenpower); - - PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; - // stosunek mocy teraz do mocy max - // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) - { - - if (tmpV < Vhyp * power / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * PosRatio; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tmp / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - - if (FuseFlag) - Ft = 0; - else - Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc - Fw = Ft / NPoweredAxles; // sila na obwodzie kola - Mw = Fw * WheelDiameter / 2.0; // moment na osi kola - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - Im = dieselelectric_motor_current(Mm); - - if (ShuntMode) - { - EnginePower = EngineVoltage * Im / 1000.0; - if (EnginePower > tmp) - { - EnginePower = tmp; - EngineVoltage = EnginePower * 1000.0 / Im; - } - if (EnginePower < tmp) - { - Ft *= EnginePower / tmp; - } - } - else - { - if (abs(Im) > tempImax) - { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; - Im = tempImax; - } - - if (Im > 0) - { - // jak pod obciazeniem - if (true == Flat) - { - // ograniczenie napiecia w pradnicy - plaszczak u gory - EngineVoltage = 1000.0 * tmp / std::abs(Im); - } - else - { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; - // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa - EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); - EngineVoltage /= tempMCPN - 1; - EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); - } - } - - if (EngineVoltage > tempUmax || Im == 0) - { - // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); - } - - EnginePower = EngineVoltage * Im / 1000.0; - /* - // power curve drop - // NOTE: disabled for the time being due to side-effects - if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, - std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); - } - */ - } - - if (Imax > 1 && Im > Imax) - FuseOff(); - if (FuseFlag) - EngineVoltage = 0; - - // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (false == StLinFlag || ShuntMode) - { - ScndCtrlPos = 0; - } - else - { - if (AutoRelayFlag) - { - - auto const shuntfieldstate{ScndCtrlPos}; - - switch (RelayType) - { - - case 0: - { - - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) - { - --ScndCtrlPos; - } - break; - } - case 1: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - break; - } - case 2: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - break; - } - case 41: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - enrot = enrot * 0.73; - } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - break; - } - case 45: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) - { - - if (Im < MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - } - // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) - { - - if (ScndCtrlPos == 1) - { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - else - { - if (Vel < MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - } - } - // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - /* - // crude woodward approximation; difference between rpm for consecutive positions is ~5% - // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction - auto const woodward { std::clamp( - ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, - 0.0, 1.0 ) }; - */ - break; - } - case 46: - { - // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) - { - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } - } - // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) - { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - } - } - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - break; - } - default: - { - break; - } - } // switch RelayType - - if (ScndCtrlPos != shuntfieldstate) - { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); - } - } - } - if (DEDynamicBrake.level > 0.0) - { - // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(dt); - } - break; - } // DieselElectric - - case TEngineType::ElectricInductionMotor: - { - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double ActiveInverters = 0.0; - for (auto const &inv : Inverters) - { - if (inv.IsActive) - ActiveInverters += 1.0; - } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) - { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); - } - // tempomat - if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) - { - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) - { - case 0: - NewSpeed = 0; - SpeedCtrlValue = 0; - SpeedCtrlTimer = 10; - break; - case 1: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; - } - else - SpeedCtrlTimer += dt; - break; - case 2: - SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; - break; - case 3: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; - } - else - SpeedCtrlTimer += dt; - break; - case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; - SpeedCtrlTimer = 10; - break; - default: - break; - } - } - else if (ScndCtrlPosNo > 1) - { - if (ScndCtrlPos != NewSpeed) - { - - SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; - } - else - { - SpeedCtrlTimer += dt; - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); - if (NewSCAP != SpeedCtrlValue) - { - SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); - } - } - } - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - } - double edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; - // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza - // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) - { - DynamicBrakeFlag = true; - } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; - edBCP = Hamulec->GetEDBCP() * eimc[eimc_p_abed]; // stala napedu - if (DynamicBrakeFlag) - { - // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) - { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); - PosRatio = std::clamp(PosRatio, 0.0, 1.0); - } - else - { - PosRatio = 0; - } - PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED - if (PosRatio < 19.5 / 20.0) - PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia - // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED - { - PosRatio = 0; - eimv[eimv_Fzad] = 0; - } - else - { - // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); - if (SplitEDPneumaticBrake) - { - // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl - // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) - double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); - } - else - { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); - } - } - tmp = 5; - } - else - { - PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); - /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) - PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); - else - PosRatio = - std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ - // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); - // (Hamulec as TLSt).SetLBP(LocBrakePress); - tmp = 4; // szybkie malenie, powolne wzrastanie - } - // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions - // TODO: gather these in single place so they can be resolved together - if (SlippingWheels) - { - PosRatio = 0; - tmp = 10; - SandboxAuto(true, range_t::unit); - } // przeciwposlizg - else - { - // switch sandbox off - SandboxAuto(false, range_t::unit); - } - if (ActiveInverters == 0.0) - { - PosRatio = 0; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio= 0) - Vadd *= 1.0 - 2.0 * dt; - else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) - Vadd *= 1.0 - dt; - else - Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - auto const tmpV{std::abs(eimv[eimv_fp])}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; - auto const list = useFFEDList ? FFEDlist : FFlist; - - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) - { - - int i = 0; - while (i < listSize - 1 && list[i + 1].v < tmpV) - { - ++i; - } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; - } - else - { - InverterFrequency = 0.0; - } - - Mm = eimv[eimv_M] * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; - } // mains - else - { - for (auto &inv : Inverters) - { - inv.Freal = 0.0; - inv.IsActive = false; - } - Im = 0.0; - Mm = 0.0; - Mw = 0.0; - Fw = 0.0; - Ft = 0.0; - Itot = 0.0; - eimv_pr = 0.0; - EnginePower = 0.0; - { - for (auto &eimvvalue : eimv) - eimvvalue = 0.0; - } - Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); - } - break; - } // ElectricInductionMotor - - case TEngineType::None: default: - { + DynamicBrakeRes = DynamicBrakeRes1; + TUHEX_Sum = 0; break; } - } // case EngineType - - if (EngineType == TEngineType::DieselElectric) + } + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + Vadd -= 500.0 * dt; + if (Vadd < TUHEX_MinIw) + { + Vadd = 0; + DynamicBrakeFlag = false; + } + } + else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + { + Vadd += 70.0 * dt; + Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); + } + if (Vadd > 0) + Mm = MomentumF(Im, Vadd, 0); +} + +void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +{ + Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation + if (hydro_R && hydro_R_Placement == 0) + Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; + Ft = Fw * NPoweredAxles; // sila trakcyjna + Ft = Ft * DirAbsolute; // DirActive*CabActive; +} + +// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() +void TMoverParameters::DieselElectricTractionForce(double tmp) +{ + double PosRatio; + // tmpV:=V*CabActive*DirActive; + auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto tempUmax = 0.0; + auto tempImax = 0.0; + // jazda manewrowa + if (EIMCtrlType > 0) // sterowanie cyfrowe + { + tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + else if (true == ShuntMode) + { + DieselElectricShuntForce(tmpV, tmp); + PosRatio = 1; + } + else // jazda ciapongowa + { + auto power = Power; + tempImax = DElist[MainCtrlPos].Imax; + tempUmax = DElist[MainCtrlPos].Umax; + if (true == Heating) + { + power -= HeatingPower; + } + power = std::max(power, 0.0); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; + + tmp = std::min(power, currentgenpower); + + PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; + // stosunek mocy teraz do mocy max + // NOTE: Mains in this context is working diesel engine + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; } - return Ft; + if (FuseFlag) + Ft = 0; + else + Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc + Fw = Ft / NPoweredAxles; // sila na obwodzie kola + Mw = Fw * WheelDiameter / 2.0; // moment na osi kola + Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego + + Im = dieselelectric_motor_current(Mm); + + if (ShuntMode) + { + DieselElectricShuntPower(tmp); + } + else + { + DieselElectricGenerator(tmp, tempUmax, tempImax); + } + + if (Imax > 1 && Im > Imax) + FuseOff(); + if (FuseFlag) + EngineVoltage = 0; + + // przekazniki bocznikowania, kazdy inny dla kazdej pozycji + if (false == StLinFlag || ShuntMode) + { + ScndCtrlPos = 0; + } + else if (AutoRelayFlag) + { + ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); + } +} + +// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; +// tmp, the power the generator gives +void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) +{ + if (true == StLinFlag) + { + EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); + Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); + } + else + { + EngineVoltage = 0; + Ft = 0; + } +} + +// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's +// voltage and current limits too. returns the power the generator gives +double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +{ + auto eimic_positive = std::max(0.0, eimic_real); + auto const rpmratio{EngineRPMRatio()}; + tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; + tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); + auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + return tempPmax; +} + +// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed +// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it +double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +{ + if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) + { + // czy na czesci prostej, czy na hiperboli + return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada + } + // na hiperboli + // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka + return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy +} + +// in the shunting mode, the generator's power limited to tmp, the power the engine gives +void TMoverParameters::DieselElectricShuntPower(double const tmp) +{ + EnginePower = EngineVoltage * Im / 1000.0; + if (EnginePower > tmp) + { + EnginePower = tmp; + EngineVoltage = EnginePower * 1000.0 / Im; + } + if (EnginePower < tmp) + { + Ft *= EnginePower / tmp; + } +} + +// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp +void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +{ + if (abs(Im) > tempImax) + { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy + Ft = Ft / Im * tempImax; + Im = tempImax; + } + + if (Im > 0) + { + // jak pod obciazeniem + if (true == Flat) + { + // ograniczenie napiecia w pradnicy - plaszczak u gory + EngineVoltage = 1000.0 * tmp / std::abs(Im); + } + else + { + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa + EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); + EngineVoltage /= tempMCPN - 1; + EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); + } + } + + if (EngineVoltage > tempUmax || Im == 0) + { + // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) + EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); + } + + EnginePower = EngineVoltage * Im / 1000.0; + /* + // power curve drop + // NOTE: disabled for the time being due to side-effects + if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { + Ft = std::lerp( + Ft, EnginePower / tmp, + std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); + } + */ +} + +// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the +// power (tmp, the power the engine gives) +void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +{ + auto const shuntfieldstate{ScndCtrlPos}; + + switch (RelayType) + { + + case 0: + { + + if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) + { + --ScndCtrlPos; + } + break; + } + case 1: + { + + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + break; + } + case 2: + { + + ShuntFieldRelaysType2(tmp); + break; + } + case 41: + { + ShuntFieldRelaysType41(tmpV); + break; + } + case 45: + { + ShuntFieldRelaysType45(); + break; + } + case 46: + { + ShuntFieldRelaysType46(); + break; + } + default: + { + break; + } + } // switch RelayType + + if (ScndCtrlPos != shuntfieldstate) + { + SetFlag(SoundFlag, sound::relay | sound::shuntfield); + } +} + +// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current +void TMoverParameters::ShuntFieldRelaysType2(double const tmp) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } +} + +// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current +void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + enrot = enrot * 0.73; + } + if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } +} + +// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th +void TMoverParameters::ShuntFieldRelaysType45() +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) + { + + if (Im < MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + } + // check for cases where the speed drops below threshold for level 2 or 3 + if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + // malenie + if (ScndCtrlPos > 0 && MainCtrlPos < 11) + { + + if (ScndCtrlPos == 1) + { + if (Im > MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + else + { + if (Vel < MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } + } + } + // 3rd level drops with master controller at position lower than 10... + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + // ...and below position 7 field shunt drops altogether + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } + /* + // crude woodward approximation; difference between rpm for consecutive positions is ~5% + // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction + auto const woodward { std::clamp( + ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, + 0.0, 1.0 ) }; + */ +} + +// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two +// under the 11th, none under the 8th +void TMoverParameters::ShuntFieldRelaysType46() +{ + // wzrastanie + if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) + { + ShuntFieldRelaysType46Up(); + } + // malenie + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) + { + ShuntFieldRelaysType46Down(); + } + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } +} + +// a relay of type 46 down: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Down() +{ + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + } +} + +// a relay of type 46 up: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Up() +{ + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Iup > Im) + { + ++ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + } +} + +void TMoverParameters::InductionMotorTractionForce(double dt) +{ + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) + { + double PosRatio; + double tmp; + double ActiveInverters = 0.0; + for (auto const &inv : Inverters) + { + if (inv.IsActive) + ActiveInverters += 1.0; + } + InvertersRatio = ActiveInverters / (double)InvertersNo; + if (EIM_Pmax_Table.size() > 1) + { + eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); + } + InductionMotorSpeedControl(dt); + InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); + // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions + // TODO: gather these in single place so they can be resolved together + if (SlippingWheels) + { + PosRatio = 0; + tmp = 10; + SandboxAuto(true, range_t::unit); + } // przeciwposlizg + else + { + // switch sandbox off + SandboxAuto(false, range_t::unit); + } + if (ActiveInverters == 0.0) + { + PosRatio = 0; + eimv_pr = 0; + } + + eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) + { + SpeedControlByPosition(dt); + } +} + +// the speed control set by the position of the second controller, after it's been held for its delay +void TMoverParameters::SpeedControlByPosition(double dt) +{ + if (ScndCtrlPos != NewSpeed) + { + + SpeedCtrlTimer = 0; + NewSpeed = ScndCtrlPos; + } + else + { + SpeedCtrlTimer += dt; + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); + if (NewSCAP != SpeedCtrlValue) + { + SpeedCtrlValue = NewSCAP; + // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); + } + } + } + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; +} + +// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, +// or off and at the top +void TMoverParameters::SpeedControlByTime(double dt) +{ + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; + switch (ScndCtrlPos) + { + case 0: + NewSpeed = 0; + SpeedCtrlValue = 0; + SpeedCtrlTimer = 10; + break; + case 1: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed -= 10; + if (NewSpeed < 0) + NewSpeed = 0; + } + else + SpeedCtrlTimer += dt; + break; + case 2: + SpeedCtrlTimer = 10; + SpeedCtrlValue = NewSpeed; + break; + case 3: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed += 10; + if (NewSpeed > Vmax) + NewSpeed = Vmax; + } + else + SpeedCtrlTimer += dt; + break; + case 4: + NewSpeed = Vmax; + SpeedCtrlValue = Vmax; + SpeedCtrlTimer = 10; + break; + default: + break; + } +} + +// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the +// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) +void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +{ + InductionMotorDynamicBrakeFlag(); + auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu + if (DynamicBrakeFlag) + { + PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); + tmp = 5; + } + else + { + PosRatio = std::max(eimic_real, 0.); + eimv[eimv_Fzad] = PosRatio; + if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) + PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); + /* if (ScndCtrlActualPos > 0) //speed control + if (Vmax < 250) + PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); + else + PosRatio = + std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ + // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio + Hamulec->SetED(0); + // (Hamulec as TLSt).SetLBP(LocBrakePress); + tmp = 4; // szybkie malenie, powolne wzrastanie + } +} + +// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local +// brake or its own controller; off without them +void TMoverParameters::InductionMotorDynamicBrakeFlag() +{ + double const edBCP = Hamulec->GetEDBCP(); + auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; + // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza + // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem + auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; + if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || + (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) + { + DynamicBrakeFlag = true; + } + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + DynamicBrakeFlag = true; +} + +// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none +// when the air brake cuts the electrodynamic one off, or an inverter is out +double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +{ + double PosRatio; + // ustalanie współczynnika blendingu do luzowania hamulca PN + if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + { + PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = std::clamp(PosRatio, 0.0, 1.0); + } + else + { + PosRatio = 0; + } + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED + if (PosRatio < 19.5 / 20.0) + PosRatio *= 0.9; + Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + // ustalanie siły hamowania ED + if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED + { + PosRatio = 0; + eimv[eimv_Fzad] = 0; + } + else + { + // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); + if (SplitEDPneumaticBrake) + { + // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl + // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) + double const edLeverDemand = DynamicBrakeRatio(); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + } + else + { + PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + } + } + return PosRatio; +} + +// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force +void TMoverParameters::InductionMotorDrive(double dt) +{ + double tmp; + if (DynamicBrakeFlag) + tmp = eimc[eimc_f_Uzh]; + else + tmp = eimc[eimc_f_Uzmax]; + + auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + + eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); + eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; + if (eimv_pr < 0) + { + eimv[eimv_Pmax] = eimc[eimc_p_Ph]; + } + else + { + eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + } + eimv[eimv_FMAXMAX] = 0.001 * + square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * + (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + InductionMotorForceLimits(); + for (auto &inv : Inverters) + { + inv.Request = inv.IsActive ? eimv_pr : 0.0; + inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); + inv.IsActive = inv.Activate && !inv.Error; + } + eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; + eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; + eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV + // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); + // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); + if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) + eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; + else + eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); + eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; + eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; + eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; + eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; + eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; + eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; + eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; + eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; + + Im = eimv[eimv_If]; + if (eimv[eimv_Ipoj] >= 0) + Vadd *= 1.0 - 2.0 * dt; + else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) + Vadd *= 1.0 - dt; + else + Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); + Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + + EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; + // power inverters + UpdateInverterFrequency(); + + Mm = eimv[eimv_M] * DirAbsolute; + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles * InvertersRatio; + eimv[eimv_Fr] = DirAbsolute * Ft / 1000; +} + +// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the +// electrodynamic brake, driving within the power and the starting force +void TMoverParameters::InductionMotorForceLimits() +{ + if (eimv_pr < 0) + { + eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); + eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); + double pr = eimv_pr; + if (EIMCLogForce) + pr = -log(1 - 4 * pr) / log(5); + eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); + if (InvertersRatio < 1.0) + eimv[eimv_Fful] = 0; + //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) + } + else + { + eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); + // if(not Flat)then + eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; + // else + // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); + double pr = eimv_pr; + if (EIMCLogForce) + pr = log(1 + 4 * pr) / log(5); + eimv[eimv_Fr] = eimv[eimv_Fful] * pr; + } +} + +// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake +void TMoverParameters::UpdateInverterFrequency() +{ + auto const tmpV{std::abs(eimv[eimv_fp])}; + auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; + auto const list = useFFEDList ? FFEDlist : FFlist; + + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + { + + int i = 0; + while (i < listSize - 1 && list[i + 1].v < tmpV) + { + ++i; + } + InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + } + else + { + InverterFrequency = 0.0; + } +} + +// the induction motor drive without power, or blocked by the security system +void TMoverParameters::InductionMotorOff() +{ + for (auto &inv : Inverters) + { + inv.Freal = 0.0; + inv.IsActive = false; + } + Im = 0.0; + Mm = 0.0; + Mw = 0.0; + Fw = 0.0; + Ft = 0.0; + Itot = 0.0; + eimv_pr = 0.0; + EnginePower = 0.0; + { + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; + } + Hamulec->SetED(0.0); + InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); } // the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor @@ -8170,7 +8517,6 @@ bool TMoverParameters::AutoRelayCheck(void) if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { StLinFlag = false; - OK = false; if (false == DynamicBrakeFlag) { Im = 0; @@ -8194,253 +8540,16 @@ bool TMoverParameters::AutoRelayCheck(void) { if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) { // zmieniaj scndctrlactualpos - // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) - { - if (LastRelayTime > CtrlDelay && ARFASI2) - { - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else if (ScndCtrlActualPos > ScndCtrlPos) - { - if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayShuntStep(ARFASI2); } else { // zmieniaj mainctrlactualpos - // running backwards, the motors don't get joined in more branches than allowed (the series connection - // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it - // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; - // main bez samoczynnego rozruchu - if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table - && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == dt_ET22 && DelayCtrlFlag))) - { - - // prevent switch to parallel mode if motor overload relay is set to high threshold mode - if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) - { - return false; - } - - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) - { - // HACK: ensure we play only single sound of basic relays for entire trasition; return false - // for all but last step despite configuration change, to prevent playback of the basic relay sound - // TBD, TODO: move the basic sound event here and enable it with call parameter - OK = true; - } - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel | sound::loud); - OK = true; - } - } - else if (LastRelayTime > CtrlDelay && ARFASI) - { - // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + - // FloatToStr(CtrlDelay)); - if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) - { - // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie - { - ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia - OK = true; - } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie - { - - DelayCtrlFlag = false; - OK = true; - } - /* - else - ; - */ - } - else // nie ET22 z wałem grupowym - { - ++MainCtrlActualPos; - OK = true; - } - //--------- - // hunter-111211: poprawki - if (MainCtrlActualPos > 0) - { - if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) - { - // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); - } - else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) - { - // wejscie na drugi uklad - SetFlag(SoundFlag, sound::parallel); - } - } - } - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - --MainCtrlActualPos; - OK = true; - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel); - } - } - else if (LastRelayTime > CtrlDownDelay) - { - if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem - { - --MainCtrlActualPos; - OK = true; - } - // hunter-111211: poprawki - if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } - } - } - else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) - { - if (LastRelayTime > CtrlDownDelay) - { - --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayMainStep(ARFASI); } } else // not StLinFlag { - OK = false; - // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) - { - - DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) - { - StLinFlag = true; - MainCtrlActualPos = 1; - DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); - OK = true; - } - } - else - { - DelayCtrlFlag = false; - } - - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) - { - - if (CoupledCtrl) - { - - if (TrainType == dt_EZT) - { - // EN57 wal jednokierunkowy calosciowy - if (MainCtrlActualPos == 1) - { - - MainCtrlActualPos = 0; - OK = true; - } - else - { - - if (LastRelayTime > CtrlDownDelay) - { - - if (MainCtrlActualPos < RlistSize) - { - // dojdz do konca - ++MainCtrlActualPos; - } - else if (ScndCtrlActualPos < ScndCtrlPosNo) - { - // potem boki - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - // i sie przewroc na koniec - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - } - OK = true; - } - } - } - else - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (ScndCtrlActualPos > 0) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - --MainCtrlActualPos; - } - OK = true; - } - } - } - else if (HasCamshaft) - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (MainCtrlActualPos > 0) - { - --MainCtrlActualPos; - } - ScndCtrlActualPos = 0; - OK = true; - } - } - else - { - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - OK = true; - } - } + OK = AutoRelayLineContactorsStep(motorconnectorsoff); } if (OK) LastRelayTime = 0; @@ -8449,6 +8558,304 @@ bool TMoverParameters::AutoRelayCheck(void) } } +// a step of the shunt field on a position without resistors, up or down to the second controller +bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) +{ + bool OK = false; + // scnd bez samoczynnego rozruchu + if (ScndCtrlActualPos < ScndCtrlPos) + { + if (LastRelayTime > CtrlDelay && ARFASI2) + { + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else if (ScndCtrlActualPos > ScndCtrlPos) + { + if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors +bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) +{ + bool OK = false; + // running backwards, the motors don't get joined in more branches than allowed (the series connection + // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it + // was, the line contactors closed, whatever the driver did with the master controller) + auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + // main bez samoczynnego rozruchu + if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table + && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || + (TrainType == dt_ET22 && DelayCtrlFlag))) + { + OK = AutoRelayMainUp(ARFASI); + } + else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) + { + OK = AutoRelayMainDown(); + } + else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) + { + if (LastRelayTime > CtrlDownDelay) + { + --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main relays up to the controller's position, at once to the parallel position without resistors +// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high +bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) +{ + bool OK = false; + // prevent switch to parallel mode if motor overload relay is set to high threshold mode + if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) + { + return false; + } + + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + ++MainCtrlActualPos; + if (MainCtrlPos - MainCtrlActualPos == 1) + { + // HACK: ensure we play only single sound of basic relays for entire trasition; return false + // for all but last step despite configuration change, to prevent playback of the basic relay sound + // TBD, TODO: move the basic sound event here and enable it with call parameter + OK = true; + } + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel | sound::loud); + OK = true; + } + } + else if (LastRelayTime > CtrlDelay && ARFASI) + { + OK = AutoRelayMainNotchUp(); + } + return OK; +} + +// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the +// parallel positions; returns whether they moved +bool TMoverParameters::AutoRelayMainNotchUp() +{ + bool OK = false; + // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + + // FloatToStr(CtrlDelay)); + if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + { + // et22 z walem grupowym + if (!DelayCtrlFlag) // najpierw przejscie + { + ++MainCtrlActualPos; + DelayCtrlFlag = true; // tryb przejscia + OK = true; + } + else if (LastRelayTime > 4 * CtrlDelay) // przejscie + { + + DelayCtrlFlag = false; + OK = true; + } + /* + else + ; + */ + } + else // nie ET22 z wałem grupowym + { + ++MainCtrlActualPos; + OK = true; + } + //--------- + // hunter-111211: poprawki + if (MainCtrlActualPos > 0) + { + if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) + { + // wejscie na bezoporowa + SetFlag(SoundFlag, sound::parallel | sound::loud); + } + else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) + { + // wejscie na drugi uklad + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// a step of the main relays down to the controller's position; returns whether they moved +bool TMoverParameters::AutoRelayMainDown() +{ + bool OK = false; + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + --MainCtrlActualPos; + OK = true; + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel); + } + } + else if (LastRelayTime > CtrlDownDelay) + { + if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem + { + --MainCtrlActualPos; + OK = true; + } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// the line contactors closed at the first position, or, open, the camshaft run back to zero +bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +{ + bool OK = false; + // ybARC - zalaczenie stycznikow liniowych + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + { + + DelayCtrlFlag = true; + if (LastRelayTime >= InitialCtrlDelay) + { + StLinFlag = true; + MainCtrlActualPos = 1; + DelayCtrlFlag = false; + SetFlag(SoundFlag, sound::relay | sound::loud); + OK = true; + } + } + else + { + DelayCtrlFlag = false; + } + + if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + { + OK |= CamshaftRunDown(); + } + return OK; +} + +// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; +// returns whether it moved +bool TMoverParameters::CamshaftRunDown() +{ + bool OK = false; + + if (CoupledCtrl) + { + + if (TrainType == dt_EZT) + { + OK = CamshaftRunDownEMU(); + } + else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + { + if (ScndCtrlActualPos > 0) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + --MainCtrlActualPos; + } + OK = true; + } + } + else if (HasCamshaft) + { + // wal kulakowy dwukierunkowy + if (LastRelayTime > CtrlDownDelay) + { + if (MainCtrlActualPos > 0) + { + --MainCtrlActualPos; + } + ScndCtrlActualPos = 0; + OK = true; + } + } + else + { + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + OK = true; + } + return OK; +} + +// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved +bool TMoverParameters::CamshaftRunDownEMU() +{ + bool OK = false; + // EN57 wal jednokierunkowy calosciowy + if (MainCtrlActualPos == 1) + { + + MainCtrlActualPos = 0; + OK = true; + } + else + { + + if (LastRelayTime > CtrlDownDelay) + { + + if (MainCtrlActualPos < RlistSize) + { + // dojdz do konca + ++MainCtrlActualPos; + } + else if (ScndCtrlActualPos < ScndCtrlPosNo) + { + // potem boki + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + // i sie przewroc na koniec + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + } + OK = true; + } + } + return OK; +} + bool TMoverParameters::MotorConnectorsCheck() { @@ -8709,160 +9116,205 @@ void TMoverParameters::CheckEIMIC(double dt) switch (EIMCtrlType) { case 0: - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) - { - if (eimic > 0.001) - eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) - eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); - } - if (eimic > 0.001 && SpeedCtrlUnit.IsActive) - eimic = std::max(eimic, SpeedCtrlUnit.MinPower); + EIMICFromController(brakeDemand, offset, multiplier); break; case 1: - switch (MainCtrlPos) + EIMICFromSteps(dt); + break; + case 2: + EIMICFromFourPositions(dt); + break; + case 3: + EIMICFromUniversalController(dt, brakeDemand); + break; + } + if (LocHandleTimeTraxx) + { + EIMICTraxxLocalBrake(dt); + } + + EIMICLimit(); +} + +// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked +void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +{ + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; + if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) + { + if (eimic > 0.001) + eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); + if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) + eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); + } + if (eimic > 0.001 && SpeedCtrlUnit.IsActive) + eimic = std::max(eimic, SpeedCtrlUnit.MinPower); +} + +// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace +void TMoverParameters::EIMICFromSteps(double dt) +{ + switch (MainCtrlPos) + { + case 0: // B+ + eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + break; + case 1: // B + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + break; + case 2: // B- + case 3: // 0 + case 4: // T- + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 5: // T + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 6: // T+ + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 + break; + case 7: // TMax + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + break; + default: + break; + } + if (MainCtrlPos >= 3 && eimic < 0) + eimic = 0; + if (MainCtrlPos <= 3 && eimic > 0) + eimic = 0; +} + +// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the +// emergency brake position below them, where the controller has one, brakes in full at once +void TMoverParameters::EIMICFromFourPositions(double dt) +{ + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { - case 0: // B+ - eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + case 0: + case 1: + eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + if (eimic > 0) + eimic = 0; break; - case 1: // B - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + case 2: + eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; - case 2: // B- - case 3: // 0 - case 4: // T- - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + case 3: + eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; - case 5: // T - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 6: // T+ - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 - break; - case 7: // TMax - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + case 4: + eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + if (eimic < 0) + eimic = 0; break; default: break; } - if (MainCtrlPos >= 3 && eimic < 0) - eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) - eimic = 0; - break; - case 2: - if (IsMainCtrlEmergencyPos()) - { - // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() - eimic = -1.0; - } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) - { - case 0: - case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 - if (eimic > 0) - eimic = 0; - break; - case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 - break; - case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 - break; - case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 - if (eimic < 0) - eimic = 0; - break; - default: - break; - } - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - break; - case 3: - if (UniCtrlIntegratedBrakePNCtrl) - { - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only - { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) - BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) - BrakeLevelSet(UniCtrlList[0].mode); // top clamping - if (IsCabMaster()) - { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) - DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) - IncMainCtrl(1); // find nearest position - } - } - else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); - } - - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - 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; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake - eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) - { - // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, - // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; - } } - if (LocHandleTimeTraxx) + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else { - if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie - { - eim_localbrake -= dt * 0.17; - } + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } +} - if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie - { - eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); - } - else // pozycja 1, utrzymanie cisnienia - { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) - eim_localbrake = 0; - } - eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); - if (eim_localbrake > 0.04 && eimic > 0) - eimic = 0; +// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not +void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) +{ + if (UniCtrlIntegratedBrakePNCtrl) + { + UniversalControllerTrainBrake(); } + if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + 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; + else + { + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } + if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + eimic = 0; // shut off retarder + if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) + { + // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, + // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; + } +} + +// the train brake built into the universal controller: the handle set to the controller's position, or the +// controller, at a brake handle moved alone, to the nearest position of the handle's +void TMoverParameters::UniversalControllerTrainBrake() +{ + if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + { + if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) + BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping + if (BrakeCtrlPos > UniCtrlList[0].mode) + BrakeLevelSet(UniCtrlList[0].mode); // top clamping + if (IsCabMaster()) + { + while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) + DecMainCtrl(1); // find nearest position + while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) + IncMainCtrl(1); // find nearest position + } + } + else // controller was moved + BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); +} + +// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off +void TMoverParameters::EIMICTraxxLocalBrake(double dt) +{ + if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie + { + eim_localbrake -= dt * 0.17; + } + + if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie + { + eim_localbrake += dt * 0.17; + eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); + } + else // pozycja 1, utrzymanie cisnienia + { + if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) + eim_localbrake = 0; + } + eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); + if (eim_localbrake > 0.04 && eimic > 0) + eimic = 0; +} + +// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits +void TMoverParameters::EIMICLimit() +{ auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; double eimic_max = 0.0; @@ -8931,40 +9383,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { if (!SpeedCtrlUnit.Standby) { - if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) - eimic = 1.0; - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; - double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; - if (eSCP < -1.0) - { - SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; - eSCP = -1.0; - } - SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; - if (abs(eSCP) < 0.999) - { - // TODO: check how to disable integral part when braking in smart way - // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); - } - else - { - eimicSpeedCtrlIntegral = 0; - } - auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); - if (Vel < SpeedCtrlUnit.FullPowerVelocity) - { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); - } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) - { - eimicSpeedCtrl = 0; - eimic = 0; - } + SpeedCtrlRegulator(dt, accfactor); } else { @@ -8996,6 +9415,46 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } } +// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of +// the speed; accfactor, the most power it may ask +void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) +{ + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; + double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module + bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + if (eSCP < -1.0) + { + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; + eSCP = -1.0; + } + SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; + if (abs(eSCP) < 0.999) + { + // TODO: check how to disable integral part when braking in smart way + // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); + } + else + { + eimicSpeedCtrlIntegral = 0; + } + auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; + eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + if (Vel < SpeedCtrlUnit.FullPowerVelocity) + { + eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); + } + if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) + { + eimicSpeedCtrl = 0; + eimic = 0; + } +} + bool TMoverParameters::IsSpeedCtrlSeparate() const { // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) @@ -9149,108 +9608,142 @@ bool TMoverParameters::dizel_AutoGearCheck(void) if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) { - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi - { - if (Vel > VelUp) - { - // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) - { - dizel_automaticgearstatus = 1; - OK = true; - } - } - else if (Vel < VelDown) - { - // shift down - if (ScndCtrlActualPos > 0) - { - dizel_automaticgearstatus = -1; - OK = true; - } - } - } - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; - dizel_EngageSwitch(1.0); - OK = true; - } + OK = dizel_GearShiftCheck(VelUp, VelDown); } if (Mains) { - if (EIMCtrlType > 0) // sterowanie komputerowe - { - if (dizel_automaticgearstatus == 0) - { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) - dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_EngageSwitch(0.5); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} - switch (RList[MainCtrlPos].Mn) - { - case 1: - dizel_EngageSwitch(0.5); - break; - case 2: - dizel_EngageSwitch(1.0); - break; - case 3: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.5); - break; - case 4: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.66); - break; - case 5: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); - break; - default: - if (hydro_TC && hydro_TC_Fill > 0.01) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) - dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; + dizel_ClutchCheck(); } return OK; } +// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted +bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) + { + if (dizel_engagestate > 0) + dizel_EngageSwitch(0); + if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) + dizel_automaticgearstatus = -1; + } + else + { + OK = dizel_GearShiftRequest(VelUp, VelDown); + } + if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) + { + if (dizel_automaticgearstatus == 1) + ScndCtrlActualPos++; + else + ScndCtrlActualPos--; + dizel_automaticgearstatus = 0; + dizel_EngageSwitch(1.0); + OK = true; + } + return OK; +} + +// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is +bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + { + if (Vel > VelUp) + { + // shift up + if (ScndCtrlActualPos < ScndCtrlPosNo) + { + dizel_automaticgearstatus = 1; + OK = true; + } + } + else if (Vel < VelDown) + { + // shift down + if (ScndCtrlActualPos > 0) + { + dizel_automaticgearstatus = -1; + OK = true; + } + } + } + return OK; +} + +// the pressure in the clutch's cylinder, by the controller's position or the integrated controller +void TMoverParameters::dizel_ClutchCheck() +{ + if (EIMCtrlType > 0) // sterowanie komputerowe + { + dizel_ClutchByIntegratedController(); + } + else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} + dizel_ClutchByController(); + else + dizel_EngageSwitch(0.0); + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) + dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych + if (!AutoRelayFlag) + ScndCtrlActualPos = ScndCtrlPos; +} + +// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement +void TMoverParameters::dizel_ClutchByController() +{ + switch (RList[MainCtrlPos].Mn) + { + case 1: + dizel_EngageSwitch(0.5); + break; + case 2: + dizel_EngageSwitch(1.0); + break; + case 3: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.5); + break; + case 4: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.66); + break; + case 5: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); + break; + default: + if (hydro_TC && hydro_TC_Fill > 0.01) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.0); + } +} + +// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder +void TMoverParameters::dizel_ClutchByIntegratedController() +{ + if (dizel_automaticgearstatus == 0) + { + if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) + dizel_EngageSwitch(1.0); + else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_EngageSwitch(0.5); + else + dizel_EngageSwitch(0.0); + } + else + dizel_EngageSwitch(0.0); +} + // performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise bool TMoverParameters::dizel_StartupCheck() { @@ -9370,26 +9863,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // napelnienie zalezne od MainCtrlPos if (EIMCtrlType > 0) { - realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) - { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); - } - else - { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); - else - dizel_nreg_min = dizel_nmin; - } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) - { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); - } - else - { - dizel_nreg_max = dizel_nmax; - } + realfill = dizel_DigitalFill(dt); } else { @@ -9399,54 +9873,97 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } if (dizel_nmax_cutoff > 0) { - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - switch (RList[MainCtrlPos].Mn) - { - case 0: - case 1: - nreg = dizel_nmin; - break; - case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; - else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; - break; - case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; - break; - default: - realfill = 0; // sluczaj - break; - } - if (enrot > nreg) // nad predkoscia regulatora zeruj dawke - realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna - realfill = 1; + realfill = dizel_GovernorFill(mcp, realfill); } } return std::clamp(realfill, 0.0, 1.0); } +// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to +double TMoverParameters::dizel_DigitalFill(double dt) +{ + double realfill; + realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimic_real > 0.005 && !hydro_TC_Lockup) + { + dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); + } + else + { + if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); + else + dizel_nreg_min = dizel_nmin; + } + if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) + { + dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); + } + else + { + dizel_nreg_max = dizel_nmax; + } + return realfill; +} + +// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones +double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const +{ + auto nreg{0.0}; + if (EIMCtrlType > 0) + nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; + else + nreg = dizel_GovernorRevolutions(mcp, realfill); + if (enrot > nreg) // nad predkoscia regulatora zeruj dawke + realfill = 0; + if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + realfill = 1; + return realfill; +} + +// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at +// a position the governor doesn't know +double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const +{ + auto nreg{0.0}; + switch (RList[MainCtrlPos].Mn) + { + case 0: + case 1: + nreg = dizel_nmin; + break; + case 2: + if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 3: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 4: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nmax; + else + nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; + break; + case 5: + if (Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; + break; + default: + realfill = 0; // sluczaj + break; + } + return nreg; +} + // ************************************************************************************************* // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy @@ -9499,38 +10016,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) dizel_Torque = Moment; - if (hydro_TC) // jesli przetwornik momentu - { - // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; - // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; - // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); - - // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) - { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; - } - // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) - { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; - } - // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); - } - else - { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; - } + hydro_TCFillCheck(dt); // obliczanie momentow poszczegolnych sprzegiel // sprzeglo glowne (skrzynia biegow) @@ -9538,32 +10024,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) if (hydro_TC) // jesli hydro { - double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) - { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); - } - else - { - if (nOut2In < hydro_TC_CouplingPoint) - { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - else - { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - } + hydro_TCTorque(); TorqueH = hydro_TC_TorqueOut; TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; } @@ -9635,6 +10096,74 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) return gearMoment; } +// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed +void TMoverParameters::hydro_TCFillCheck(double dt) +{ + if (hydro_TC) // jesli przetwornik momentu + { + // napelnianie przetwornika + bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + if (IsPower && Mains && enrot > dizel_nmin * 0.9) + hydro_TC_Fill += hydro_TC_FillRateInc * dt; + // oproznianie przetwornika + if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) + hydro_TC_Fill -= hydro_TC_FillRateDec * dt; + // obcinanie zakresu + hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); + + // blokowanie sprzegla blokującego + if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) + { + hydro_TC_Lockup = true; + hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; + } + // luzowanie sprzegla blokujacego + if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) + { + hydro_TC_Lockup = false; + hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; + } + // obcinanie zakresu + hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); + } + else + { + hydro_TC_Fill = 0.0; + hydro_TC_LockupRate = 0.0; + } +} + +// the torque converter's moments on its input and output shafts, by their revolutions and its fill +void TMoverParameters::hydro_TCTorque() +{ + double HydroTorque = 0; + HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; + HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; + HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; + double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); + if (hydro_TC_Table.size() > 1) + { + hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); + } + else + { + if (nOut2In < hydro_TC_CouplingPoint) + { + hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + else + { + hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + } +} + double TMoverParameters::dizel_MomentumRetarder(double n, double dt) { double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; @@ -10226,89 +10755,8 @@ void TMoverParameters::update_doors(double const Deltatime) for (auto &door : Doors.instances) { - // revoke permit if... - door.open_permit = true == door.open_permit // ...we already have one... - && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... - || (false == Doors.is_locked // ...and the door lock is engaged... - && false == door.remote_close)); // ...or the door is about to be closed - - door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); - door.is_closed = door.position <= 0.f && door.step_position <= 0.f; - door.is_door_closed = door.position <= 0.f; - - door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); - door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); - - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; - auto const openrequest{(localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open)}; - - auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || - (Doors.permit_needed && false == door.open_permit)}; - auto const closerequest{(door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open)}; - - auto const ispowered{(Doors.voltage == 0 ? true : Doors.voltage == 24 ? Power24vIsAvailable || Power110vIsAvailable : Doors.voltage == 110 ? Power110vIsAvailable : false)}; - - door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); - door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); - door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; - door.step_folding = door.step_position > 0.f // is unfolded - && (false == Doors.step_enabled // we lost permission to stay open or our door is calling the shots - || (Doors.permit_needed ? false == door.open_permit : door.is_closing)) && - (door.close_delay > Doors.close_delay || door.position <= 0.f); // door is about to close, or already done - - if (true == door.is_opening) - { - door.auto_timer = localopencontrol && door.local_open ? Doors.auto_duration : remoteopencontrol && door.remote_open && Doors.auto_include_remote ? Doors.auto_duration : -1.f; - } - // doors - if (true == door.is_opening) - { - // open door - if (false == door.step_unfolding // no wait if no doorstep - || Doors.step_type == 2) - { // no wait for rotating doorstep - door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) - { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); - } - } - door.close_delay = 0.f; - } - if (true == door.is_closing) - { - // close door - door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) - { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); - } - door.open_delay = 0.f; - } - // doorsteps - if (door.step_unfolding) - { - // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); - } - if (door.step_folding) - { - // fold left doorstep - if (TrainType == dt_EZT || TrainType == dt_DMU) - { - // multi-unit vehicles typically fold the doorstep only after closing the door - if (door.position <= 0.f) - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - else - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } + update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + move_door(door, Deltatime); } if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) @@ -10318,25 +10766,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (Doors.auto_duration > 0.f) { - // update door timers if the door close after defined time - for (auto &door : Doors.instances) - { - - if (false == door.is_open) - { - continue; - } - - if (door.auto_timer > 0.f) - { - door.auto_timer -= static_cast(Deltatime); - } - // if there's load exchange in progress, reset the timer(s) for already open doors - if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) - { - door.auto_timer = Doors.auto_duration; - } - } + update_door_timers(Deltatime); } /* // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold @@ -10354,6 +10784,169 @@ void TMoverParameters::update_doors(double const Deltatime) */ } +// the permit, the state and the requests of a door, and whether it and its step open or close +void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +{ + // revoke permit if... + door.open_permit = true == door.open_permit // ...we already have one... + && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == Doors.is_locked // ...and the door lock is engaged... + && false == door.remote_close)); // ...or the door is about to be closed + + door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); + door.is_closed = door.position <= 0.f && door.step_position <= 0.f; + door.is_door_closed = door.position <= 0.f; + + door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); + door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); + + auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{doors_powered()}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = door_step_folding(door); + + if (true == door.is_opening) + { + door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; + return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); +} + +// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or +// with its permit taken back +bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (Doors.permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + +// whether the doors have the voltage they work on +bool TMoverParameters::doors_powered() const +{ + if (Doors.voltage == 0) + { + return true; + } + if (Doors.voltage == 24) + { + return Power24vIsAvailable || Power110vIsAvailable; + } + return Doors.voltage == 110 && Power110vIsAvailable; +} + +// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to +// close or closed +bool TMoverParameters::door_step_folding(basic_door const &door) const +{ + auto const unfolded{door.step_position > 0.f}; + auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f); +} + +// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the +// opening from afar; none otherwise +float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + if (localopencontrol && door.local_open) + { + return Doors.auto_duration; + } + if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) + { + return Doors.auto_duration; + } + return -1.f; +} + +// a door and its step moved as they open or close +void TMoverParameters::move_door(basic_door &door, double const Deltatime) +{ + // doors + if (true == door.is_opening) + { + // open door + if (false == door.step_unfolding // no wait if no doorstep + || Doors.step_type == 2) + { // no wait for rotating doorstep + door.open_delay += static_cast(Deltatime); + if (door.open_delay > Doors.open_delay) + { + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); + } + } + door.close_delay = 0.f; + } + if (true == door.is_closing) + { + // close door + door.close_delay += static_cast(Deltatime); + if (door.close_delay > Doors.close_delay) + { + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); + } + door.open_delay = 0.f; + } + // doorsteps + if (door.step_unfolding) + { + // unfold left doorstep + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); + } + if (door.step_folding) + { + // fold left doorstep + if (TrainType == dt_EZT || TrainType == dt_DMU) + { + // multi-unit vehicles typically fold the doorstep only after closing the door + if (door.position <= 0.f) + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } + else + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } +} + +// the timers of the open doors which close after a while, kept running while the load is exchanged +void TMoverParameters::update_door_timers(double const Deltatime) +{ + // update door timers if the door close after defined time + for (auto &door : Doors.instances) + { + + if (false == door.is_open) + { + continue; + } + + if (door.auto_timer > 0.f) + { + door.auto_timer -= static_cast(Deltatime); + } + // if there's load exchange in progress, reset the timer(s) for already open doors + if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) + { + door.auto_timer = Doors.auto_duration; + } + } +} + // ************************************************************************************************* // Q: 20160713 // Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) @@ -11224,7 +11817,7 @@ bool TMoverParameters::LoadFIZ_Text(std::string const &Text) return LoadFIZ_Parse(fizparser); } -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former body of LoadFIZ(), moved as it was; splitting it up is a change of its own +bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) { LISTLINE = 0; startBPT = false; @@ -11249,7 +11842,7 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b // Zbieranie danych zawartych w pliku FIZ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::unordered_map fizlines; + std::map> fizlines; std::string inputline; /* while (std::getline(in, inputline)) @@ -11281,542 +11874,11 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b continue; } - // checking if table parsing should be switched off goes first... - if (issection("END-MPT", inputline)) + if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) { - startBPT = false; - startMPT = false; - startMPT0 = false; - continue; - } - if (issection("END-RL", inputline)) - { - startBPT = false; - startRLIST = false; - continue; - } - if (issection("END-UCL", inputline)) - { - startBPT = false; - startUCLIST = false; - continue; - } - if (issection("END-DL", inputline)) - { - startBPT = false; - startDLIST = false; - continue; - } - if (issection("END-DML", inputline)) - { - startBPT = false; - startDIZELMOMENTUMLIST = false; - continue; - } - if (issection("END-V2NL", inputline)) - { - startBPT = false; - startDIZELV2NMAXLIST = false; - continue; - } - if (issection("END-HTCL", inputline)) - { - startBPT = false; - startHYDROTCLIST = false; - continue; - } - if (issection("END-PML", inputline)) - { - startBPT = false; - startPMAXLIST = false; - continue; - } - if (issection("endff", inputline)) - { - startBPT = false; - startFFLIST = false; - startFFEDLIST = false; - continue; - } - if (issection("endwl", inputline)) - { - // skonczylismy czytac liste konfiguracji wycieraczek - startBPT = false; - startWiperList = false; - continue; - } - if (issection("endDimmerList", inputline)) - { - // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia - startBPT = false; - startDimmerList = false; - continue; - } - if (issection("END-WWL", inputline)) - { - startBPT = false; - startWWLIST = false; - continue; - } - if (issection("endL", inputline)) - { - startBPT = false; - startLIGHTSLIST = false; - continue; - } - if (issection("endCL", inputline)) - { - startBPT = false; - startCOMPRESSORLIST = false; - continue; - } - // ...then all recognized sections... - if (issection("Param.", inputline)) - { - startBPT = false; - fizlines.try_emplace("Param", inputline); - LoadFIZ_Param(inputline); - continue; - } - - if (issection("Load:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Load", inputline); - LoadFIZ_Load(inputline); - continue; - } - - if (issection("Dimensions:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Dimensions", inputline); - LoadFIZ_Dimensions(inputline); - continue; - } - - if (issection("Wheels:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Wheels", inputline); - LoadFIZ_Wheels(inputline); - continue; - } - - if (issection("Brake:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Brake", inputline); - LoadFIZ_Brake(inputline); - continue; - } - - if (issection("Doors:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Doors", inputline); - LoadFIZ_Doors(inputline); - continue; - } - - if (issection("BuffCoupl.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl", inputline); - LoadFIZ_BuffCoupl(inputline, 0); - continue; - } - - else if (issection("BuffCoupl1.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl1", inputline); - LoadFIZ_BuffCoupl(inputline, 1); - continue; - } - - else if (issection("BuffCoupl2.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl2", inputline); - LoadFIZ_BuffCoupl(inputline, 2); - continue; - } - - if (issection("TurboPos:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("TurboPos", inputline); - LoadFIZ_TurboPos(inputline); - continue; - } - - if (issection("Cntrl.", inputline)) - { - - startBPT = true; - LISTLINE = 0; - fizlines.try_emplace("Cntrl", inputline); - LoadFIZ_Cntrl(inputline); - continue; - } - - if (issection("Headlights:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Headlights", inputline); - LoadFIZ_Headlights(inputline); - continue; - } - - if (issection("Blending:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("Blending", inputline); - LoadFIZ_Blending(inputline); - continue; - } - - if (issection("DCEMUED:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("DCEMUED", inputline); - LoadFIZ_DCEMUED(inputline); - continue; - } - - if (issection("SpringBrake:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("SpringBrake", inputline); - LoadFIZ_SpringBrake(inputline); - continue; - } - - if (issection("Light:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Light", inputline); - LoadFIZ_Light(inputline); - continue; - } - - if (issection("Security:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Security", inputline); - SecuritySystem.load(inputline, Vmax); - extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); - continue; - } - - if (issection("Clima:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Clima", inputline); - LoadFIZ_Clima(inputline); - continue; - } - - if (issection("Power:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Power", inputline); - LoadFIZ_Power(inputline); - continue; - } - - if (issection("SpeedControl:", inputline)) - { - startBPT = false; - fizlines.try_emplace("SpeedControl", inputline); - LoadFIZ_SpeedControl(inputline); - continue; - } - - if (issection("Engine:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Engine", inputline); - LoadFIZ_Engine(inputline); - continue; - } - - if (issection("Switches:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Switches", inputline); - LoadFIZ_Switches(inputline); - continue; - } - - if (issection("MotorParamTable:", inputline)) - { - startBPT = false; - startMPT = true; - LISTLINE = 0; - fizlines.try_emplace("MotorParamTable", inputline); - LoadFIZ_MotorParamTable(inputline); - continue; - } - - if (issection("MotorParamTable0:", inputline)) - { - startBPT = false; - startMPT0 = true; - LISTLINE = 0; - continue; - } - - if (issection("Circuit:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Circuit", inputline); - LoadFIZ_Circuit(inputline); - continue; - } - - if (issection("AI:", inputline)) - { - startBPT = false; - fizlines.try_emplace("AI", inputline); - LoadFIZ_AI(inputline); - continue; - } - - if (issection("RList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("RList", inputline); - startRLIST = true; - LISTLINE = 0; - LoadFIZ_RList(inputline); - continue; - } - - if (issection("UCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("UCList", inputline); - startUCLIST = true; - LISTLINE = 0; - LoadFIZ_UCList(inputline); - continue; - } - - if (issection("DList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DList", inputline); - startDLIST = true; - LISTLINE = 0; - LoadFIZ_DList(inputline); - continue; - } - - if (issection("DMList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DMList", inputline); - startDIZELMOMENTUMLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("HTCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("HTCList", inputline); - startHYDROTCLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("PmaxList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("PmaxList", inputline); - startPMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("V2NList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("V2NList", inputline); - startDIZELV2NMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("ffList:", inputline)) - { - startBPT = false; - startFFLIST = true; - LISTLINE = 0; - LoadFIZ_FFList(inputline); - continue; - } - - if (issection("ffBrakeList:", inputline)) - { - startBPT = false; - startFFEDLIST = true; - LISTLINE = 0; - LoadFIZ_FFEDList(inputline); - continue; - } - - if (issection("WWList:", inputline)) - { - startBPT = false; - startWWLIST = true; - LISTLINE = 0; - - continue; - } - - if (issection("WiperList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("WiperList", inputline); - startWiperList = true; - LISTLINE = 0; - LoadFIZ_WiperList(inputline); - - continue; - } - - if (issection("DimmerList:", inputline)) - { - dimPositions.clear(); // uzywamy customowej listy - startBPT = false; - startDimmerList = true; - fizlines.try_emplace("DimmerList", inputline); - LoadFIZ_DimmerList(inputline); - continue; - } - - if (issection("LightsList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("LightsList", inputline); - startLIGHTSLIST = true; - LISTLINE = 0; - LoadFIZ_LightsList(inputline); - continue; - } - - if (issection("CompressorList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("CompressorList", inputline); - startCOMPRESSORLIST = true; - LISTLINE = 0; - LoadFIZ_CompressorList(inputline); - continue; - } - - // ...and finally, table parsers. - // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized - if (true == startBPT) - { - readBPT(inputline); - continue; - } - if (true == startMPT) - { - readMPT(inputline); - continue; - } - if (true == startMPT0) - { - readMPT0(inputline); - continue; - } - if (true == startRLIST) - { - readRList(inputline); - continue; - } - if (true == startUCLIST) - { - readUCList(inputline); - continue; - } - if (true == startDLIST) - { - readDList(inputline); - continue; - } - if (true == startDIZELMOMENTUMLIST) - { - readDMList(inputline); - continue; - } - if (true == startDIZELV2NMAXLIST) - { - readV2NMAXList(inputline); - continue; - } - if (true == startHYDROTCLIST) - { - readHTCList(inputline); - continue; - } - if (true == startPMAXLIST) - { - readPmaxList(inputline); - continue; - } - if (true == startFFLIST) - { - readFFList(inputline); - continue; - } - if (true == startFFEDLIST) - { - readFFEDList(inputline); - continue; - } - if (true == startWWLIST) - { - readWWList(inputline); - continue; - } - if (true == startWiperList) - { - readWiperList(inputline); - continue; - } - if (true == startDimmerList) - { - readDimmerList(inputline); - } - if (true == startLIGHTSLIST) - { - readLightsList(inputline); - continue; - } - if (true == startCOMPRESSORLIST) - { - readCompressorList(inputline); continue; } + LoadFIZ_TableRow(inputline); } // while line /* in.close(); @@ -11843,6 +11905,564 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b return result; } +// the end of the table being read; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const +{ + // checking if table parsing should be switched off goes first... + if (issection("END-MPT", inputline)) + { + startBPT = false; + startMPT = false; + startMPT0 = false; + return true; + } + if (issection("END-RL", inputline)) + { + startBPT = false; + startRLIST = false; + return true; + } + if (issection("END-UCL", inputline)) + { + startBPT = false; + startUCLIST = false; + return true; + } + if (issection("END-DL", inputline)) + { + startBPT = false; + startDLIST = false; + return true; + } + if (issection("END-DML", inputline)) + { + startBPT = false; + startDIZELMOMENTUMLIST = false; + return true; + } + if (issection("END-V2NL", inputline)) + { + startBPT = false; + startDIZELV2NMAXLIST = false; + return true; + } + if (issection("END-HTCL", inputline)) + { + startBPT = false; + startHYDROTCLIST = false; + return true; + } + if (issection("END-PML", inputline)) + { + startBPT = false; + startPMAXLIST = false; + return true; + } + if (issection("endff", inputline)) + { + startBPT = false; + startFFLIST = false; + startFFEDLIST = false; + return true; + } + if (issection("endwl", inputline)) + { + // skonczylismy czytac liste konfiguracji wycieraczek + startBPT = false; + startWiperList = false; + return true; + } + if (issection("endDimmerList", inputline)) + { + // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia + startBPT = false; + startDimmerList = false; + return true; + } + if (issection("END-WWL", inputline)) + { + startBPT = false; + startWWLIST = false; + return true; + } + if (issection("endL", inputline)) + { + startBPT = false; + startLIGHTSLIST = false; + return true; + } + if (issection("endCL", inputline)) + { + startBPT = false; + startCOMPRESSORLIST = false; + return true; + } + return false; +} + +// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +{ + // ...then all recognized sections... + if (issection("Param.", inputline)) + { + startBPT = false; + fizlines.try_emplace("Param", inputline); + LoadFIZ_Param(inputline); + return true; + } + + if (issection("Load:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Load", inputline); + LoadFIZ_Load(inputline); + return true; + } + + if (issection("Dimensions:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Dimensions", inputline); + LoadFIZ_Dimensions(inputline); + return true; + } + + if (issection("Wheels:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Wheels", inputline); + LoadFIZ_Wheels(inputline); + return true; + } + + if (issection("Brake:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Brake", inputline); + LoadFIZ_Brake(inputline); + return true; + } + + if (issection("Doors:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Doors", inputline); + LoadFIZ_Doors(inputline); + return true; + } + + if (issection("BuffCoupl.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl", inputline); + LoadFIZ_BuffCoupl(inputline, 0); + return true; + } + + else if (issection("BuffCoupl1.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl1", inputline); + LoadFIZ_BuffCoupl(inputline, 1); + return true; + } + + else if (issection("BuffCoupl2.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl2", inputline); + LoadFIZ_BuffCoupl(inputline, 2); + return true; + } + + if (issection("TurboPos:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("TurboPos", inputline); + LoadFIZ_TurboPos(inputline); + return true; + } + + if (issection("Cntrl.", inputline)) + { + + startBPT = true; + LISTLINE = 0; + fizlines.try_emplace("Cntrl", inputline); + LoadFIZ_Cntrl(inputline); + return true; + } + + if (issection("Headlights:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Headlights", inputline); + LoadFIZ_Headlights(inputline); + return true; + } + + if (issection("Blending:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("Blending", inputline); + LoadFIZ_Blending(inputline); + return true; + } + + if (issection("DCEMUED:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("DCEMUED", inputline); + LoadFIZ_DCEMUED(inputline); + return true; + } + + if (issection("SpringBrake:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("SpringBrake", inputline); + LoadFIZ_SpringBrake(inputline); + return true; + } + + if (issection("Light:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Light", inputline); + LoadFIZ_Light(inputline); + return true; + } + + if (issection("Security:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Security", inputline); + SecuritySystem.load(inputline, Vmax); + extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); + return true; + } + + if (issection("Clima:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Clima", inputline); + LoadFIZ_Clima(inputline); + return true; + } + + if (issection("Power:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Power", inputline); + LoadFIZ_Power(inputline); + return true; + } + + if (issection("SpeedControl:", inputline)) + { + startBPT = false; + fizlines.try_emplace("SpeedControl", inputline); + LoadFIZ_SpeedControl(inputline); + return true; + } + + if (issection("Engine:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Engine", inputline); + LoadFIZ_Engine(inputline); + return true; + } + + if (issection("Switches:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Switches", inputline); + LoadFIZ_Switches(inputline); + return true; + } + + if (issection("Circuit:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Circuit", inputline); + LoadFIZ_Circuit(inputline); + return true; + } + + if (issection("AI:", inputline)) + { + startBPT = false; + fizlines.try_emplace("AI", inputline); + LoadFIZ_AI(inputline); + return true; + } + + return false; +} + +// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) +{ + if (issection("MotorParamTable:", inputline)) + { + startBPT = false; + startMPT = true; + LISTLINE = 0; + fizlines.try_emplace("MotorParamTable", inputline); + LoadFIZ_MotorParamTable(inputline); + return true; + } + + if (issection("MotorParamTable0:", inputline)) + { + startBPT = false; + startMPT0 = true; + LISTLINE = 0; + return true; + } + + if (issection("RList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("RList", inputline); + startRLIST = true; + LISTLINE = 0; + LoadFIZ_RList(inputline); + return true; + } + + if (issection("UCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("UCList", inputline); + startUCLIST = true; + LISTLINE = 0; + LoadFIZ_UCList(inputline); + return true; + } + + if (issection("DList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DList", inputline); + startDLIST = true; + LISTLINE = 0; + LoadFIZ_DList(inputline); + return true; + } + + if (issection("DMList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DMList", inputline); + startDIZELMOMENTUMLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("HTCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("HTCList", inputline); + startHYDROTCLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("PmaxList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("PmaxList", inputline); + startPMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("V2NList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("V2NList", inputline); + startDIZELV2NMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("ffList:", inputline)) + { + startBPT = false; + startFFLIST = true; + LISTLINE = 0; + LoadFIZ_FFList(inputline); + return true; + } + + if (issection("ffBrakeList:", inputline)) + { + startBPT = false; + startFFEDLIST = true; + LISTLINE = 0; + LoadFIZ_FFEDList(inputline); + return true; + } + + if (issection("WWList:", inputline)) + { + startBPT = false; + startWWLIST = true; + LISTLINE = 0; + + return true; + } + + if (issection("WiperList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("WiperList", inputline); + startWiperList = true; + LISTLINE = 0; + LoadFIZ_WiperList(inputline); + + return true; + } + + if (issection("DimmerList:", inputline)) + { + dimPositions.clear(); // uzywamy customowej listy + startBPT = false; + startDimmerList = true; + fizlines.try_emplace("DimmerList", inputline); + LoadFIZ_DimmerList(inputline); + return true; + } + + if (issection("LightsList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("LightsList", inputline); + startLIGHTSLIST = true; + LISTLINE = 0; + LoadFIZ_LightsList(inputline); + return true; + } + + if (issection("CompressorList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("CompressorList", inputline); + startCOMPRESSORLIST = true; + LISTLINE = 0; + LoadFIZ_CompressorList(inputline); + return true; + } + return false; +} + +// a row of the table being read +void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) +{ + // ...and finally, table parsers. + // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized + if (true == startBPT) + { + readBPT(inputline); + return; + } + if (true == startMPT) + { + readMPT(inputline); + return; + } + if (true == startMPT0) + { + readMPT0(inputline); + return; + } + if (true == startRLIST) + { + readRList(inputline); + return; + } + if (true == startUCLIST) + { + readUCList(inputline); + return; + } + if (true == startDLIST) + { + readDList(inputline); + return; + } + if (true == startDIZELMOMENTUMLIST) + { + readDMList(inputline); + return; + } + if (true == startDIZELV2NMAXLIST) + { + readV2NMAXList(inputline); + return; + } + if (true == startHYDROTCLIST) + { + readHTCList(inputline); + return; + } + if (true == startPMAXLIST) + { + readPmaxList(inputline); + return; + } + if (true == startFFLIST) + { + readFFList(inputline); + return; + } + if (true == startFFEDLIST) + { + readFFEDList(inputline); + return; + } + if (true == startWWLIST) + { + readWWList(inputline); + return; + } + if (true == startWiperList) + { + readWiperList(inputline); + return; + } + if (true == startDimmerList) + { + readDimmerList(inputline); + } + if (true == startLIGHTSLIST) + { + readLightsList(inputline); + return; + } + if (true == startCOMPRESSORLIST) + { + readCompressorList(inputline); + return; + } +} + void TMoverParameters::LoadFIZ_Param(std::string const &line) { @@ -12461,6 +13081,14 @@ void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { + LoadFIZ_CntrlBrakes(line); + LoadFIZ_CntrlControllers(line); + LoadFIZ_CntrlStarts(line); +} + +// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes +void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) +{ { using enum TBrakeSystem; std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; @@ -12469,93 +13097,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } if (BrakeSystem != TBrakeSystem::Individual) { - using enum TBrakeHandle; - - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); - for (int idx = 0; idx < 4; ++idx) - { - - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); - } - // brakedelays, brakedelayflag - { - std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, - {"PR", bdelay_P + bdelay_R}, - {"GP", bdelay_G + bdelay_P}, - {"R", bdelay_R}, - {"P", bdelay_P}, - {"G", bdelay_G}, - {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, - {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; - std::string brakedelay; - extract_value(brakedelay, "BrakeDelays", line, ""); - auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; - lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; - } - // brakeopmode - { - std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; - auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; - } - // brakehandle - { - std::map> brakehandles{ - {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, - {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, - {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; - auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; - } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); - // brakelochandle - { - std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; - auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; - } - - // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) - { - // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; - } - - // asbtype - std::string const asb{ToLower(extract_value("ASB", line))}; - if (BrakeCtrlPosNo > 0) - { - - if (asb == "manual") - { - ASBType = 1; - } - else if (asb == "automatic") - { - ASBType = 2; - } - else if (asb == "yes") - { - ASBType = 128; - } - } - else - { - - if (asb == "yes") - { - ASBType = 128; - } - } + LoadFIZ_CntrlTrainBrake(line); } // brakesystem != individual // localbrake @@ -12567,7 +13109,96 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // mbrake extract_value(MBrake, "ManualBrake", line, ""); +} +// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake +void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) +{ + using enum TBrakeHandle; + + extract_value(BrakeCtrlPosNo, "BCPN", line, ""); + for (int idx = 0; idx < 4; ++idx) + { + + extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); + } + // brakedelays, brakedelayflag + { + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + {"PR", bdelay_P + bdelay_R}, + {"GP", bdelay_G + bdelay_P}, + {"R", bdelay_R}, + {"P", bdelay_P}, + {"G", bdelay_G}, + {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, + {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::string brakedelay; + extract_value(brakedelay, "BrakeDelays", line, ""); + auto lookup = brakedelays.find(brakedelay); + BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; + lookup = brakedelayflags.find(brakedelay); + BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; + } + // brakeopmode + { + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); + BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; + } + // brakehandle + { + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; + auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; + } + extract_value(Handle_AutomaticOverload, "HAO", line, ""); + extract_value(Handle_ManualOverload, "HMO", line, ""); + extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); + extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); + extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); + extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); + // brakelochandle + { + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; + auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + } + + // mbpm + if (true == extract_value(MBPM, "MaxBPMass", line, "")) + { + // NOTE: only convert the value from tons to kilograms if the entry is present in the config file + MBPM *= 1000.0; + } + + // asbtype + LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); +} + +// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle +void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +{ + if (asb == "yes") + { + ASBType = 128; + } + else if (BrakeCtrlPosNo > 0 && asb == "manual") + { + ASBType = 1; + } + else if (BrakeCtrlPosNo > 0 && asb == "automatic") + { + ASBType = 2; + } +} + +// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk +void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) +{ // maksymalna predkosc dostepna na tarczce predkosciomierza extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); @@ -12667,15 +13298,20 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(isBatteryButtonImpulse, "IBTB", line, ""); extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); extract_value(BatteryButtonHoldTime, "BBHT", line, ""); +} - std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, - {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; +// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays +void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) +{ + using enum start_t; + std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, + {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; // main circuit extract_value(MainsInitTime, "MainInitTime", line, ""); { auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; + MainsStart = lookup != starts.end() ? lookup->second : manual; } extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); // the brake pipe pressure of an emergency brake application, which opens the line breaker under power @@ -12684,24 +13320,24 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : start_t::manual; + BatteryStart = lookup != starts.end() ? lookup->second : manual; } // converter { auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : start_t::manual; + ConverterStart = lookup != starts.end() ? lookup->second : manual; } extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == dt_EZT ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + CompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor { auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve PantAutoValve = TrainType == dt_EZT; // legacy code behaviour, automatic valve was initially installed in all EMUs @@ -12709,13 +13345,13 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // pantographs valve { auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy code behaviour, there was no pantographs valve + PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); } // pantograph valve configuration { auto lookup = starts.find(extract_value("PantValveStart", line)); - auto valvestarttype = lookup != starts.end() ? lookup->second : start_t::manual; + auto valvestarttype = lookup != starts.end() ? lookup->second : manual; auto valvespring{true}; extract_value(valvespring, "PantValveSpring", line, ""); auto valvesolenoid{true}; @@ -12730,22 +13366,22 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // fuel pump { auto lookup = starts.find(extract_value("FuelStart", line)); - FuelPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; } // oil pump { auto lookup = starts.find(extract_value("OilStart", line)); - OilPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + OilPump.start_type = lookup != starts.end() ? lookup->second : manual; } // water pump { auto lookup = starts.find(extract_value("WaterStart", line)); - WaterPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; } // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } // what else the line contactors need to close @@ -12759,19 +13395,19 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // compartment lights { auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); - CompartmentLights.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy behaviour + CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour } // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? automatic : manual}; GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? converter : manual}; ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -12960,154 +13596,17 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) } case TEngineType::DieselEngine: { - - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) - { - dizel_nmin_hdrive = dizel_nmin; - } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) - { - dizel_nmin_retarder = dizel_nmin; - } - // TODO: unify naming scheme and sort out which diesel engine params are used where and how - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - - extract_value(engageupspeed, "EUS", Input, "0.5"); - extract_value(engagedownspeed, "EDS", Input, "0.9"); - - if (true == extract_value(AnPos, "ShuntMode", Input, "")) - { - // dodatkowa przekładnia dla SM03 (2Ls150) - ShuntModeAllow = true; - ShuntMode = false; - if (AnPos < 1.0) - { - //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie - } - } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) - { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); - - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) - { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); - } - } + LoadFIZ_EngineDiesel(Input); break; } case TEngineType::DieselElectric: { // youBy - - extract_value(Ftmax, "Ftmax", Input, ""); - Flat = extract_value("Flat", Input) == "1"; - extract_value(Vhyp, "Vhyp", Input, ""); - Vhyp /= 3.6; - extract_value(Vadd, "Vadd", Input, ""); - Vadd /= 3.6; - extract_value(PowerCorRatio, "Cr", Input, ""); - extract_value(RelayType, "RelayType", Input, ""); - if (extract_value("ShuntMode", Input) == "1") - { - - ShuntModeAllow = true; - ShuntMode = false; - AnPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; - } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - LoadFIZ_DieselElectricDynamicBrake(Input); + LoadFIZ_EngineDieselElectric(Input); break; } case TEngineType::ElectricInductionMotor: { - - RVentnmax = 1.0; - extract_value(NominalVoltage, "Volt", Input, ""); - - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); - extract_value(Flat, "Flat", Input, ""); - - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) - { - InvertersNo = 1; - } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) - { - inverter x; - Inverters.emplace_back(x); - }*/ + LoadFIZ_EngineInductionMotor(Input); break; } default: @@ -13119,40 +13618,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // NOTE: elements shared by both diesel engine variants; crude but, eh if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) { - // 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, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); - // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); - // water heater - extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); - extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf{ 1235.f }; - extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; + LoadFIZ_EngineDieselShared(Input); } // traction motors @@ -13166,6 +13632,200 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); } +// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder +void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) +{ + + extract_value(dizel_nmin, "nmin", Input, ""); + dizel_nmin /= 60.0; + dizel_nreg_min = dizel_nmin * 0.98; + extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); + dizel_nmin_hdrive /= 60.0; + if (dizel_nmin_hdrive == 0.0) + { + dizel_nmin_hdrive = dizel_nmin; + } + extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); + dizel_nmin_hdrive_factor /= 60.0; + extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); + dizel_nmin_retarder /= 60.0; + if (dizel_nmin_retarder == 0.0) + { + dizel_nmin_retarder = dizel_nmin; + } + // TODO: unify naming scheme and sort out which diesel engine params are used where and how + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); + dizel_nmax_cutoff /= 60.0; + extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); + dizel_nreg_acc /= 60.0; + extract_value(dizel_AIM, "AIM", Input, "1.0"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + + extract_value(engageupspeed, "EUS", Input, "0.5"); + extract_value(engagedownspeed, "EDS", Input, "0.9"); + + if (true == extract_value(AnPos, "ShuntMode", Input, "")) + { + // dodatkowa przekładnia dla SM03 (2Ls150) + ShuntModeAllow = true; + ShuntMode = false; + if (AnPos < 1.0) + { + //"rozruch wysoki" ma dawać większą siłę + AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie + } + } + extract_value(hydro_TC, "IsTC", Input, ""); + if (true == hydro_TC) + { + extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); + extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); + extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); + extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); + extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); + extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); + extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); + extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); + extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); + extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); + extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); + extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); + extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); + + extract_value(hydro_R, "IsRetarder", Input, ""); + if (true == hydro_R) + { + extract_value(hydro_R_Placement, "R_Place", Input, ""); + extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); + extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); + extract_value(hydro_R_MaxPower, "R_MP", Input, ""); + extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); + extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); + extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); + extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); + extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); + extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); + } + } +} + +// Engine: of a diesel-electric +void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) +{ + + extract_value(Ftmax, "Ftmax", Input, ""); + Flat = extract_value("Flat", Input) == "1"; + extract_value(Vhyp, "Vhyp", Input, ""); + Vhyp /= 3.6; + extract_value(Vadd, "Vadd", Input, ""); + Vadd /= 3.6; + extract_value(PowerCorRatio, "Cr", Input, ""); + extract_value(RelayType, "RelayType", Input, ""); + if (extract_value("ShuntMode", Input) == "1") + { + + ShuntModeAllow = true; + ShuntMode = false; + AnPos = 0.0; + ImaxHi = 2; + ImaxLo = 1; + } + extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); + extract_value(dizel_AIM, "AIM", Input, "1.25"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); +} + +// Engine: of an induction motor drive +void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) +{ + + RVentnmax = 1.0; + extract_value(NominalVoltage, "Volt", Input, ""); + + extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); + extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); + extract_value(eimc[eimc_s_p], "p", Input, ""); + extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); + extract_value(eimc[eimc_s_cim], "cim", Input, ""); + extract_value(eimc[eimc_s_icif], "icif", Input, ""); + extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); + extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); + extract_value(eimc[eimc_f_DU], "DU", Input, ""); + extract_value(eimc[eimc_f_I0], "I0", Input, ""); + extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); + extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); + extract_value(eimc[eimc_p_F0], "F0", Input, ""); + extract_value(eimc[eimc_p_a1], "a1", Input, ""); + extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); + extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); + extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); + extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); + extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); + extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); + extract_value(eimc[eimc_p_abed], "abed", Input, ""); + extract_value(eimc[eimc_p_eped], "edep", Input, ""); + extract_value(EIMCLogForce, "eimclf", Input, ""); + extract_value(InvertersNo, "InvNo", Input, ""); + extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); + extract_value(Imaxrpc, "Imaxrpc", Input, ""); + extract_value(BRVto, "BRVto", Input, ""); + extract_value(Flat, "Flat", Input, ""); + + if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) + { + InvertersNo = 1; + } + Inverters.resize(InvertersNo); + /*for (int i = 0; i > InvertersNo; i++) + { + inverter x; + Inverters.emplace_back(x); + }*/ +} + +// Engine: what both kinds of diesels have, their heat among it +void TMoverParameters::LoadFIZ_EngineDieselShared(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, ""); + extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); + extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); + extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); + extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); + // engine cooling systems + extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + // water heater + extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); + extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); + float pf{1235.f}; + extract_value(pf, "NominalCoolingPower", Input, "1235"); + dizel_heat.powerfactor = 1235 / pf; +} + void TMoverParameters::LoadFIZ_Switches(std::string const &Input) { @@ -13588,6 +14248,136 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); + CreateBrakeValve(); + + CreateBrakeHandles(); + + CreateBrakePipes(); + + if (LightsPosNo > 0) + LightsPos = LightsDefPos; + + // set default wiper switch position + wiperSwitchPos = WiperDefaultPos; + + if (CompressorListPosNo > 0) + CompressorListPos = CompressorListDefPos; + + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) + { + HeatingPowerSource.SourceType = TPowerSource::Main; + } + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + { + HeatingPowerSource.SourceType = TPowerSource::PowerCable; + HeatingPowerSource.PowerType = TPowerType::ElectricPower; + } + + // checking ready flag + // to dac potem do init + if (ReadyFlag) // gotowy do drogi + { + SetReadyToDepart(); + } + else + { // zahamowany} + SetBraked(); + } + + ActFlowSpeed = 0.0; + BrakeCtrlPosR = BrakeCtrlPos; + + if (BrakeLocHandle == TBrakeHandle::Knorr) + LocalBrakePosA = 0.5; + + Pipe->CreatePress(PipePress); + Pipe2->CreatePress(ScndPipePress); + Pipe->Act(); + Pipe2->Act(); + + EqvtPipePress = PipePress; + + Handle->Init(PipePress); + + ComputeConstans(); + + if (LoadFlag > 0) + { + + if (LoadAmount < MaxLoad * 0.45) + { + IncBrakeMult(); + IncBrakeMult(); + DecBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount < MaxLoad * 0.35) + DecBrakeMult(); + } + else + { + IncBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount >= MaxLoad * 0.55) + IncBrakeMult(); + } + } + + // taki mini automat - powinno byc ladnie dobrze :) + BrakeDelayFlag = bdelay_P; + if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) + BrakeDelayFlag = bdelay_G; + if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) + BrakeDelayFlag = bdelay_R; + /* + // disabled, as test mode is used in specific situations and not really a default + if (BrakeOpModes & bom_PS) + BrakeOpModeFlag = bom_PS; + else + */ + BrakeOpModeFlag = bom_PN; + + // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + + for (int b = 1; b < 4; b++) + { + if (BrakeDelay[b] == 0) + BrakeDelay[b] = DefBrakeTable[b]; + BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + } + + Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + /* + ScndPipePress = Compressor; + */ + // WriteLogSS("OK=", BoolTo10(OK)); + // WriteLog(""); + + if (EIMCtrlType == 3) + { + for (auto idx = 0; idx < MainCtrlPosNo; ++idx) + { + if (UniCtrlList[idx].MaxCtrlVal > 0.0) + { + UniCtrlNoPowerPos = std::max(0, idx - 1); + break; + } + } + } + + // security system + // by default place the magnet in the vehicle centre + if (SecuritySystem.MagnetLocation == 0) + { + SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + } + SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + + return OK; +} + +// the distributor valve of the vehicle's kind +void TMoverParameters::CreateBrakeValve() +{ switch (BrakeValve) { case TBrakeValve::W: @@ -13682,7 +14472,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) Hamulec->SetASBP(MaxBrakePress[4]); Hamulec->SetRV(RapidVel); +} +// the driver's handle and the local brake handle of the vehicle's kinds +void TMoverParameters::CreateBrakeHandles() +{ switch (BrakeHandle) { using enum TBrakeHandle; @@ -13744,7 +14538,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) default: LocHandle = std::make_shared(); } +} +// the brake pipe, the main pipe and the spring brake's cylinder +void TMoverParameters::CreateBrakePipes() +{ if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy Spg = 0.792; else @@ -13760,173 +14558,73 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) SpringBrake.Cylinder = std::make_shared(); SpringBrake.Cylinder->CreateCap(1); } +} - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // NOTE: legacy compatibility behaviour for vehicles without defined heating power source - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) +// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none +double TMoverParameters::InitialScndPipePress(double const HosePressure) const +{ + if (VeselVolume > 0.0) { - HeatingPowerSource.SourceType = TPowerSource::Main; + return CompressedVolume / VeselVolume; } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) { - HeatingPowerSource.SourceType = TPowerSource::PowerCable; - HeatingPowerSource.PowerType = TPowerType::ElectricPower; + return HosePressure; } + return 0.0; +} - // checking ready flag - // to dac potem do init - if (ReadyFlag) // gotowy do drogi - { - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - 0.0; - PipePress = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; - if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); - /* - // NOTE: disabled and left up to the driver, if there's any - MainSwitch( false ); - PantFront( true ); - PantRear( true ); - MainSwitch( true ); - */ - DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! - DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; - - Battery = BatteryStart != start_t::disabled; - } - else - { // zahamowany} - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - 0.0; - PipePress = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; +// the air and the controls of a vehicle ready to depart +void TMoverParameters::SetReadyToDepart() +{ + WriteLog("Ready to depart"); + CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; + ScndPipePress = InitialScndPipePress(5.0); + PipePress = CntrlPipePress; + BrakePress = 0.0; + LocalBrakePosA = 0.0; + if (CabActive == 0) BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) - { - IncManualBrakeLevel(ManualBrakePosNo); - } - if (SpringBrake.MaxBrakeForce > 0.0) - { - SpringBrake.Activate = true; - } - } - - ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; - - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; - - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); - - EqvtPipePress = PipePress; - - Handle->Init(PipePress); - - ComputeConstans(); - - if (LoadFlag > 0) - { - - if (LoadAmount < MaxLoad * 0.45) - { - IncBrakeMult(); - IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount < MaxLoad * 0.35) - DecBrakeMult(); - } - else - { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount >= MaxLoad * 0.55) - IncBrakeMult(); - } - } - - // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; + else + BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); /* - // disabled, as test mode is used in specific situations and not really a default - if (BrakeOpModes & bom_PS) - BrakeOpModeFlag = bom_PS; - else + // NOTE: disabled and left up to the driver, if there's any + MainSwitch( false ); + PantFront( true ); + PantRear( true ); + MainSwitch( true ); */ - BrakeOpModeFlag = bom_PN; + DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! + DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów + LimPipePress = CntrlPipePress; - // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + Battery = BatteryStart != start_t::disabled; +} - for (int b = 1; b < 4; b++) - { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; - } - - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); +// the air and the brakes of a vehicle standing braked +void TMoverParameters::SetBraked() +{ + WriteLog("Braked"); + Volume = BrakeVVolume * MaxBrakePress[3]; + CompressedVolume = VeselVolume * MinCompressor * 0.55; /* - ScndPipePress = Compressor; + ScndPipePress = 5.1; */ - // WriteLogSS("OK=", BoolTo10(OK)); - // WriteLog(""); - - if (EIMCtrlType == 3) + ScndPipePress = InitialScndPipePress(5.1); + PipePress = LowPipePress; + PipeBrakePress = MaxBrakePress[3] * 0.5; + BrakePress = MaxBrakePress[3] * 0.5; + LocalBrakePosA = 0.0; + BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + LimPipePress = LowPipePress; + if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) { - for (auto idx = 0; idx < MainCtrlPosNo; ++idx) - { - if (UniCtrlList[idx].MaxCtrlVal > 0.0) - { - UniCtrlNoPowerPos = std::max(0, idx - 1); - break; - } - } + IncManualBrakeLevel(ManualBrakePosNo); } - - // security system - // by default place the magnet in the vehicle centre - if (SecuritySystem.MagnetLocation == 0) + if (SpringBrake.MaxBrakeForce > 0.0) { - SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + SpringBrake.Activate = true; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); - - return OK; } // ************************************************************************************************* @@ -14022,8 +14720,26 @@ bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double con // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) { - bool OK{false}; + // the group of the command sets OK; a command none of them knows isn't done + if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) + { + return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + } + return false; +} +// RunCommand() for the controllers; returns whether the command is one of them +bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ if (Command == "MainCtrl") { // sent as MainCtrlPosForCoupled(), passed on unchanged @@ -14063,7 +14779,102 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do eimic_real = CValue1; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... + else + { + return false; + } + return true; +} + +// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them +bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Direction") + { + DirActive = static_cast(floor(CValue1)); + DirAbsolute = DirActive * CabActive; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "AutoRelaySwitch") + { + if (CValue1 == 1 && AutoRelayType == 2) + AutoRelayFlag = true; + else + AutoRelayFlag = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MaxCurrentSwitch") + { + MaxCurrentSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MinCurrentSwitch") + { + OK = MinCurrentSwitch(CValue1 == 1); + } + /*test komend oddzialywujacych na tabor*/ + else + { + return false; + } + return true; +} + +// RunCommand() for the cab and the speed control; returns whether the command is one of them +bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "CabActivisation") + { + // OK:=Power>0.01; + switch (static_cast(CValue1 * CValue2)) + { // CValue2 ma zmieniany znak przy niezgodności sprzęgów + case 1: + { + CabActive = 1; + break; + } + case -1: + { + CabActive = -1; + break; + } + default: + { + CabActive = 0; // gdy CValue1==0 + break; + } + } + if (PulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } + DirAbsolute = DirActive * CabActive; + CabMaster = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCntrl") + { + if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) + SpeedCtrlValue = static_cast(round(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCtrlUnit.Parking") + { + SpeedCtrlUnit.Parking = static_cast(CValue1); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them +bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... { if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -14086,7 +14897,119 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } - else if (Command == "WaterPumpBreakerSwitch") + else if (Command == "Emergency_brake") + { + if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? + OK = true; + else + OK = false; + } + else + { + return false; + } + return true; +} + +// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them +bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "BrakeDelay") + { + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) + { + BrakeDelayFlag = brakesetting; + OK = true; + } + else + { + OK = false; + } + SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpringBrakeActivate") + { + if (Power24vIsAvailable || Power110vIsAvailable) + { + SpringBrake.Activate = CValue1 > 0; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + OK = true; + } + + else if (Command == "Sandbox") + { + OK = Sandbox(CValue1 == 1, range_t::local); + } + else if (Command == "CabSignal") /*SHP,Indusi*/ + { // Ra: to powinno działać tylko w członie obsadzonym + SecuritySystem.set_cabsignal(); + // else OK:=false; + OK = true; // true, gdy można usunąć komendę + } + /*naladunek/rozladunek*/ + // TODO: have these commands leverage load exchange system instead + // TODO: CValue1 defines amount to load/unload + else + { + return false; + } + return true; +} + +// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them +bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "HeatingSwitch") + { + HeatingSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "ConverterSwitch") /*NBMX*/ + { + if (ConverterStart == start_t::manual) + { + ConverterAllow = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "BatterySwitch") /*NBMX*/ + { + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + { + Battery = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + // else if command='EpFuseSwitch' then {NBMX} + // begin + // if (CValue1=1) then EpFuse:=true + // else if (CValue1=0) then EpFuse:=false; + // OK:=SendCtrlToNext(command,CValue1,CValue2); + // end + else if (Command == "CompressorSwitch") /*NBMX*/ + { + CompressorSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompressorPreset") + { + CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them +bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "WaterPumpBreakerSwitch") { /* if( FuelPump.start_type != start::automatic ) { @@ -14187,7 +15110,17 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersFrontSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them +bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MotorBlowersFrontSwitch") { if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) { @@ -14243,176 +15176,26 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MainSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them +bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MainSwitch") { MainSwitch_(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CabActivisation") - { - // OK:=Power>0.01; - switch (static_cast(CValue1 * CValue2)) - { // CValue2 ma zmieniany znak przy niezgodności sprzęgów - case 1: - { - CabActive = 1; - break; - } - case -1: - { - CabActive = -1; - break; - } - default: - { - CabActive = 0; // gdy CValue1==0 - break; - } - } - if (PulleeMode) - { - // a vehicle prepared for hauling takes no cab, the command only passes through it - CabActive = 0; - } - DirAbsolute = DirActive * CabActive; - CabMaster = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "AutoRelaySwitch") - { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; - else - AutoRelayFlag = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "RelayReset") { RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "ConverterSwitch") /*NBMX*/ - { - if (ConverterStart == start_t::manual) - { - ConverterAllow = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "BatterySwitch") /*NBMX*/ - { - // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) - { - Battery = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - // else if command='EpFuseSwitch' then {NBMX} - // begin - // if (CValue1=1) then EpFuse:=true - // else if (CValue1=0) then EpFuse:=false; - // OK:=SendCtrlToNext(command,CValue1,CValue2); - // end - else if (Command == "CompressorSwitch") /*NBMX*/ - { - CompressorSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompressorPreset") - { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorPermit") - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) - { - PermitDoors_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } - - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorLock") - { - Doors.lock_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorStep") - { - Doors.step_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorMode") - { - Doors.remote_only = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DepartureSignal") - { - DepartureSignal = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "PantValve") // Winger 160204 { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; @@ -14437,63 +15220,94 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do DropAllPantographs(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MaxCurrentSwitch") + else { - MaxCurrentSwitch(CValue1 == 1, range_t::local); + return false; + } + return true; +} + +// RunCommand() for the doors and the departure signal; returns whether the command is one of them +bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "DoorPermit") + { + DoorPermitCommand(CValue1, CValue2); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MinCurrentSwitch") + else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorLock") { - OK = MinCurrentSwitch(CValue1 == 1); + Doors.lock_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - /*test komend oddzialywujacych na tabor*/ - else if (Command == "SetDamage") + else if (Command == "DoorStep") { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - { - auto const derailed{TestFlag(DamageFlag, dtrain_out)}; - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); - // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held - if (derailed && false == TestFlag(DamageFlag, dtrain_out)) - rerail(); - } + Doors.step_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Emergency_brake") + else if (Command == "DoorMode") { - if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? - OK = true; - else - OK = false; + Doors.remote_only = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "BrakeDelay") + else if (Command == "DepartureSignal") { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) - { - BrakeDelayFlag = brakesetting; - OK = true; - } - else - { - OK = false; - } - SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + DepartureSignal = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Sandbox") + else { - OK = Sandbox(CValue1 == 1, range_t::local); + return false; } - else if (Command == "CabSignal") /*SHP,Indusi*/ - { // Ra: to powinno działać tylko w członie obsadzonym - SecuritySystem.set_cabsignal(); - // else OK:=false; - OK = true; // true, gdy można usunąć komendę + return true; +} + +// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the +// direction the command comes from +void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) +{ + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) + { + PermitDoors_(side::right, CValue1 > 0); } - /*naladunek/rozladunek*/ - // TODO: have these commands leverage load exchange system instead - // TODO: CValue1 defines amount to load/unload - else if (issection("Load=", Command)) + if (std::abs(static_cast(CValue1)) & leftside) + { + PermitDoors_(side::left, CValue1 > 0); + } +} + +// the doors opened or closed from afar on the sides the command names, unless they're only worked locally +void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +{ + using enum control_t; + if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) + { + return; + } + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) + { + Doors.instances[side::right].remote_open = Open; + Doors.instances[side::right].remote_close = false == Open; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = Open; + Doors.instances[side::left].remote_close = false == Open; + } +} + +// RunCommand() for the load and the damage; returns whether the command is one of them +bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) +{ + if (issection("Load=", Command)) { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist @@ -14530,29 +15344,24 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do LastLoadChangeTime = 0.0; } } - else if (Command == "SpeedCntrl") + else if (Command == "SetDamage") { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) - SpeedCtrlValue = static_cast(round(CValue1)); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCtrlUnit.Parking") - { - SpeedCtrlUnit.Parking = static_cast(CValue1); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) + if (CValue2 == 1) + OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); + if (CValue2 == -1) { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; + OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); } - else - OK = true; } - - return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + else + { + return false; + } + return true; } // ************************************************************************************************* diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index b30372e5e..4a2029af5 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -855,25 +855,7 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -908,6 +890,29 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TESt::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the dimensionless opening factor of the ZS-filling slide valve /// (control reservoir <-> brake pipe) for the current pre-chamber/auxiliary @@ -1164,33 +1169,7 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // odluzniacz CheckReleaser(dt); - // sprawdzanie stanu - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP - 0.12) - BrakeStatus |= b_on; // hamowanie stopniowe; - else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - } - else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania - { - // if ((BrakeStatus & 1) == 0) - //{ - // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 - // // SoundFlag:=SoundFlag or sf_Acc; - // // ValveRes.Act; - //} - BrakeStatus |= b_on | b_hld; - } - else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie - BrakeStatus |= b_hld; - - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } + UpdateStatusEP2(BCP, VVP, CVP); // przeplyw ZS <-> PG if (BVP < CVP - 0.2 || BrakeStatus != b_off || BCP > 0.25) @@ -1258,6 +1237,38 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) return result; } +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TEStEP2::UpdateStatusEP2(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP - 0.12) + BrakeStatus |= b_on; // hamowanie stopniowe; + else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + } + else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania + { + // if ((BrakeStatus & 1) == 0) + //{ + // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 + // // SoundFlag:=SoundFlag or sf_Acc; + // // ValveRes.Act; + //} + BrakeStatus |= b_on | b_hld; + } + else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie + BrakeStatus |= b_hld; + + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + /// /// Recomputes the load-weighing coefficient LoadC for the current vehicle /// mass (linear between TareBP/MaxBP for TareM..LoadM, capped at 1.0). @@ -1672,58 +1683,8 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) double dV{0.0}; double dV1{0.0}; - // sprawdzanie stanu - // NOTE: partial copypaste from checkstate() of base class - // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - else if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - } - else if (VVP + 0.10 < CVP && BCP < 0.25) - { - // poczatek hamowania - if ((BrakeStatus & b_hld) == b_off) - { - SoundFlag |= sf_Acc; - } - BrakeStatus |= b_on | b_hld; - } - else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) - { - // zatrzymanie luzowanie - BrakeStatus |= b_hld; - } - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } - // equivalent of checkreleaser() in the base class? - if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) - { - if (CVP < 0.0) - { - BrakeStatus &= ~b_rls; - } - else - { // 008 - dV = PF1(CVP, BCP, 0.024) * dt; - CntrlRes->Flow(dV); - } - } + UpdateStatusLSt(BCP, VVP, CVP); + ReleaserLSt(BCP, CVP, dt); // przeplyw ZS <-> PG double temp; @@ -1770,6 +1731,87 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP + CylinderFlowLSt(BCP, BVP, CVP, dt, Vel); + + ImplsRes->Act(); + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + // LBP:=ValveRes->P(); + // ValveRes.CreatePress(ImplsRes->P()); + return result; +} + +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TLSt::UpdateStatusLSt(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + // NOTE: partial copypaste from checkstate() of base class + // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + else if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + } + else if (VVP + 0.10 < CVP && BCP < 0.25) + { + // poczatek hamowania + if ((BrakeStatus & b_hld) == b_off) + { + SoundFlag |= sf_Acc; + } + BrakeStatus |= b_on | b_hld; + } + else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) + { + // zatrzymanie luzowanie + BrakeStatus |= b_hld; + } + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + +// the releaser, or the universal button set to release, letting the control reservoir out into the impulse chamber +void TLSt::ReleaserLSt(double const BCP, double const CVP, double const dt) +{ + double dV; + // equivalent of checkreleaser() in the base class? + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) + { + if (CVP < 0.0) + { + BrakeStatus &= ~b_rls; + } + else + { // 008 + dV = PF1(CVP, BCP, 0.024) * dt; + CntrlRes->Flow(dV); + } + } +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure the relay is set to: by the pilot +// pressure, the anti-slip brake and the rapid setting, at least the local brake's +void TLSt::CylinderFlowLSt(double const BCP, double const BVP, double const CVP, double const dt, double const Vel) +{ + double dV; + double temp; RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) @@ -1795,15 +1837,6 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) dV = 0; BrakeRes->Flow(dV); BrakeCyl->Flow(-dV); - - ImplsRes->Act(); - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - // LBP:=ValveRes->P(); - // ValveRes.CreatePress(ImplsRes->P()); - return result; } /// @@ -1916,33 +1949,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) nastG = BrakeDelayFlag & bdelay_G; - // sprawdzanie stanu - if (BCP < 0.25 && VVP + 0.08 > CVP) - Przys_blok = false; - - // sprawdzanie stanu - if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) - BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania - BrakeStatus |= b_hld; - - // poczatek hamowania - if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } - - if (BCP > 0.5) - Zamykajacy = true; - else if (VVP - 0.6 < MPP) - Zamykajacy = false; + UpdateStatus(BCP, VVP, CVP, MPP); if ((BrakeStatus & b_rls) == b_rls) { @@ -1963,60 +1970,9 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); BrakeRes->Flow(dv); - // przeplyw testowy miedzypojemnosci - if (MPP < CVP - 0.3) - temp = Nozzles[4]; - else if (BCP < 0.5) - if (Zamykajacy) - temp = Nozzles[8]; // 1.25; - else - temp = Nozzles[7]; - else - temp = 0; - dv = PF(MPP, VVP, temp); + Miedzypoj->Flow(IntermediateFlow(BCP, VVP, CVP, MPP, BVP, nastG) * dt * 0.15); - if (MPP < CVP - 0.17) - temp = 0; - else if (MPP > CVP - 0.08) - temp = Nozzles[5]; - else - temp = Nozzles[6]; - dv = dv + PF(MPP, CVP, temp); - - if (MPP - 0.05 > BVP) - dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); - if (MPP > VVP) - dv = dv + PF(MPP, VVP, 0.02); - Miedzypoj->Flow(dv * dt * 0.15); - - RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; - temp = std::max(1 - RapidTemp, 0.001); - // if EDFlag then temp:=1000; - // temp:=temp/(1-); - - // powtarzacz — podwojny zawor zwrotny - temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); - - if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) - temp = std::max(temp, ASBP); - - double speed = 1; - if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) - { - temp = 0; - speed = 3; - } - - if (BrakeCyl->P() > temp) - dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; - else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) - dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; - else - dv = 0; - - BrakeCyl->Flow(dv); - if (dv > 0) - BrakeRes->Flow(-dv); + CylinderFlow(BCP, BVP, dt, Vel); // przeplyw ZS <-> PG if (MPP < CVP - 0.17) @@ -2051,6 +2007,107 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) return dv - dV1; } +// the state of the valve: braking in steps, holding or releasing, the accelerator at the start of braking, and the +// closing valve +void TEStED::UpdateStatus(double const BCP, double const VVP, double const CVP, double const MPP) +{ + // sprawdzanie stanu + if (BCP < 0.25 && VVP + 0.08 > CVP) + Przys_blok = false; + + // sprawdzanie stanu + if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) + BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; + else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.05) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + BrakeStatus |= b_hld; + + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } + + if (BCP > 0.5) + Zamykajacy = true; + else if (VVP - 0.6 < MPP) + Zamykajacy = false; +} + +// the flow into the intermediate reservoir from the pipe and the control reservoir, less the flow filling the auxiliary one +double TEStED::IntermediateFlow(double const BCP, double const VVP, double const CVP, double const MPP, double const BVP, double const nastG) const +{ + double dv; + double temp; + // przeplyw testowy miedzypojemnosci + if (MPP < CVP - 0.3) + temp = Nozzles[4]; + else if (BCP < 0.5) + if (Zamykajacy) + temp = Nozzles[8]; // 1.25; + else + temp = Nozzles[7]; + else + temp = 0; + dv = PF(MPP, VVP, temp); + + if (MPP < CVP - 0.17) + temp = 0; + else if (MPP > CVP - 0.08) + temp = Nozzles[5]; + else + temp = Nozzles[6]; + dv = dv + PF(MPP, CVP, temp); + + if (MPP - 0.05 > BVP) + dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); + if (MPP > VVP) + dv = dv + PF(MPP, VVP, 0.02); + return dv; +} + +// the cylinders filled or let out to the pressure the relay is set to: by the pilot pressure and the load, at least the +// local brake's, the anti-slip brake's, faster at the rapid setting +void TEStED::CylinderFlow(double const BCP, double const BVP, double const dt, double const Vel) +{ + double dv; + double temp; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; + temp = std::max(1 - RapidTemp, 0.001); + // if EDFlag then temp:=1000; + // temp:=temp/(1-); + + // powtarzacz — podwojny zawor zwrotny + temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); + + if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) + temp = std::max(temp, ASBP); + + double speed = 1; + if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) + { + temp = 0; + speed = 3; + } + + if (BrakeCyl->P() > temp) + dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; + else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) + dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; + else + dv = 0; + + BrakeCyl->Flow(dv); + if (dv > 0) + BrakeRes->Flow(-dv); +} + /// /// Initialises the EStED: chains TLSt::Init, sizes Miedzypoj (5 l), pre-charges /// pressures, computes BVM with a 0.05 bar offset on HPP, configures the @@ -2509,25 +2566,7 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe; - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania; - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + BCP / BVM > CVP) - { - // luzowanie; - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -2562,6 +2601,29 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TKE::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe; + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania; + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + BCP / BVM > CVP) + { + // luzowanie; + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the KE ZS-filling slide valve opening factor: closed once /// any pneumatic braking is requested, slightly attenuated when the @@ -2681,6 +2743,36 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) BrakeRes->Flow(dv); ImplsRes->Flow(-dv); + IMP = CylinderFlowKE(IMP, BCP, BVP, Vel, dt); + + // przeplyw ZP <-> rozdzielacz + temp = BVs(IMP); + // if(BrakeStatus and b_hld)=b_off then + if (IMP < 0.25 || 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); + // przeplyw PG <-> rozdzielacz + dv = PF(PP, VVP, 0.01) * dt; + ValveRes->Flow(-dv); + + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + ImplsRes->Act(); + return dv - dV1; +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure of the impulse chamber IMP, by the load +// and the rapid setting, at least the local brake's and the anti-slip brake's; returns that pressure +double TKE::CylinderFlowKE(double IMP, double const BCP, double const BVP, double const Vel, double const dt) +{ + double dv; + double temp; // rapid auto const &frictionmaterial{*FM}; if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz @@ -2715,27 +2807,7 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) dv = 0; BrakeRes->Flow(-dv); BrakeCyl->Flow(+dv); - - // przeplyw ZP <-> rozdzielacz - temp = BVs(IMP); - // if(BrakeStatus and b_hld)=b_off then - if (IMP < 0.25 || 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); - // przeplyw PG <-> rozdzielacz - dv = PF(PP, VVP, 0.01) * dt; - ValveRes->Flow(-dv); - - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - ImplsRes->Act(); - return dv - dV1; + return IMP; } /// @@ -3034,32 +3106,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) // na wszelki wypadek, zeby nie wyszlo poza zakres i_bcp = std::clamp(i_bcp, -1.999, 5.999); - double DP{0.0}; - if (TP > 0.0) - { - // jesli czasowy jest niepusty - DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) - TP -= DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - //.08 - TP = 0.0; - } - - if (XP > 0) - { - // jesli komora pod niepusta jest niepusty - DP = 2.5; - Sounds[s_fv4a_x] = DP * XP; - XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) - } - else - { - // jak pusty, to pusty - XP = 0.0; - } + DischargeChambers(dt); double pom; if (EQ(i_bcp, -1.0)) @@ -3071,21 +3118,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) pom = std::min(CP, HP); } - if (pom > RP + 0.25) - { - Fala = true; - } - if (Fala) - { - if (pom > RP + 0.3) - { - XP = XP - 20.0 * PR(pom, XP) * dt; - } - else - { - Fala = false; - } - } + UpdateWave(pom, dt); double LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie @@ -3127,28 +3160,12 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } ep = dpPipe; - if (EQ(i_bcp, 0) || RP > ep) - { - // powolne wzrastanie, ale szybsze na jezdzie; - RP += PF(RP, ep, 0.0007) * dt; - } - else - { - // powolne wzrastanie i to bardzo - RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; - } - // jednak trzeba wydluzyc, bo obecnie zle dziala - if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) - { - // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) - // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG - RP += PF(RP, CP, 0.005) * dt; - } + UpdateReductor(i_bcp, ep, dt); if (EQ(i_bcp, i_bcpno) || EQ(i_bcp, -2)) { - DP = PF(0.0, PP, ActFlowSpeed / LBDelay); + auto const DP{PF(0.0, PP, ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0.0; @@ -3171,6 +3188,80 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) return dpMainValve * dt; } +// the time reservoir and the reductor's air chamber let out, and their sounds +void TFV4aM::DischargeChambers(double const dt) +{ + double DP{0.0}; + if (TP > 0.0) + { + // jesli czasowy jest niepusty + DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) + TP -= DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + //.08 + TP = 0.0; + } + + if (XP > 0) + { + // jesli komora pod niepusta jest niepusty + DP = 2.5; + Sounds[s_fv4a_x] = DP * XP; + XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) + } + else + { + // jak pusty, to pusty + XP = 0.0; + } +} + +// the release pressure wave: on while the supply is well over the reductor's pressure, its chamber filled meanwhile +void TFV4aM::UpdateWave(double const pom, double const dt) +{ + if (pom > RP + 0.25) + { + Fala = true; + } + if (Fala) + { + if (pom > RP + 0.3) + { + XP = XP - 20.0 * PR(pom, XP) * dt; + } + else + { + Fala = false; + } + } +} + +// the reductor reservoir following the pressure ep the pipe is driven to, slowly, faster at running, and filled from +// the control reservoir under the lowest pressure of the handle +void TFV4aM::UpdateReductor(double const i_bcp, double const ep, double const dt) +{ + if (EQ(i_bcp, 0) || RP > ep) + { + // powolne wzrastanie, ale szybsze na jezdzie; + RP += PF(RP, ep, 0.0007) * dt; + } + else + { + // powolne wzrastanie i to bardzo + RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; + } + // jednak trzeba wydluzyc, bo obecnie zle dziala + if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) + { + // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) + // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG + RP += PF(RP, CP, 0.005) * dt; + } +} + /// Initialises CP and RP to the supplied pressure. /// Initial pressure [bar]. void TFV4aM::Init(double Press) @@ -3259,7 +3350,6 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double dpPipe; double dpMainValve; double ActFlowSpeed; - double DP; double pom; for (auto &soundvalue : Sounds) @@ -3270,30 +3360,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres - if (TP > 0 && CP > 4.9) - { - DP = OverloadPressureDecrease; - if (EQ(i_bcp, 0)) - TP = TP - DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - TP = 0; - } + DischargeTimedReservoir(i_bcp, dt); LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - double uop = UnbrakeOverPressure; // unbrake over pressure in actual state - ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed - if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists - uop = 0; - - if (EQ(i_bcp, -1) && uop > 0) - pom = std::min(HP, 5.4 + RedAdj + uop); - else - pom = std::min(CP, HP); + pom = SupplyPressure(i_bcp, HP); if (LimPP > CP) // podwyzszanie szybkie CP = CP + 60 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy; @@ -3313,15 +3385,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) { - if (TP < 5) - TP = TP + dt; // 5/10 - if (TP < OverloadMaxPressure) - TP = TP - 0.5 * dt; // 5/10 + ChargeTimedReservoir(dt); } if (EQ(i_bcp, 10) || EQ(i_bcp, -2)) { - DP = PF(0, PP, 2 * ActFlowSpeed / LBDelay); + auto const DP{PF(0, PP, 2 * ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0; @@ -3344,6 +3413,45 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep return dpMainValve * dt; } +// the time reservoir let out of the overload, at the running position, while the control reservoir is charged +void TMHZ_EN57::DischargeTimedReservoir(double const i_bcp, double const dt) +{ + if (TP > 0 && CP > 4.9) + { + auto const DP{OverloadPressureDecrease}; + if (EQ(i_bcp, 0)) + TP = TP - DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + TP = 0; + } +} + +// the time reservoir charged by the overload, up to its highest pressure +void TMHZ_EN57::ChargeTimedReservoir(double const dt) +{ + if (TP < 5) + TP = TP + dt; // 5/10 + if (TP < OverloadMaxPressure) + TP = TP - 0.5 * dt; // 5/10 +} + +// the pressure the handle feeds the pipe from: the supply's over the running pressure at the filling stroke, where the +// handle has the overpressure (with its button pressed, for a button worked one), the control reservoir's otherwise +double TMHZ_EN57::SupplyPressure(double const i_bcp, double const HP) +{ + double uop = UnbrakeOverPressure; // unbrake over pressure in actual state + ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed + if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists + uop = 0; + + if (EQ(i_bcp, -1) && uop > 0) + return std::min(HP, 5.4 + RedAdj + uop); + return std::min(CP, HP); +} + /// Initialises CP to the supplied pressure. /// Initial pressure [bar]. void TMHZ_EN57::Init(double Press) diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 097a164d7..1e4572dfe 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -605,6 +605,8 @@ class TESt : public TBrake /// Brake cylinder (or impulse) pressure. /// In/out accumulator for the brake pipe flow correction. void CheckState(double BCP, double &dV1); // glowny przyrzad rozrzadczy + /// The state of a valve holding: braking on in steps, the filling stopped, or released. + void CheckStateHeld(double BCP, double VVP, double CVP); /// Drives the releaser logic — bleeds the control reservoir while the releaser is engaged. /// Time step [s]. void CheckReleaser(double dt); // odluzniacz @@ -763,6 +765,12 @@ class TLSt : public TESt4R /// Constructs the LSt distributor. using TESt4R::TESt4R; + + private: + // the parts of GetPF() + void UpdateStatusLSt(double BCP, double VVP, double CVP); + void ReleaserLSt(double BCP, double CVP, double dt); + void CylinderFlowLSt(double BCP, double BVP, double CVP, double dt, double Vel); }; /// @@ -803,6 +811,13 @@ class TEStED : public TLSt /// Stores the load-weighing parameters. void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + private: + // the parts of GetPF() + void UpdateStatus(double BCP, double VVP, double CVP, double MPP); + double IntermediateFlow(double BCP, double VVP, double CVP, double MPP, double BVP, double nastG) const; + void CylinderFlow(double BCP, double BVP, double dt, double Vel); + + public: /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) { @@ -829,6 +844,10 @@ class TEStEP2 : public TLSt /// EP intensity (-1..1). double EPS = 0.0; + private: + // the part of GetPF() + void UpdateStatusEP2(double BCP, double VVP, double CVP); + public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja @@ -986,6 +1005,10 @@ class TKE : public TBrake /// Auxiliary (local) brake pressure feeding the DCV. double LBP = 0.0; // cisnienie hamulca pomocniczego + // the parts of GetPF() and CheckState() + double CylinderFlowKE(double IMP, double BCP, double BVP, double Vel, double dt); + void CheckStateHeld(double BCP, double VVP, double CVP); + public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; @@ -1164,6 +1187,10 @@ class TFV4aM : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeChambers(double dt); + void UpdateWave(double pom, double dt); + void UpdateReductor(double i_bcp, double ep, double dt); public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). @@ -1214,6 +1241,10 @@ class TMHZ_EN57 : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeTimedReservoir(double i_bcp, double dt); + void ChargeTimedReservoir(double dt); + double SupplyPressure(double i_bcp, double HP); public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). From 3cbb529d16e3b06216414fa0c55e773715a3a358 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:32 +0100 Subject: [PATCH 04/22] fix(scene): write the region cache through a temporary file, reject a damaged one (#351) * fix(scene): write the region cache through a temporary file, reject a damaged one The static geometry cache of a scenery (.sbt) was written in place, and only its 8-byte header was checked before it was used. A write cut short (a crash, the process killed, the test mode's real time watchdog) left a truncated file which every later start loaded as it was: the sections up to the cut, then whatever the reads past the end produced, with the section index used unchecked and the section size read and ignored. - basic_region::serialize() writes .sbt.tmp and renames it over the final name only when complete; a failed write is logged and the temporary file removed, the previous file stays. - basic_region::is_scene() checks the whole layout: header, section count, every section index within the region and present once, and the section sizes adding up to the length of the file. A cut-short file is turned down there ("Bad file: ... ignored"), so the scenery loads from the text and the cache is written anew at the end of the load. - basic_region::deserialize() checks the layout again, reads each section out of its own data (sectionsize bytes) and requires the section to use exactly that; sections are restored apart from the region and taken over only when the whole file was read, so a damaged file leaves nothing of itself behind. If the content is damaged although the layout holds, the default .sbt (the game's own copy of the text) is removed so the next start rebuilds it. - A vertex count the rest of the data can't hold, a shape count running past the data, and a string cut short by the end of the data (sn_utils::d_str() looped forever there) now stop the read instead of allocating or looping on. - The layout check and the write through a temporary file are in scene/regionfile.{h,cpp}, in the core library with sn_utils, and have unit tests (test_region_file.cpp). - run.py also removes a .sbt.tmp left by a run cut short. The file format is unchanged. * refactor(scene): the region file code without Sonar issues write_through_temporary takes the writer as a template parameter, the messages are built with std::format, the reading of one section moves into a helper (one break per loop), and the test drops chained assignments and implicit lambda captures. No change in behaviour. --- CMakeLists.txt | 3 +- scene/regionfile.cpp | 130 ++++++++++++ scene/regionfile.h | 77 ++++++++ scene/scene.cpp | 240 ++++++++++++++++------- scene/scene.h | 9 + scene/scenenode.cpp | 16 +- scene/sn_utils.cpp | 16 +- scene/sn_utils.h | 2 + simulation/simulationstateserializer.cpp | 8 +- tests/scenarios/run.py | 9 +- tests/unit/test_region_file.cpp | 207 +++++++++++++++++++ 11 files changed, 634 insertions(+), 83 deletions(-) create mode 100644 scene/regionfile.cpp create mode 100644 scene/regionfile.h create mode 100644 tests/unit/test_region_file.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bb63e935..2f4f8227d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,7 +146,6 @@ set(SOURCES "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" -"scene/sn_utils.cpp" "world/Segment.cpp" "environment/sky.cpp" "environment/sun.cpp" @@ -552,6 +551,8 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"scene/sn_utils.cpp" +"scene/regionfile.cpp" "utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" diff --git a/scene/regionfile.cpp b/scene/regionfile.cpp new file mode 100644 index 000000000..593e07e82 --- /dev/null +++ b/scene/regionfile.cpp @@ -0,0 +1,130 @@ +/* +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 "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +namespace scene::region_file { + +std::string +check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ) { + + Input.clear(); + Input.seekg( 0, std::ios::end ); + auto const end { Input.tellg() }; + Input.seekg( 0, std::ios::beg ); + if( ( end < 0 ) || ( false == Input.good() ) ) { + return "can't be read"; + } + auto const filesize { static_cast( end ) }; + + auto const headermain { sn_utils::ld_uint32( Input ) }; + if( auto const headertype { sn_utils::ld_uint32( Input ) }; ( false == Input.good() ) || ( headermain != Header ) || ( headertype != Version ) ) { + return "is of either unrecognized type or version"; + } + auto sectioncount { sn_utils::ld_uint32( Input ) }; + if( false == Input.good() ) { + return "ends before the section count"; + } + if( sectioncount > Sectionlimit ) { + return std::format( "holds {} sections, more than the {} a region has", sectioncount, Sectionlimit ); + } + std::vector present( Sectionlimit, false ); + std::uint64_t position { 3 * sizeof( std::uint32_t ) }; + std::uint32_t sectionnumber { 0 }; + while( sectionnumber < sectioncount ) { + if( filesize - position < section_header_size ) { + return std::format( "ends after {} of its {} sections", sectionnumber, sectioncount ); + } + std::uint32_t index; + std::uint32_t size; + if( auto const error { read_section_header( Input, Sectionlimit, index, size ) }; false == error.empty() ) { + return error; + } + if( true == present[ index ] ) { + return std::format( "holds section {} more than once", index ); + } + present[ index ] = true; + if( filesize - position < size ) { + return std::format( + "ends inside section {} ({} of {}), {} of its {} bytes are there", index, sectionnumber + 1, sectioncount, filesize - position, size ); + } + position += size; + Input.seekg( static_cast( position ), std::ios::beg ); + if( false == Input.good() ) { + return std::format( "can't be read past section {}", index ); + } + ++sectionnumber; + } + if( position != filesize ) { + return std::format( "has {} bytes past its last section", filesize - position ); + } + return {}; +} + +std::string +read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ) { + + Index = sn_utils::ld_uint32( Input ); + Size = sn_utils::ld_uint32( Input ); + if( false == Input.good() ) { + return "ends inside a section header"; + } + if( Index >= Sectionlimit ) { + return std::format( "holds section {}, out of the {} a region has", Index, Sectionlimit ); + } + if( Size < section_header_size ) { + return std::format( "gives section {} the size of {} bytes, less than its header takes", Index, Size ); + } + return {}; +} + +std::string +open_temporary( std::string const &Filename, std::ofstream &Output ) { + + Output.open( Filename + ".tmp", std::ios::binary | std::ios::trunc ); + if( Output.fail() ) { + return "can't write to file \"" + Filename + ".tmp\""; + } + return {}; +} + +std::string +finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ) { + + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + Output.close(); + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + std::filesystem::path const temporaryfile { Filename + ".tmp" }; + std::error_code result; + if( false == Error.empty() ) { + std::filesystem::remove( temporaryfile, result ); + return Error; + } + // the finished file replaces the previous version in one go, so an interrupted write doesn't leave a broken one behind + std::filesystem::rename( temporaryfile, Filename, result ); + if( result ) { + Error = "can't replace file \"" + Filename + "\": " + result.message(); + std::filesystem::remove( temporaryfile, result ); + return Error; + } + return {}; +} + +} // scene::region_file diff --git a/scene/regionfile.h b/scene/regionfile.h new file mode 100644 index 000000000..dd497a487 --- /dev/null +++ b/scene/regionfile.h @@ -0,0 +1,77 @@ +/* +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 parts of the region file (.sbt, the static geometry of a scenery cached by basic_region) which need +// nothing of the scene: checking how a file is laid out, and writing it so that an interrupted write leaves no +// cut-short file behind. kept apart so the unit tests can check them +namespace scene::region_file { + +// layout of the file: the header (two uint32: the file type and its version), the section count (uint32), then for +// each section its index (uint32), its size (uint32, counted from the start of the index, so it covers the index, +// the size itself and the section data) and the section data. all numbers little endian + +// size of the index and the size of a section, the least a section can take +std::uint32_t constexpr section_header_size { 2 * sizeof( std::uint32_t ) }; + +// checks the layout of the file held by the stream, read from its start: the header has to match the provided type +// and version, the sections have to have indices below Sectionlimit, each one no more than once, and their sizes have +// to add up to the length of the file. the section data itself isn't read. returns: the empty string if the layout +// holds, the reason why not otherwise +std::string + check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ); + +// reads the index and the size of the next section, and checks them: the index has to be below Sectionlimit, and the +// section no smaller than its own index and size. returns: the empty string if both were read and are sound, the +// reason why not otherwise +std::string + read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ); + +// opens the temporary file write_through_temporary() writes into. returns: the empty string on success, the reason of +// the failure otherwise +std::string + open_temporary( std::string const &Filename, std::ofstream &Output ); + +// closes the temporary file write_through_temporary() wrote into, and puts it in place of the file, unless Error holds +// the reason why the writing failed. the temporary file is removed on a failure. returns: the empty string on success, +// the reason of the failure otherwise +std::string + finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ); + +// writes a file with the provided function (taking the std::ostream to write into) into a temporary file next to it +// (the name with .tmp added), which then replaces the file in one go. if the writing fails or is cut short, the +// previous file (or none) stays in place, rather than a partial one; the temporary file is removed when the failure is +// noticed. returns: the empty string on success, the reason of the failure otherwise +template +std::string + write_through_temporary( std::string const &Filename, Writer_ const &Write ) { + + std::ofstream output; + if( auto const openerror { open_temporary( Filename, output ) }; false == openerror.empty() ) { + return openerror; + } + std::string error; + try { + Write( output ); + output.flush(); + } + catch( std::exception const &Exception ) { + error = "can't write to file \"" + Filename + ".tmp\": " + Exception.what(); + } + return finish_temporary( Filename, output, std::move( error ) ); +} + +} // scene::region_file diff --git a/scene/scene.cpp b/scene/scene.cpp index eed3f6438..666cd43c0 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -19,17 +19,71 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "scene/sn_utils.h" +#include "scene/regionfile.h" #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" +#include + namespace scene { std::string const EU07_FILEEXTENSION_REGION { ".sbt" }; std::uint32_t const EU07_FILEHEADER { MAKE_ID4( 'E','U','0','7' ) }; std::uint32_t const EU07_FILEVERSION_REGION { MAKE_ID4( 'S', 'B', 'T', '2' ) }; std::map Hierarchy; + +namespace { + +// name of the region file kept for specified scenario file +std::string +region_file_name( std::string const &Scenariofile ) { + + auto filename { Scenariofile }; + while( filename[ 0 ] == '$' ) { + // trim leading $ char rainsted utility may add to the base name for modified .scn files + filename.erase( 0, 1 ); + } + erase_extension( filename ); + filename = Global.asCurrentSceneryPath + filename; + filename += EU07_FILEEXTENSION_REGION; + + return filename; +} + +// reads the next section of a region file into the provided list. returns: the empty string on success, the reason +// of the failure otherwise +std::string +read_region_section( std::istream &Input, std::uint32_t const Sectionlimit, std::vector>> &Sections ) { + + // section index, followed by section data size (counted from the start of the index), followed by section data + std::uint32_t sectionindex; + std::uint32_t sectionsize; + if( auto const error { region_file::read_section_header( Input, Sectionlimit, sectionindex, sectionsize ) }; false == error.empty() ) { + return error; + } + // the section is read out of its own data, it can't reach into the next one + std::string data( sectionsize - region_file::section_header_size, '\0' ); + Input.read( data.data(), static_cast( data.size() ) ); + if( false == Input.good() ) { + return std::format( "ends inside section {}", sectionindex ); + } + std::istringstream sectioninput { std::move( data ) }; + auto section { std::make_unique() }; + section->deserialize( sectioninput ); + std::string error; + if( true == sectioninput.fail() ) { + error = std::format( "has section {} shorter than its content", sectionindex ); + } + else if( sectioninput.peek() != std::char_traits::eof() ) { + error = std::format( "has section {} longer than its content", sectionindex ); + } + Sections.emplace_back( sectionindex, std::move( section ) ); + return error; +} + +} // namespace // potentially activates event handler with the same name as provided node, and within handler activation range void @@ -241,22 +295,38 @@ basic_cell::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // cell shapes // shape count followed by opaque shape data + // NOTE: a damaged count is cut short by the end of the data rather than followed auto itemcount { sn_utils::ld_uint32( Input ) }; - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapesopaque.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapestranslucent.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_lines.emplace_back( lines_node().deserialize( Input ) ); } // cell activation flag m_active = true == m_active || false == m_shapesopaque.empty() || false == m_shapestranslucent.empty() || false == m_lines.empty(); } +// takes over the content restored from a file into another cell, as deserialize() would have added it to this one +void +basic_cell::merge( basic_cell &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapesopaque.insert( m_shapesopaque.end(), std::make_move_iterator( Other.m_shapesopaque.begin() ), std::make_move_iterator( Other.m_shapesopaque.end() ) ); + m_shapestranslucent.insert( m_shapestranslucent.end(), std::make_move_iterator( Other.m_shapestranslucent.begin() ), std::make_move_iterator( Other.m_shapestranslucent.end() ) ); + m_lines.insert( m_lines.end(), std::make_move_iterator( Other.m_lines.begin() ), std::make_move_iterator( Other.m_lines.end() ) ); + m_active = true == m_active || true == Other.m_active; + Other.m_shapesopaque.clear(); + Other.m_shapestranslucent.clear(); + Other.m_lines.clear(); +} + // sends content of the class in legacy (text) format to provided stream void basic_cell::export_as_text( std::ostream &Output ) const { @@ -885,7 +955,7 @@ basic_section::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // section shapes: shape count followed by shape data auto shapecount { sn_utils::ld_uint32( Input ) }; - while( shapecount-- ) { + while( ( shapecount-- ) && ( true == Input.good() ) ) { m_shapes.emplace_back( shape_node().deserialize( Input ) ); } // partitioned data @@ -894,6 +964,19 @@ basic_section::deserialize( std::istream &Input ) { } } +// takes over the content restored from a file into another section, as deserialize() would have added it to this one +void +basic_section::merge( basic_section &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapes.insert( m_shapes.end(), std::make_move_iterator( Other.m_shapes.begin() ), std::make_move_iterator( Other.m_shapes.end() ) ); + Other.m_shapes.clear(); + for( std::size_t index { 0 }; index < m_cells.size(); ++index ) { + m_cells[ index ].merge( std::move( Other.m_cells[ index ] ) ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_section::export_as_text( std::ostream &Output ) const { @@ -1220,26 +1303,17 @@ basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, doubl bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { return false; } - // file type and version check + // file type and version check, and whether the sections add up to the whole file. a file cut short (by a write + // interrupted with an older version, or a copy) is caught here, while the scenery can still be loaded from the text std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type + if( auto const layout { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, static_cast( m_sections.size() ) ) }; + false == layout.empty() ) { + WriteLog( "Bad file: \"" + filename + "\" " + layout + ", ignored" ); return false; } @@ -1250,38 +1324,35 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; - std::ofstream output { filename, std::ios::binary }; - - // region file version 1 - // header: EU07SBT + version (0-255) - sn_utils::ls_uint32( output, EU07_FILEHEADER ); - sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); - // sections - // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { - if( section != nullptr ) { - ++sectioncount; + // the file is written under a temporary name and takes the final one only when complete, so a write cut short + // (a crash, the process killed) leaves no partial file to be read on the next start + auto const error { region_file::write_through_temporary( filename, [ this ]( std::ostream &output ) { + // region file version 1 + // header: EU07SBT + version (0-255) + sn_utils::ls_uint32( output, EU07_FILEHEADER ); + sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); + // sections + // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range + std::uint32_t sectioncount { 0 }; + for( auto *section : m_sections ) { + if( section != nullptr ) { + ++sectioncount; + } } - } - // section count, followed by section data - sn_utils::ls_uint32( output, sectioncount ); - std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { - // section data: section index, followed by length of section data, followed by section data - if( section != nullptr ) { - sn_utils::ls_uint32( output, sectionindex ); - section->serialize( output ); } - ++sectionindex; + // section count, followed by section data + sn_utils::ls_uint32( output, sectioncount ); + std::uint32_t sectionindex { 0 }; + for( auto *section : m_sections ) { + // section data: section index, followed by length of section data, followed by section data + if( section != nullptr ) { + sn_utils::ls_uint32( output, sectionindex ); + section->serialize( output ); } + ++sectionindex; + } } ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: binary version of the scenery wasn't written, " + error ); } } @@ -1289,48 +1360,69 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; return false; } // region file version 1 - // file type and version check + // file type and version check, and whether the sections add up to the whole file std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type - WriteLog( "Bad file: \"" + filename + "\" is of either unrecognized type or version" ); + auto const sectionlimit { static_cast( m_sections.size() ) }; + auto error { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, sectionlimit ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); return false; } // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - // section count - auto sectioncount { sn_utils::ld_uint32( input ) }; - while( sectioncount-- ) { - // section index, followed by section data size, followed by section data - auto const sectionindex { sn_utils::ld_uint32( input ) }; - auto const sectionsize { sn_utils::ld_uint32( input ) }; - if( m_sections[ sectionindex ] == nullptr ) { - m_sections[ sectionindex ] = new basic_section(); + // the sections are restored apart from the region, which takes them over only once the whole file was read + // without a fault: a damaged file leaves nothing of itself behind + std::vector>> sections; + try { + input.clear(); + input.seekg( 2 * sizeof( std::uint32_t ), std::ios::beg ); + // section count + auto sectioncount { sn_utils::ld_uint32( input ) }; + sections.reserve( sectioncount ); + while( ( sectioncount-- ) && ( true == error.empty() ) ) { + error = read_region_section( input, sectionlimit, sections ); + } + } + catch( std::exception const &Exception ) { + error = std::string( "can't be read, " ) + Exception.what(); + } + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); + return false; + } + for( auto &[ sectionindex, section ] : sections ) { + if( m_sections[ sectionindex ] == nullptr ) { + m_sections[ sectionindex ] = section.release(); + } + else { + m_sections[ sectionindex ]->merge( std::move( *section ) ); } - m_sections[ sectionindex ]->deserialize( input ); } return true; } +// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew +void +basic_region::discard_scene( std::string const &Scenariofile ) const { + + auto const filename { region_file_name( Scenariofile ) }; + std::error_code error; + if( true == std::filesystem::remove( filename, error ) ) { + WriteLog( "Bad file: \"" + filename + "\" removed, it will be made anew from the scenery on the next start" ); + } + else if( error ) { + ErrorLog( "Bad file: \"" + filename + "\" can't be removed, " + error.message() + ". Remove it to have it made anew from the scenery" ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_region::export_as_text( std::ostream &Output ) const { diff --git a/scene/scene.h b/scene/scene.h index b8256e257..bde88bc87 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -134,6 +134,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another cell, as deserialize() would have added it to this one + void + merge( basic_cell &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -343,6 +346,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another section, as deserialize() would have added it to this one + void + merge( basic_section &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -474,6 +480,9 @@ public: // restores content of the class from file with specified name. returns: true on success, false otherwise bool deserialize( std::string const &Scenariofile ); + // removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew + void + discard_scene( std::string const &Scenariofile ) const; // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 18b1905a4..afe87cf83 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -108,7 +108,13 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); if(has_userdata) userdata.resize(vertices.size()); gfx::basic_vertex localvertex; @@ -527,7 +533,13 @@ lines_node::linesnode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); gfx::basic_vertex localvertex; for( auto &vertex : vertices ) { localvertex.deserialize( Input ); diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index b6a3f7c32..fbdbcb7f0 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -93,14 +93,26 @@ std::string sn_utils::d_str(std::istream &s) char c{}; while (true) { - s.read(&c, 1); - if (c == 0) + // a string cut short by the end of the data ends there too + if (!s.read(&c, 1) || c == 0) break; r.push_back(c); } return r; } +// number of bytes left to read in the stream, 0 if it failed or can't tell +std::uint64_t sn_utils::remaining(std::istream &s) +{ + auto const position{s.tellg()}; + if (position < 0) + return 0; + s.seekg(0, std::ios::end); + auto const end{s.tellg()}; + s.seekg(position); + return end > position ? static_cast(end - position) : 0; +} + bool sn_utils::d_bool(std::istream& s) { return ld_uint16(s) == 1; diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 4212ac29a..87da22d93 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -20,6 +20,8 @@ public: static glm::dvec3 d_dvec3(std::istream&); static glm::vec3 d_vec3(std::istream&); static glm::vec4 d_vec4(std::istream&); + // number of bytes left to read in the stream, 0 if it failed or can't tell + static std::uint64_t remaining(std::istream&); static void ls_uint16(std::ostream&, uint16_t); static void ls_uint32(std::ostream&, uint32_t); diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index da3e075ef..0b114f837 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -426,7 +426,13 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc // TBD: postpone loading furter and only load required blocks during the simulation? if (false == Scratchpad.binary.terrain_included) { - Region->deserialize(Scratchpad.name); + if (false == Region->deserialize(Scratchpad.name)) + { + // the file looked whole to is_scene() but its content is damaged. the geometry it holds is missing from this + // session, as the text definitions were skipped already. the file is the game's own copy of the text, so it + // goes, and the next start loads the text and writes it anew + Region->discard_scene(Scratchpad.name); + } } else { diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 52ff6cf2a..438b68aa4 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -883,10 +883,13 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float 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 + # the scenery's geometry cache. the simulator writes it through .sbt.tmp and turns down a cut-short + # one, but older builds wrote it in place and checked only its header, so the next runs would read a + # truncated one. either 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) + cache = scenery_cache(game_dir, name) + cache.unlink(missing_ok=True) + cache.with_name(cache.name + ".tmp").unlink(missing_ok=True) if result.failure: say(f" FAIL {result.failure}") ok = False diff --git a/tests/unit/test_region_file.cpp b/tests/unit/test_region_file.cpp new file mode 100644 index 000000000..346823ae3 --- /dev/null +++ b/tests/unit/test_region_file.cpp @@ -0,0 +1,207 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +// the region file (.sbt), the static geometry of a scenery the game caches beside it: a file cut short or +// damaged is turned down before any of it is used, and the game writes it so that it is never left cut short + +namespace { + +std::uint32_t constexpr header{0x37305545}; // EU07 +std::uint32_t constexpr version{0x32544253}; // SBT2 +std::uint32_t constexpr sectionlimit{500 * 500}; + +struct section { + std::uint32_t index; + std::string data; +}; + +// the file as basic_region::serialize() lays it out: the section size covers the index, the size and the data +std::string region(std::vector
const &Sections, std::uint32_t const Header = header, std::uint32_t const Version = version) { + std::ostringstream output; + sn_utils::ls_uint32(output, Header); + sn_utils::ls_uint32(output, Version); + sn_utils::ls_uint32(output, static_cast(Sections.size())); + for (auto const §ion : Sections) { + sn_utils::ls_uint32(output, section.index); + sn_utils::ls_uint32(output, static_cast(scene::region_file::section_header_size + section.data.size())); + output << section.data; + } + return output.str(); +} + +std::string check(std::string const &File) { + std::istringstream input{File}; + return scene::region_file::check_layout(input, header, version, sectionlimit); +} + +// what a writer throws when it gives up +class writer_failure : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +std::string read(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + return {std::istreambuf_iterator{input}, std::istreambuf_iterator{}}; +} + +} // namespace + +TEST_CASE("region file: a file laid out whole is accepted, with no sections or with many") { + CHECK(check(region({})) == ""); + CHECK(check(region({{0, ""}, {7, std::string(100, 'x')}, {sectionlimit - 1, std::string(3, '\0')}})) == ""); +} + +TEST_CASE("region file: a file cut short anywhere is turned down") { + auto const file{region({{12, std::string(40, 'a')}, {13, std::string(7, 'b')}, {250, std::string(64, 'c')}})}; + REQUIRE(check(file) == ""); + for (std::size_t length{0}; length < file.size(); ++length) { + CAPTURE(length); + CHECK(check(file.substr(0, length)) != ""); + } + // the count of the sections is checked against those present, and the length against where the last one ends + CHECK(check(file.substr(0, file.size() - 64 - 8)).find("ends after 2 of its 3 sections") != std::string::npos); + CHECK(check(file.substr(0, file.size() / 2)).find("ends inside section") != std::string::npos); +} + +TEST_CASE("region file: a file of another type or version is turned down") { + CHECK(check(region({{1, "x"}}, header, version + 1)).find("unrecognized type or version") != std::string::npos); + CHECK(check(region({{1, "x"}}, header + 1, version)).find("unrecognized type or version") != std::string::npos); + CHECK(check("EU0").find("unrecognized type or version") != std::string::npos); +} + +TEST_CASE("region file: sections the region can't hold, held twice, or of impossible sizes are turned down") { + CHECK(check(region({{sectionlimit, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{0xffffffffu, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{5, "x"}, {5, "y"}})).find("more than once") != std::string::npos); + + // a size smaller than the header of the section + auto file{region({{5, "abcd"}})}; + file[16] = 7; + file[17] = 0; + file[18] = 0; + file[19] = 0; + CHECK(check(file).find("less than its header takes") != std::string::npos); + // a size reaching past the end of the file + file[16] = 13; + CHECK(check(file).find("ends inside section 5") != std::string::npos); + // a size falling short of it + file[16] = 11; + CHECK(check(file).find("bytes past its last section") != std::string::npos); + // more sections than a region has + auto many{region({})}; + for (std::size_t byte{8}; byte < 12; ++byte) { + many[byte] = static_cast(0xff); + } + CHECK(check(many).find("more than the 250000") != std::string::npos); +} + +TEST_CASE("region file: the header of a section is read and checked") { + std::uint32_t index{0}; + std::uint32_t size{0}; + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size) == ""); + CHECK(index == 42); + CHECK(size == 11); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12, 6)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size).find("ends inside a section header") != std::string::npos); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, 42, index, size).find("out of the 42") != std::string::npos); + } +} + +TEST_CASE("region file: a string cut short by the end of the data ends there, rather than being read on forever") { + std::istringstream input{std::string{"abc"}}; + CHECK(sn_utils::d_str(input) == "abc"); + CHECK(input.fail()); + CHECK(sn_utils::d_str(input) == ""); + + std::istringstream whole{std::string{"abc\0def", 7}}; + CHECK(sn_utils::d_str(whole) == "abc"); + CHECK(whole.good()); +} + +TEST_CASE("region file: the bytes left in the data are known, so a count it can't hold is turned down before anything is made for it") { + std::istringstream input{std::string(100, 'x')}; + CHECK(sn_utils::remaining(input) == 100); + sn_utils::ld_uint32(input); + CHECK(sn_utils::remaining(input) == 96); + // asking doesn't move the reading on + CHECK(sn_utils::ld_uint32(input) == 0x78787878); + input.seekg(0, std::ios::end); + CHECK(sn_utils::remaining(input) == 0); + sn_utils::ld_uint32(input); + CHECK(input.fail()); + CHECK(sn_utils::remaining(input) == 0); +} + +TEST_CASE("region file: the file is written through a temporary one, which replaces the previous file when complete") { + test::scratch_folder folder{"region_file"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + auto const write = [&file](std::string const &Content) { + return scene::region_file::write_through_temporary(file.string(), [&Content](std::ostream &Output) { Output << Content; }); + }; + + SUBCASE("a new file") { + CHECK(write("first") == ""); + CHECK(read(file) == "first"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a previous file is replaced, a longer one entirely") { + REQUIRE(write("a much longer first version") == ""); + CHECK(write("second") == ""); + CHECK(read(file) == "second"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a temporary file left by a write cut short earlier is written over") { + folder.write("scenery.sbt.tmp", "left over from a crash, longer than what follows"); + CHECK(write("third") == ""); + CHECK(read(file) == "third"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } +} + +TEST_CASE("region file: a write which fails leaves the previous file, or none, and no temporary file") { + test::scratch_folder folder{"region_file_failed"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + folder.write("scenery.sbt", "previous"); + + SUBCASE("the writer gives up half way") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + throw writer_failure("out of memory"); + })}; + CHECK(error.find("out of memory") != std::string::npos); + } + SUBCASE("the stream fails") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + Output.setstate(std::ios::badbit); + })}; + CHECK(error.find("can't write to file") != std::string::npos); + } + CHECK(read(file) == "previous"); + CHECK_FALSE(std::filesystem::exists(temporary)); + + SUBCASE("the temporary file can't be made") { + auto const missing{folder.root() / "no such folder" / "scenery.sbt"}; + auto const error{scene::region_file::write_through_temporary(missing.string(), [](std::ostream &Output) { Output << "x"; })}; + CHECK(error.find("can't write to file") != std::string::npos); + CHECK_FALSE(std::filesystem::exists(missing)); + } +} From b24e87dc6394c56855b9735ccb9191ceac961925 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:55 +0100 Subject: [PATCH 05/22] Cab: the light preset selector turns on past its end, with sound (#345) * fix: the light preset selector turns on past its end with sound (eu07/maszyna#464) A selector with Wrap=Yes turned past its last position to the first one (or back) was set with PutValue(): no animation and no sound. On the EN57AKM these are the positions 0 and A1. A knob whose positions make a full turn now turns on the same way it was turned, sounding the position it reaches; other switches still jump, but sound the position too. * refactor(cab): the wrapping rotary switch without Sonar issues The full turn and the way on are declared in the ifs that use them, and the optional is tested with has_value(). No change in behaviour. --- CMakeLists.txt | 1 + tests/unit/test_gauge_wrap.cpp | 55 ++++++++++++++++++++++++++++++++++ vehicle/Gauge.cpp | 21 +++++++++++++ vehicle/Gauge.h | 4 +++ vehicle/Train.cpp | 9 +++--- vehicle/gaugewrap.cpp | 48 +++++++++++++++++++++++++++++ vehicle/gaugewrap.h | 29 ++++++++++++++++++ 7 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_gauge_wrap.cpp create mode 100644 vehicle/gaugewrap.cpp create mode 100644 vehicle/gaugewrap.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f4f8227d..a047f11ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -564,6 +564,7 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" diff --git a/tests/unit/test_gauge_wrap.cpp b/tests/unit/test_gauge_wrap.cpp new file mode 100644 index 000000000..629183369 --- /dev/null +++ b/tests/unit/test_gauge_wrap.cpp @@ -0,0 +1,55 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/gaugewrap.h" +#include "vehicle/gaugepositions.h" + +#include +#include + +// a light preset selector with Wrap=Yes turned on past its last position to the first one, or back past the first one +// to the last (eu07/maszyna#464): the EN57AKM selector has 0 as its first position and A1 as its last one, and the +// knob, rather than jump between them with no sound, turns on to the next position as it does between any two others + +TEST_CASE("gauge wrap: a knob whose positions make a full turn turns on past its end") { + CHECK(gauge_wrap::full_turn(-0.08333f, 12) == 12); // E186, BR285: 12 positions, 30 degrees each + CHECK(gauge_wrap::full_turn(-0.0625f, 16) == 16); // E189: 16 positions + CHECK(gauge_wrap::full_turn(-0.167f, 6) == 6); // EN57AL Zachodniopomorskie: a sixth given as 0.167 +} + +TEST_CASE("gauge wrap: a knob with a free position in its turn turns on across it (eu07/maszyna#464)") { + // EN57AKM: 7 positions, 45 degrees each, A1 at 270 degrees, 0 at 0 degrees: 90 degrees on from A1 to 0 + CHECK(gauge_wrap::full_turn(0.125f, 7) == 8); + // the way on is half a turn at most + CHECK(gauge_wrap::full_turn(0.25f, 3) == 4); + CHECK_FALSE(gauge_wrap::full_turn(0.125f, 4).has_value()); +} + +TEST_CASE("gauge wrap: a switch whose positions don't make a full turn doesn't turn on past its end") { + CHECK_FALSE(gauge_wrap::full_turn(0.1f, 12).has_value()); // the positions would overlap in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.15f, 6).has_value()); // 6.67 positions in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.f, 6).has_value()); // no motion + CHECK_FALSE(gauge_wrap::full_turn(0.5f, 1).has_value()); // nothing to turn to +} + +TEST_CASE("gauge wrap: turned round, the knob stands the same one turn earlier or later") { + // EN57AKM, from A1 (value 6) on to 0: from -2 up to 0, 90 degrees the way it was turned + CHECK(gauge_wrap::turned_round(6.f, 8, true) == doctest::Approx(-2.f)); + // from 0 back to A1 (value 6): from 8 down to 6 + CHECK(gauge_wrap::turned_round(0.f, 8, false) == doctest::Approx(8.f)); + // the angle stays: value * scale differs by one full turn + CHECK((6.f - gauge_wrap::turned_round(6.f, 8, true)) * 0.125f == doctest::Approx(1.f)); +} + +TEST_CASE("gauge wrap: turned round, the knob sounds the position it reaches (eu07/maszyna#464)") { + // the EN57AKM selector has a sound for each position 0-7, as values of the gauge + std::map sounds{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}}; + auto const reached{[&sounds](float const From, float const To) { + auto const position{gauge_positions::last_reached(sounds, static_cast(std::round(100.f * From)), static_cast(std::round(100.f * To)))}; + return position != sounds.end() ? position->second : -1; + }}; + // A1 (6) on to 0 + CHECK(reached(gauge_wrap::turned_round(6.f, 8, true), 0.f) == 0); + // 0 back to A1 (6) + CHECK(reached(gauge_wrap::turned_round(0.f, 8, false), 6.f) == 6); +} diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index c99448eed..0944fe83b 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Gauge.h" #include "vehicle/gaugepositions.h" #include "vehicle/gaugeduplicates.h" +#include "vehicle/gaugewrap.h" #include "utilities/parser.h" #include "model/Model3d.h" #include "vehicle/DynObj.h" @@ -401,6 +402,26 @@ TGauge::UpdateValue( float fNewDesired ) { return false; // no suitable sound was found } +void +TGauge::UpdateValueWrapped( float const fNewDesired, bool const Forward, int const Positions, std::optional &Fallbacksound ) { + + if( auto const turn { ( + m_animation == TGaugeAnimation::gt_Rotate && false == m_interpolatescale && m_scaletable.empty() ? + gauge_wrap::full_turn( m_scale, Positions ) : + std::nullopt ) }; + turn.has_value() ) { + // the knob stands the same one turn earlier (later), from there it turns on to the new position + // rather than all the way back, sounding the position it reaches + m_value = gauge_wrap::turned_round( m_value, *turn, Forward ); + m_targetvalue = gauge_wrap::turned_round( m_targetvalue, *turn, Forward ); + UpdateValue( fNewDesired, Fallbacksound ); + return; + } + // a switch that doesn't turn all the way round jumps to the new position, which still sounds + UpdateValue( fNewDesired, Fallbacksound ); + m_value = m_targetvalue; +} + void TGauge::PutValue(float fNewDesired) { // McZapkie-281102: natychmiastowe wpisanie wartosci m_targetvalue = fNewDesired; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index 18ddf373a..9c93057c1 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -47,6 +47,10 @@ public: void Load(cParser &Parser, TDynamicObject const *Owner, double const mul = 1.0); bool UpdateValue( float fNewDesired ); bool UpdateValue( float fNewDesired, std::optional &Fallbacksound ); + // sets a multi-position switch of Positions positions, turned on past its last position to the first one (Forward) + // or back past the first one to the last, to the position at fNewDesired. A knob which turns all the way round + // turns on the same way, others jump there; either way the position reached sounds + void UpdateValueWrapped( float fNewDesired, bool Forward, int Positions, std::optional &Fallbacksound ); void PutValue(float fNewDesired); float GetValue() const; float GetDesiredValue() const; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 4ed2a6b67..080e697c4 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -5455,14 +5455,15 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // past the last position to the first one: a knob turning all the way round turns on rather than + // back across all the positions, and the position reached sounds (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } @@ -5493,14 +5494,14 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // back past the first position to the last one, the same way (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } diff --git a/vehicle/gaugewrap.cpp b/vehicle/gaugewrap.cpp new file mode 100644 index 000000000..f16b6e857 --- /dev/null +++ b/vehicle/gaugewrap.cpp @@ -0,0 +1,48 @@ +/* +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/gaugewrap.h" + +#include + +namespace gauge_wrap { + +namespace { + +// how far the positions in a full turn worked out from the scale may be off a whole number: the scales in the cab +// definitions are given to three decimals or so, 0.167 for a sixth gives 5.988 +constexpr double turn_tolerance{0.05}; + +} // namespace + +std::optional full_turn(float const Scale, int const Positions) { + if (Positions < 2 || Scale == 0.f) { + return std::nullopt; + } + auto const perturn{1.0 / std::abs(static_cast(Scale))}; + auto const turn{std::round(perturn)}; + if (std::abs(perturn - turn) > turn_tolerance) { + // the positions don't make a full turn: a lever, or a knob that stops at its ends + return std::nullopt; + } + auto const positions{static_cast(turn)}; + // the way on from the last position to the first one, in positions + if (auto const wayon{positions - (Positions - 1)}; wayon < 1 || 2 * wayon > positions) { + // the positions overlap in a turn, or the knob would turn on more than half a turn + return std::nullopt; + } + return positions; +} + +float turned_round(float const Value, int const Turn, bool const Forward) { + return Forward ? Value - static_cast(Turn) : Value + static_cast(Turn); +} + +} // namespace gauge_wrap diff --git a/vehicle/gaugewrap.h b/vehicle/gaugewrap.h new file mode 100644 index 000000000..126652922 --- /dev/null +++ b/vehicle/gaugewrap.h @@ -0,0 +1,29 @@ +/* +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 + +// a multi-position rotary switch of the cab turned past its last position to the first one, or back past the first +// one to the last (a selector with Wrap=Yes, such as the light preset selector) +namespace gauge_wrap { + +// the number of positions in one full turn of a rotary switch of Positions positions that turns by Scale of a full turn +// per position, if the switch can turn on past its end the short way round: the full turn is a whole number of positions +// (within the rounding of the scale in the cab definition, e.g. 0.167 for a sixth), all the positions fit in it, and the +// way on from the last position to the first one is at most half a turn. None otherwise +std::optional full_turn(float Scale, int Positions); + +// the value of the switch at Value seen one full turn of Turn positions earlier (Forward: it turns on past its last +// position to the first one) or later (back past the first position to the last one). The knob stands the same there, +// and turning from that value to the new position turns it on the way it was turned rather than all the way back +float turned_round(float Value, int Turn, bool Forward); + +} // namespace gauge_wrap From 97a6218094e9556c9b24cd2ee1b331a240842515 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:33:34 +0100 Subject: [PATCH 06/22] fix(audio): measure the start offset on the buffer queued last, not on AL_BUFFER (AL_INVALID_NAME) (#350) * fix(audio): measure the start offset on the buffer queued last, not on AL_BUFFER (AL_INVALID_NAME) openal_source::update() looked up the buffer left playing after a multipart sound's opening bookend with alGetSourcei(AL_BUFFER). For a source with queued buffers that is 0 in OpenAL Soft 1.18 (the version the game ships), and in newer versions once the source has stopped, so alGetBufferi(0) raised AL_INVALID_NAME ("sound: al error: AL_INVALID_NAME" in errors.txt) and the sample offset came from an uninitialised size. It happened every time a sound with a start offset (the motor blowers of the EN76/EN96 family, with start/stop bookends) went from its start sample to the loop. The source now remembers the buffer it queued last and measures that one. The offset itself is computed by audio::start_sample(), in the core library with unit tests; it also keeps the offset inside the buffer. * refactor(audio): the start sample without Sonar issues The sample count is cast to float explicitly, as it was converted implicitly. No change in behaviour. --- CMakeLists.txt | 1 + audio/audiorenderer.cpp | 16 +++++++-------- audio/audiorenderer.h | 2 ++ audio/audiorenderer_extra.h | 5 +++-- audio/startsample.cpp | 28 ++++++++++++++++++++++++++ audio/startsample.h | 19 ++++++++++++++++++ tests/unit/test_start_sample.cpp | 34 ++++++++++++++++++++++++++++++++ 7 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 audio/startsample.cpp create mode 100644 audio/startsample.h create mode 100644 tests/unit/test_start_sample.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a047f11ad..3e80acbf7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -541,6 +541,7 @@ add_library(eu07_settings INTERFACE) # the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle # 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 +"audio/startsample.cpp" "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 7950fca56..7d5285def 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -182,18 +182,16 @@ openal_source::update( double const Deltatime, glm::vec3 const &Listenervelocity --sound_index; sound_change = true; // potentially adjust starting point of the last buffer (to reduce chance of reverb effect with multiple, looping copies playing) - if( controller->start() > 0.f && sounds.size() == 1 ) { - ALint bufferid; - ::alGetSourcei( - id, - AL_BUFFER, - &bufferid ); - ALint buffersize; - ::alGetBufferi( bufferid, AL_SIZE, &buffersize ); + if( controller->start() > 0.f && sounds.size() == 1 && last_buffer != audio::null_resource ) { + // NOTE: the buffer is the one queued last, not the one the source reports: for a source with queued + // buffers AL_BUFFER is 0 in OpenAL Soft 1.18 (the one the game comes with), and in the newer ones + // once the source has stopped. alGetBufferi() on buffer 0 fails with AL_INVALID_NAME + ALint buffersize { 0 }; + ::alGetBufferi( last_buffer, AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 86ea89cd8..afa819c1b 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "audio/audio.h" +#include "audio/startsample.h" #include "model/ResourceManager.h" #include "application/uitranscripts.h" @@ -69,6 +70,7 @@ struct openal_source { using buffer_sequence = std::vector; ALuint id { audio::null_resource }; + ALuint last_buffer { audio::null_resource }; // the buffer queued last, the one left playing once those before it are done sound_source *controller { nullptr }; uint32_sequence sounds; int sound_index { 0 }; diff --git a/audio/audiorenderer_extra.h b/audio/audiorenderer_extra.h index 430f594b3..fb38816fc 100644 --- a/audio/audiorenderer_extra.h +++ b/audio/audiorenderer_extra.h @@ -19,6 +19,7 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ if( id != audio::null_resource && !buffers.empty()) { ::alSourceQueueBuffers( id, static_cast( buffers.size() ), buffers.data() ); + last_buffer = buffers.back(); ::alSourceRewind( id ); // sound controller can potentially request playback to start from certain buffer point // for multipart sounds the offset is applied only to last piece during playback @@ -29,12 +30,12 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ } else { // move playback start to specified point in 0-1 range - ALint buffersize; + ALint buffersize { 0 }; ::alGetBufferi( buffers.front(), AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/startsample.cpp b/audio/startsample.cpp new file mode 100644 index 000000000..673dda151 --- /dev/null +++ b/audio/startsample.cpp @@ -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/. +*/ + +#include "stdafx.h" +#include "audio/startsample.h" + +#include +#include + +namespace audio { + +int start_sample( float const Start, int const Buffersize ) { + + auto const samples { Buffersize / static_cast( sizeof( std::int16_t ) ) }; + if( samples <= 0 + || false == ( Start > 0.f ) ) { // also a NaN + return 0; + } + return std::min( static_cast( std::min( Start, 1.f ) * static_cast( samples ) ), samples - 1 ); +} + +} // audio diff --git a/audio/startsample.h b/audio/startsample.h new file mode 100644 index 000000000..e9837a3a9 --- /dev/null +++ b/audio/startsample.h @@ -0,0 +1,19 @@ +/* +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 + +namespace audio { + +// the sample a sound set to start at Start (a fraction of its length, 0-1) begins to play from, in a buffer of +// Buffersize bytes of 16 bit mono samples (the sound buffers are all made so, see upload_sound()). always a sample +// the buffer has: OpenAL rejects an offset at or past the end with AL_INVALID_VALUE. 0 for an empty buffer +int start_sample( float const Start, int const Buffersize ); + +} // audio diff --git a/tests/unit/test_start_sample.cpp b/tests/unit/test_start_sample.cpp new file mode 100644 index 000000000..00e7fc781 --- /dev/null +++ b/tests/unit/test_start_sample.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "audio/startsample.h" + +#include + +// the sample a sound with a start offset (startoffset:, or the random one of motors, motor blowers and +// the running noise) begins to play from, in the 16 bit mono buffers the sound files are loaded into + +TEST_CASE("start_sample: a fraction of the samples of the buffer, two bytes each") { + CHECK(audio::start_sample(0.5f, 1000) == 250); + CHECK(audio::start_sample(0.25f, 88200) == 11025); + CHECK(audio::start_sample(0.999f, 1000) == 499); +} + +TEST_CASE("start_sample: no offset starts at the first sample") { + CHECK(audio::start_sample(0.f, 1000) == 0); + CHECK(audio::start_sample(-0.5f, 1000) == 0); + CHECK(audio::start_sample(std::numeric_limits::quiet_NaN(), 1000) == 0); +} + +TEST_CASE("start_sample: the end of the buffer is its last sample, not past it") { + // OpenAL takes an offset at or past the end of the buffer for AL_INVALID_VALUE + CHECK(audio::start_sample(1.f, 1000) == 499); + CHECK(audio::start_sample(1.5f, 1000) == 499); + CHECK(audio::start_sample(1.f, 2) == 0); +} + +TEST_CASE("start_sample: a buffer of unknown or no size starts at 0") { + CHECK(audio::start_sample(0.5f, 0) == 0); + CHECK(audio::start_sample(0.5f, 1) == 0); + CHECK(audio::start_sample(0.5f, -4) == 0); +} From 96bc3e686358fdd47d12bc5785f7f0d08689d2f3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:33:42 +0100 Subject: [PATCH 07/22] fix(cab): the compartment lights keyboard toggle works more than once in a cab without the switch (#353) * fix(cab): the compartment lights keyboard toggle works more than once in a cab without the switch The compartment lights get two requests, on (CompartmentLights.is_enabled) and off (is_disabled), and the off one wins in LightsCheck(). The enable and disable commands withdrew the other request only when the cab had a toggle type compartmentlights_sw:. A push type switch and the separate compartmentlightson_sw:/compartmentlightsoff_sw: push buttons withdraw their own request when released, but a cab with none of these controls (the CD 810 cab A, where only the engine compartment has the switch) never withdrew anything: after one on/off both requests stayed set, the lights stayed off and ctrl+; kept choosing "turn off". Now a command withdraws the other request when the cab has the toggle type switch (as before), or when it has no compartmentlights_sw: and no push button for the other request, so the keyboard toggle acts as a two-state switch there. Cabs with a push type switch or with the on/off push buttons keep their behaviour. The decision is in vehicle/compartmentlightsswitch.h, unit tested together with the vehicle's LightsCheck() on the Elf definition. * fix(cab): the compartment lights keyboard toggle latches in a cab with the on and off push buttons (#355) In a cab with the compartmentlightson_sw: / compartmentlightsoff_sw: push buttons and no compartmentlights_sw: (the EN57-2000, the SA134, the 214M, the EN57AKL/AL/KM and EN71) ctrl+; turned the compartment lights off only while the key was held. OnCommand_compartmentlightstoggle picked the command from the lights' state again on the key release, after the press had changed that state, so the release went to the other command: the push button that was pressed never withdrew its request. After the first press the on request stayed set, and from then on every release withdrew the off request and the lights came back on. The toggle now sends the release to both commands, as a release of the push buttons would: each returns its own push type control to the neutral position and withdraws its request. The press is picked from the state as before. Mouse clicks on the push buttons go to the enable and disable commands directly and are unchanged; with a compartmentlights_sw: both commands release it the same way, and a cab without the controls has nothing to release. In the Elf cab (an impulse compartmentlights_sw: and the on/off return buttons) the lights worked, but the button the key had pressed stayed pressed; now it returns too. * test(cab): the compartment lights switch test without Sonar issues using enum for range_t in the release helpers, and the lights declared in the if that reads them. No change in what is tested. --- tests/unit/test_compartment_lights_switch.cpp | 227 ++++++++++++++++++ vehicle/Train.cpp | 31 ++- vehicle/compartmentlightsswitch.h | 27 +++ 3 files changed, 273 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_compartment_lights_switch.cpp create mode 100644 vehicle/compartmentlightsswitch.h diff --git a/tests/unit/test_compartment_lights_switch.cpp b/tests/unit/test_compartment_lights_switch.cpp new file mode 100644 index 000000000..b9ba78398 --- /dev/null +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "vehicle/compartmentlightsswitch.h" + +using test::definition; +using test::vehicle; + +// the compartment lights commands of the cab (TTrain::OnCommand_compartmentlightsenable/disable/toggle): whether the +// command for one request (on: CompartmentLights.is_enabled, off: is_disabled) also withdraws the other one. In a cab +// without compartmentlights_sw: and without the push buttons (the CD 810 cab A) the keyboard toggle, ctrl+;, turned +// the lights on and off once, then never again: the off request stayed set alongside the on one. In a cab with the +// compartmentlightson_sw: / compartmentlightsoff_sw: push buttons (the EN57-2000) the toggle sent the key release to the +// other command than the press, picked again from the state the press had changed: the pressed button never withdrew +// its request and the lights were off only while ctrl+; was held. + +TEST_CASE("compartment lights switch: which command withdraws the other request") { + // a two-state compartmentlights_sw: holds one request at a time + CHECK(compartment_lights_switch::withdraws_other_request(true, true, false)); + CHECK(compartment_lights_switch::withdraws_other_request(true, true, true)); + // a push type compartmentlights_sw: withdraws both requests itself, when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, false)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, true)); + // no compartmentlights_sw:, the push button of the other request withdraws it when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, false, true)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, true, true)); + // no compartmentlights_sw: and no push button: nothing else would withdraw it + CHECK(compartment_lights_switch::withdraws_other_request(false, false, false)); + CHECK(compartment_lights_switch::withdraws_other_request(false, true, false)); +} + +namespace { + +// the compartment lights controls a cab's .mmd may have +struct cab_controls { + bool has_switch{false}; // compartmentlights_sw: + bool switch_is_toggle{true}; // its type (a gauge is a toggle type unless declared otherwise) + bool has_on_button{false}; // compartmentlightson_sw: + bool has_off_button{false}; // compartmentlightsoff_sw: +}; + +// the effect of the cab's commands on the vehicle, as TTrain::OnCommand_compartmentlightsenable/disable/toggle do it +// NOTE: LightsCheck() runs between the press and the release, as the vehicle update does between two frames +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +void enable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitch(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_off_button)) { + Car->CompartmentLightsSwitchOff(false, range_t::local); + } +} + +void enable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_on_button) { + Car->CompartmentLightsSwitch(false, local); + } +} + +void disable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitchOff(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_on_button)) { + Car->CompartmentLightsSwitch(false, range_t::local); + } +} + +void disable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_off_button) { + Car->CompartmentLightsSwitchOff(false, local); + } +} + +// a click on the control of the command (or its own key): the press, then the release +void enable(vehicle &Car, cab_controls const &Cab) { + enable_press(Car, Cab); + lights_check(Car); + enable_release(Car, Cab); + lights_check(Car); +} + +void disable(vehicle &Car, cab_controls const &Cab) { + disable_press(Car, Cab); + lights_check(Car); + disable_release(Car, Cab); + lights_check(Car); +} + +// the keyboard toggle picks the command from the state on the press, the key held down for a few frames; the release +// goes to both commands, the press changed the state it would be picked from +void toggle(vehicle &Car, cab_controls const &Cab) { + if (auto const &lights{Car->CompartmentLights}; false == lights.is_active && false == lights.is_enabled) { + enable_press(Car, Cab); + } + else { + disable_press(Car, Cab); + } + for (auto frame = 0; frame < 3; ++frame) { + lights_check(Car); + } + enable_release(Car, Cab); + disable_release(Car, Cab); + lights_check(Car); +} + +// the Elf (21WE-a), its compartment lights started by hand, with the converter running +void power_up(vehicle &Car) { + REQUIRE(Car->CompartmentLights.start_type == start_t::manual); + Car->Power110vIsAvailable = true; + lights_check(Car); + REQUIRE_FALSE(Car->CompartmentLights.is_active); +} + +} // namespace + +TEST_CASE("compartment lights switch: the keyboard toggle works every time in a cab without the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{}; // no compartmentlights_sw:, no push buttons, like the CD 810 cab A + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // one request at a time + CHECK_FALSE((car->CompartmentLights.is_enabled && car->CompartmentLights.is_disabled)); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle in a cab with the two-state switch, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = true}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // the switch holds the request of its position + CHECK(car->CompartmentLights.is_enabled == (press % 2 == 1)); + CHECK(car->CompartmentLights.is_disabled == (press % 2 == 0)); + } +} + +TEST_CASE("compartment lights switch: the push type switch withdraws both requests when released, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = false}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the on and off push buttons latch the lights, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + for (auto round = 1; round <= 2; ++round) { + CAPTURE(round); + // each button withdraws its own request when it's released, the lights stay as they were put + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle latches the lights in a cab with the on and off push buttons") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; // no compartmentlights_sw:, like the EN57-2000 + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off, and they stay so after the key is released + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // both push buttons are back in the neutral position, neither request is left behind + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle and the on and off push buttons work together") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + toggle(car, cab); + REQUIRE(car->CompartmentLights.is_active); + // the off button turns off what the key turned on... + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + // ...and the key turns on what the off button turned off + toggle(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); +} diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 080e697c4..24d3132f6 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/horn.h" #include "vehicle/linebreaker.h" #include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" #include "vehicle/odometer.h" #include "vehicle/mainctrlact.h" @@ -6636,6 +6637,16 @@ void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const return; } + if (Command.action == GLFW_RELEASE) + { + // the press changed the state the command is picked from below, so a release picked from it went to the other + // command and the push button that was pressed never withdrew its request. The release goes to both commands: + // each returns its own push type control to the neutral position and withdraws its request + OnCommand_compartmentlightsenable(Train, Command); + OnCommand_compartmentlightsdisable(Train, Command); + return; + } + // keep the switch from flipping back and forth if key is held down if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) { @@ -6655,13 +6666,11 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitch(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the off request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - } + Train->mvOccupied->CompartmentLightsSwitchOff(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -6696,13 +6705,11 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitchOff(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the on request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightson_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - } + Train->mvOccupied->CompartmentLightsSwitch(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) diff --git a/vehicle/compartmentlightsswitch.h b/vehicle/compartmentlightsswitch.h new file mode 100644 index 000000000..0ef6684c0 --- /dev/null +++ b/vehicle/compartmentlightsswitch.h @@ -0,0 +1,27 @@ +/* +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 compartment lights get two requests: on (CompartmentLights.is_enabled) and off (is_disabled), and the off one +// wins. A two-state compartmentlights_sw: holds one of them, so turning it to one position withdraws the other request. +// A push type compartmentlights_sw: and the separate compartmentlightson_sw: / compartmentlightsoff_sw: push buttons +// withdraw their own request when they're released, so the other command leaves it alone. A cab with none of these +// controls (the keyboard toggle, ctrl+;, is all there is) acts as if it had the two-state switch, otherwise nothing +// would ever withdraw the off request and the lights couldn't be turned on again. +namespace compartment_lights_switch { + +// whether the command for one of the requests also withdraws the other one, from the cab's compartmentlights_sw: +// (whether it's there and whether it's a toggle type switch) and whether the cab has the push button of the other +// request (compartmentlightsoff_sw: for the on command, compartmentlightson_sw: for the off command) +inline bool withdraws_other_request(bool const Hasswitch, bool const Switchistoggle, bool const Hasotherbutton) { + return Hasswitch ? Switchistoggle : false == Hasotherbutton; +} + +} // namespace compartment_lights_switch From 8bff78588634d41769255a777c21f41173810668 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:34:04 +0100 Subject: [PATCH 08/22] build: optionally use the system nlohmann_json (USE_SYSTEM_JSON) (#360) USE_SYSTEM_JSON (default OFF) takes an installed nlohmann_json 3.9 or newer (ordered_json, used by the unit tests) with find_package instead of the ref/json submodule. Both give the nlohmann_json::nlohmann_json target linked to eu07_settings. Drop the include directory from the never defined NLOHMANN_JSON_INCLUDE_INSTALL_DIR. Fixes #54. --- CMakeLists.txt | 11 ++++++++--- README.md | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3e80acbf7..cf1b137f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -86,6 +86,7 @@ option(ENABLE_MCC "Enable multicore compilation" ON) option(WITHDUMPGEN "Enable generating DMP files on crash" ON) option(ENABLE_AVX2 "Enable AVX2 instruction set (requires AVX2-capable CPU, Haswell/2013 or newer)" ON) option(ADD_VERSION_SUFFIX "Add date and commit hash to the executable name" ON) +option(USE_SYSTEM_JSON "Use an installed nlohmann_json (3.9 or newer) instead of the ref/json submodule" OFF) set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) # vcpkg init @@ -698,10 +699,14 @@ target_link_libraries(eu07_settings INTERFACE Threads::Threads) find_package(GLM REQUIRED) target_include_directories(eu07_settings INTERFACE ${GLM_INCLUDE_DIR}) -# JSON lib -add_subdirectory(ref/json) +# JSON lib: the ref/json submodule by default, or an installed package (e.g. nlohmann-json3-dev, vcpkg nlohmann-json). +# Both give the nlohmann_json::nlohmann_json target; 3.9 is the first release with ordered_json, used by the unit tests. +if (USE_SYSTEM_JSON) + find_package(nlohmann_json 3.9 REQUIRED) +else() + add_subdirectory(ref/json) +endif() target_link_libraries(eu07_settings INTERFACE nlohmann_json::nlohmann_json) -target_include_directories(eu07_settings INTERFACE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) diff --git a/README.md b/README.md index 675026ccf..f0c7ac3cd 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms | `-DCMAKE_BUILD_TYPE=Release` | Release build | | `-DCMAKE_BUILD_TYPE=RelWithDebInfo` | Release build with debug symbols | | `-DWITH_BETTER_RENDERER=ON/OFF` | Enable/disable NVRHI-based renderer | +| `-DUSE_SYSTEM_JSON=ON/OFF` | Use an installed **nlohmann_json** 3.9 or newer (e.g. `nlohmann-json3-dev`, vcpkg `nlohmann-json`) instead of the `ref/json` submodule (default `OFF`) | | `-DPython3_ROOT_DIR=` | Root of the **Python 3.14** install on Windows (`python.exe`, `Lib`, `DLLs`) for embed/copy steps; on Linux, optional if CMake picks the wrong interpreter | > **Linux note:** `WITH_BETTER_RENDERER` uses DirectX 12 through NVRHI and is **not supported on Linux**. From 2f12768815c3258e08aa036ad5823eb557084e54 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:35:59 +0100 Subject: [PATCH 09/22] fix(timetable): the station of departure written in capitals is still a stop (#343) The first row of a timetable, which usually gives only the departure time, became a stop only when its name matched the relation's first station case-sensitively. Os33733 of linia_107_poludnie.scn writes ZAGORZ in the rows and Zagorz in the relation, so its driver counted Zagorz as passed at the start, left before its departure time and the train manager never gave the departure signal. The names are now compared regardless of case (timetable::starts_at in the core library). Tests: unit test of the rule; td.scn scenario cases with a timetable of the case's own (first row STACJA1, and Stacja1 as control) and the td.scn train started with its head 80 m past the W4 of Stacja1; the scenario runner can copy a timetable of the case into the game for the run. --- CMakeLists.txt | 1 + tests/scenarios/README.md | 15 ++++++- .../cases/eu07_td_departure_station.json | 35 +++++++++++++++++ .../eu07_td_departure_station_capitals.json | 35 +++++++++++++++++ .../cases/eu07_td_timetable_past_w4.json | 28 +++++++++++++ .../scenarios/cases/td_departure_station.scn | 9 +++++ .../scenarios/cases/td_departure_station.txt | 20 ++++++++++ .../cases/td_departure_station_capitals.txt | 20 ++++++++++ .../scenarios/cases/td_timetable_past_w4.scn | 9 +++++ tests/scenarios/run.py | 19 +++++++-- tests/unit/test_timetable_start.cpp | 39 +++++++++++++++++++ world/mtable.cpp | 5 ++- world/timetablestart.cpp | 25 ++++++++++++ world/timetablestart.h | 23 +++++++++++ 14 files changed, 277 insertions(+), 6 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_departure_station.json create mode 100644 tests/scenarios/cases/eu07_td_departure_station_capitals.json create mode 100644 tests/scenarios/cases/eu07_td_timetable_past_w4.json create mode 100644 tests/scenarios/cases/td_departure_station.scn create mode 100644 tests/scenarios/cases/td_departure_station.txt create mode 100644 tests/scenarios/cases/td_departure_station_capitals.txt create mode 100644 tests/scenarios/cases/td_timetable_past_w4.scn create mode 100644 tests/unit/test_timetable_start.cpp create mode 100644 world/timetablestart.cpp create mode 100644 world/timetablestart.h diff --git a/CMakeLists.txt b/CMakeLists.txt index cf1b137f7..75dbc5df5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -575,6 +575,7 @@ set(CORE_SOURCES "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"world/timetablestart.cpp" "vehicle/timetableservice.cpp" "world/timetableflags.cpp" "world/timetablereader.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index d8bdd160b..7e9ceef7c 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,7 +135,7 @@ Python 3.10+, no extra packages. Options: `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. The 19 cases +- `-j N` runs N cases at once. Each case prints its results when it is done. The 22 cases that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, 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 @@ -214,6 +214,7 @@ to `logs/`. | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | | `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). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | +| `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | | `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) | @@ -236,6 +237,18 @@ 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. +`eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about +35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): +its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation +says `Stacja1`, as in some timetables of the game (`Os33733` of linia_107_poludnie.scn starts at `ZAGORZ`). The +train has to stop there and leave at its departure time, 10:35, which the log shows as `as TEST24: at 10:35 next +Przystanek`; taking Stacja1 for a station it passes through, the driver logs `passed STACJA1` at once and leaves as +soon as the route is set at 10:34, and the train manager gives no departure signal. `eu07_td_departure_station` is the +same with the row written as in the relation. `eu07_td_timetable_past_w4` (fragment `td_timetable_past_w4.scn`) puts +the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 of Stacja1, on `tor1k`: the W4 stays +under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the +route begins at the last vehicle and keeps a W4 behind the head. + 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 diff --git a/tests/scenarios/cases/eu07_td_departure_station.json b/tests/scenarios/cases/eu07_td_departure_station.json new file mode 100644 index 000000000..eb97b708c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station.json @@ -0,0 +1,35 @@ +{ + "description": "Control for eu07_td_departure_station_capitals: the same timetable with the first row written as in the relation (Stacja1). The train stops at Stacja1 and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST25: at \\d+:\\d+ passed Stacja1" + }, + { + "type": "log_contains", + "pattern": "as TEST25: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station_capitals.json b/tests/scenarios/cases/eu07_td_departure_station_capitals.json new file mode 100644 index 000000000..cf1cbe2bd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station_capitals.json @@ -0,0 +1,35 @@ +{ + "description": "EU07 on td.scn on a timetable whose first row, the station of departure, is written in capitals (STACJA1) and gives no arrival time, while the relation says Stacja1. The train is to stop there and wait for its departure at 10:35, not take Stacja1 for a station it passes through and leave as soon as the route is set at 10:34 (linia_107_poludnie.scn, Os33733 at ZAGORZ).", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station_capitals.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST24: at \\d+:\\d+ passed STACJA1" + }, + { + "type": "log_contains", + "pattern": "as TEST24: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_timetable_past_w4.json b/tests/scenarios/cases/eu07_td_timetable_past_w4.json new file mode 100644 index 000000000..c60effbed --- /dev/null +++ b/tests/scenarios/cases/eu07_td_timetable_past_w4.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with three coaches on td.scn on the td/rozklad timetable, placed with its head 80 m past the W4 of Stacja1, the first station of the timetable, which stays under the consist. The driver counts Stacja1 as the stop it stands at and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_past_w4.scn", + "vars": { + "offset": 15, + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "as ROJ65113: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + } + ] +} diff --git a/tests/scenarios/cases/td_departure_station.scn b/tests/scenarios/cases/td_departure_station.scn new file mode 100644 index 000000000..b005516c4 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the same start as td_timetable.scn, the W4 of Stacja1 about 35 m ahead of the train, but on the case's own +// timetable: {{timetable}}, a copy of the case's "timetable" file, Stacja1 10:35 -> Przystanek -> Stacja2 whose +// first row gives no arrival time, only the departure. the route out of track 1 is set at 10:34 +trainset {{timetable}} tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_departure_station.txt b/tests/scenarios/cases/td_departure_station.txt new file mode 100644 index 000000000..cd4851228 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST25 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Stacja1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_departure_station_capitals.txt b/tests/scenarios/cases/td_departure_station_capitals.txt new file mode 100644 index 000000000..8d727d5d0 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station_capitals.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST24 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | STACJA1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_timetable_past_w4.scn b/tests/scenarios/cases/td_timetable_past_w4.scn new file mode 100644 index 000000000..e7e83d51b --- /dev/null +++ b/tests/scenarios/cases/td_timetable_past_w4.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad, Stacja1 10:35 -> Przystanek -> Stacja2) placed past the W4 of +// Stacja1 instead of before it: the head {{offset}} m into tor1k, the track after the one with the W4, which is +// left under the consist, behind the head. the route out of track 1 is set at 10:34 +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 438b68aa4..fd1941577 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -146,6 +146,15 @@ def scenery_cache(game_dir: Path, case_name: str) -> Path: return game_dir / "scenery" / f"autotest_{case_name}.sbt" +def timetable_name(case_name: str) -> str: + """The case's own timetable as a trainset names it: {{timetable}} in the fragment.""" + return f"autotest_{case_name}" + + +def timetable_path(game_dir: Path, case_name: str) -> Path: + return game_dir / "scenery" / f"{timetable_name(case_name)}.txt" + + 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" @@ -165,9 +174,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = text.replace(old, new) # a case on a mission of the base scenery may have nothing to add but its test_config fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" - # 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}) + # vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable"}) + fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name)}) # 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) @@ -185,6 +194,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text += header + trainsets + "\n" name = f"autotest_{case_name}.scn" (scenery_dir / name).write_bytes(text.encode("latin-1")) + # a timetable of the case's own, for a train whose timetable the sceneries of the game have none like + if "timetable" in case: + shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name)) # 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 @@ -838,6 +850,7 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float result = run_simulator(exe, game_dir, scenery, ini, physicslog, duration, float(case.get("timeout", 600)), watch, say, expect_rows=with_physicslog and not own_vehicle) + timetable_path(game_dir, name).unlink(missing_ok=True) # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): scenery_cache(game_dir, name).unlink(missing_ok=True) diff --git a/tests/unit/test_timetable_start.cpp b/tests/unit/test_timetable_start.cpp new file mode 100644 index 000000000..de00eba52 --- /dev/null +++ b/tests/unit/test_timetable_start.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "world/timetablestart.h" + +// the first row of a timetable is the station of departure, a stop the train waits at for its departure time, +// when it names the station the relation starts at. the loader then takes the departure time for the arrival +// one, which the row usually leaves out; a row without an arrival time is otherwise a station passed through + +TEST_CASE("timetable: the first row naming the station of the relation is the station of departure") { + CHECK(timetable::starts_at("Stacja1", "Stacja1")); + CHECK(timetable::starts_at("Zagorz", "Zagorz")); +} + +TEST_CASE("timetable: the station of departure written in capitals in the rows is still the one of the relation") { + // linia_107_poludnie.scn, Os33733: ZAGORZ in the rows, Zagorz in the relation (both with the polish letters + // stripped by the loader). taken for a station passed through, the AI left before its departure time and the + // train manager never gave the departure signal + CHECK(timetable::starts_at("ZAGORZ", "Zagorz")); + CHECK(timetable::starts_at("LEOSIN", "Leosin")); + CHECK(timetable::starts_at("Warszawa_Wschodnia", "WARSZAWA_WSCHODNIA")); +} + +TEST_CASE("timetable: a first row naming another station is not the station of departure") { + // a timetable which starts on the way, at a station the train passes through + CHECK_FALSE(timetable::starts_at("Tarnawa_Dolna", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Nowy_Zagorz", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Nowy_Zagorz")); + // a name which only begins like the other one + CHECK_FALSE(timetable::starts_at("Zagorz_Towarowy", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Zagorz_Towarowy")); +} + +TEST_CASE("timetable: the station names are compared as a whole, letters and the rest") { + CHECK_FALSE(timetable::starts_at("Stacja1", "Stacja2")); + CHECK_FALSE(timetable::starts_at("Stacja_1", "Stacja-1")); + CHECK_FALSE(timetable::starts_at("Stacja1", "")); + CHECK_FALSE(timetable::starts_at("", "Stacja1")); +} diff --git a/world/mtable.cpp b/world/mtable.cpp index 23a48e3a7..bef0e20d8 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/mtable.h" +#include "world/timetablestart.h" #include "utilities/Globals.h" #include "simulation/simulationtime.h" #include "utilities/dictionary.h" @@ -355,8 +356,8 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } } } - // jeśli nazwa pierwszego zgodna z relacją - if (conversionerror == 0 && TimeTable[1].StationName == Relation1 && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu + // jeśli nazwa pierwszego zgodna z relacją (bez względu na wielkość liter) + if (conversionerror == 0 && timetable::starts_at( TimeTable[1].StationName, Relation1 ) && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu { // to mamy zatrzymanie na pierwszym, a nie przelot TimeTable[1].Ah = TimeTable[1].Dh; TimeTable[1].Am = TimeTable[1].Dm; diff --git a/world/timetablestart.cpp b/world/timetablestart.cpp new file mode 100644 index 000000000..2ece9a71c --- /dev/null +++ b/world/timetablestart.cpp @@ -0,0 +1,25 @@ +/* +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 "world/timetablestart.h" + +#include +#include + +namespace timetable { + +bool starts_at(std::string_view const Firststation, std::string_view const Relationfrom) { + // the station names are plain ascii by now, the timetable loader strips the polish letters + return std::ranges::equal(Firststation, Relationfrom, [](char const Left, char const Right) { + return std::tolower(static_cast(Left)) == std::tolower(static_cast(Right)); + }); +} + +} // namespace timetable diff --git a/world/timetablestart.h b/world/timetablestart.h new file mode 100644 index 000000000..78e6f2c36 --- /dev/null +++ b/world/timetablestart.h @@ -0,0 +1,23 @@ +/* +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 + +// the first row of a timetable +namespace timetable { + +// whether the first row of a timetable is the station the train sets off from: it names the station +// the relation starts at. such a row is a stop even with no arrival time given, the train waits there +// for its departure time. the names are compared regardless of case, as the timetables write the +// station of departure in capitals as often as not (ZAGORZ in the rows, Zagorz in the relation) +bool starts_at(std::string_view Firststation, std::string_view Relationfrom); + +} // namespace timetable From e76ab8b5b37c9a36ceecbe243994f816f76bdb8c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 22 Nov 2026 09:55:09 +0100 Subject: [PATCH 10/22] Revert #408 and merge master into staging (unblocks #442) (#443) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64___noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07___noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named :, and its log went to physicslog/:.dat. On NTFS that isn't even an error: it is the stream .dat of the file , which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 * AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table since ce87aa0e (#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was before ce87aa0e and as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r * fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414) 623c4f82 (#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r * fix(particles): the smoke of a cold diesel keeps the colour of its template (#413) bcb9e644 (#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r * Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and since e230d7b9 it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r * fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r * fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1 d1f16411 (#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again; fa2ed089 swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as before d1f16411. The call added since (stepped_uc_value, 00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers and go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged is included twice, which is harmless. --------- Co-authored-by: maj00r * Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of 8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of 939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Since d13c27a7 (the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Before d13c27a7 the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from before d13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r * Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) * feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or :event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after _.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to _dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after _.scm, any included file named *_.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. _.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial : opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here… * fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), (...) Stack (addr2line -f -C -e ): to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude * fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number again ee3af0bf (#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416: ee3af0bf moved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r * revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r * Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)" This reverts commit d6c35935209a7e5b67c5a5030f660704ee91ca6f. --------- Co-authored-by: maj00r <73280030+maj00r@users.noreply.github.com> Co-authored-by: maj00r Co-authored-by: Claude Opus 5.5 Co-authored-by: Hirek193 Co-authored-by: pol102 --- CMakeLists.txt | 2 + EU07.cpp | 50 +++- McZapkie/Mover.cpp | 34 +-- application/application.cpp | 80 +++++- application/application.h | 1 + application/drivermode.cpp | 19 +- application/drivermode.h | 1 + application/editormode.cpp | 158 +++++++++- application/editormode.h | 48 +++- application/editormodelineside.cpp | 4 +- application/editormodeselftestswitch.cpp | 19 ++ application/editormodeswitchdrive.cpp | 261 +++++++++++++++-- application/editormodeswitchplace.cpp | 7 + application/editormodeswitchtemplate.cpp | 3 + application/editormodeswitchtool.cpp | 1 + application/editormodetrack.cpp | 18 +- application/scenarioloaderuilayer.cpp | 2 +- blackbox_doc.md | 16 +- editor/editorGeoMap.cpp | 8 +- editor/editorGeoMap.hpp | 2 + editor/editorHttp.cpp | 261 +++++++++++++---- editor/editorIncludeInfo.cpp | 65 +++++ editor/editorIncludeInfo.hpp | 7 + editor/editorOrthophoto.cpp | 163 +++++++++-- editor/editorOrthophoto.hpp | 27 +- editor/editorSettings.cpp | 15 + editor/editorSettings.hpp | 9 + editor/editorTerrainStreamer.cpp | 39 +++ editor/editorTerrainStreamer.hpp | 9 + global_include/interfaces/ITexture.h | 13 + lang/editor_pl.po | 66 +++++ model/AnimModel.cpp | 9 +- model/AnimModel.h | 1 + model/Texture.cpp | 119 +++++++- model/Texture.h | 27 ++ rendering/opengl33renderer.cpp | 4 +- rendering/openglparticles.cpp | 4 +- rendering/openglrenderer.cpp | 4 +- rendering/particles.cpp | 6 +- scripting/PyInt.cpp | 65 ++++- scripting/PyInt.h | 11 + scripting/pythonscreenviewer.cpp | 16 +- scripting/pythonscreenviewer.h | 4 + simulation/blackboxrecorder.cpp | 12 +- simulation/blackboxrecorder.h | 5 +- simulation/simulationenvironment.cpp | 9 +- simulation/simulationtest.cpp | 14 +- tests/unit/CMakeLists.txt | 2 + tests/unit/test_braking_curve.cpp | 195 +++++++++++++ tests/unit/test_crashsignals.cpp | 89 ++++++ tests/unit/test_editor_http.cpp | 138 +++++++++ tests/unit/test_physicslog.cpp | 145 ---------- tests/unit/test_track_uneven.cpp | 28 +- tests/unit/test_utilities.cpp | 81 +++++- tools/track_uneven_grade.py | 6 +- track_uneven_doc.md | 14 +- utilities/Globals.cpp | 7 + utilities/Globals.h | 10 + utilities/Logs.cpp | 3 + utilities/crashsignals.cpp | 234 +++++++++++++++ utilities/crashsignals.h | 25 ++ utilities/physicslog.cpp | 348 ++++------------------- utilities/physicslog.h | 119 +------- utilities/utilities.cpp | 4 +- utilities/utilities.h | 24 +- vehicle/Camera.cpp | 33 ++- vehicle/Driver.cpp | 187 +++++------- vehicle/Driver.h | 21 +- vehicle/DynObj.cpp | 50 +++- vehicle/DynObj.h | 5 + vehicle/Train.cpp | 13 +- vehicle/brakingcurve.cpp | 86 ++++++ vehicle/brakingcurve.h | 54 ++++ world/Segment.cpp | 9 +- world/TrackUneven.h | 21 +- 75 files changed, 2699 insertions(+), 970 deletions(-) create mode 100644 tests/unit/test_braking_curve.cpp create mode 100644 tests/unit/test_crashsignals.cpp create mode 100644 tests/unit/test_editor_http.cpp create mode 100644 utilities/crashsignals.cpp create mode 100644 utilities/crashsignals.h create mode 100644 vehicle/brakingcurve.cpp create mode 100644 vehicle/brakingcurve.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 75dbc5df5..294128b87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -556,6 +556,7 @@ set(CORE_SOURCES "scene/sn_utils.cpp" "scene/regionfile.cpp" "utilities/inionlysettings.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" @@ -568,6 +569,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/EU07.cpp b/EU07.cpp index a76564663..fa6bb15f2 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,9 +22,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -78,8 +82,12 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ExceptionPointers = ExceptionInfo; dumpInfo.ClientPointers = FALSE; - // Wybrana kombinacja flag - MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + // a small dump by default: the stacks with the memory they point to, the threads with their process and thread + // blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data + // (Global among them). all the memory of the simulator, as large as the memory it took, only with + // "crashdump.full yes" in eu07.ini + auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs}; + MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); // in test mode nobody is there to close the box, and the run would wait for it until killed @@ -113,7 +121,7 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); - // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + // the last two seconds of the physics logs, which the runner of the tests reads PhysicsLogs.stop(); finish_log(); fflush(stdout); @@ -172,9 +180,15 @@ int main(int argc, char *argv[]) SetUnhandledExceptionFilter(CrashHandler); #endif #endif + // on Linux, where no dump is written, the stack of a crash in the log and on the standard error + crash_signals::install(VERSION_INFO); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); + // a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it + // from a closing; how the simulator ends after a start that worked stays as it was + int exitcode{0}; + // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { @@ -221,34 +235,54 @@ int main(int argc, char *argv[]) } else { + // below 0 when the start failed (see eu07_application::init()) + int initresult{0}; try { - auto result{Application.init(argc, argv)}; - if (result == 0) + initresult = Application.init(argc, argv); + if (initresult == 0) { - result = Application.run(); + Application.run(); Application.exit(); } } + // an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the + // log and ends with an error code catch (std::bad_alloc const &Error) { ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what())); + exitcode = 1; } #ifdef _WIN32 catch (std::runtime_error const &Error) { + ErrorLog("Critical error: " + std::string(Error.what())); std::string msg = "Simulator crash occured :(\n"; msg += Error.what(); MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); + exitcode = 1; + } +#else + // elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on + // Windows it is left to CrashHandler, whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif - // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } #ifndef _WIN32 fflush(stdout); fflush(stderr); #endif - std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults + std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults } diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b4ba8478d..b1735d0c5 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -940,7 +940,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem PantPress = ScndPipePress; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = std::clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else @@ -952,7 +952,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } - PantPress = std::clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s @@ -4719,7 +4719,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not auto const initialstate{CompressorListPos}; - CompressorListPos = std::clamp(State, 0, CompressorListPosNo); + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); if (Notify != range_t::local) { @@ -6579,7 +6579,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; @@ -6955,7 +6955,7 @@ double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, doub if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -9089,7 +9089,9 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr { Progress = 0.0; } - return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); } } // namespace @@ -9203,18 +9205,18 @@ void TMoverParameters::EIMICFromFourPositions(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -9336,7 +9338,7 @@ void TMoverParameters::EIMICLimit() eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) @@ -9443,7 +9445,7 @@ void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -10451,7 +10453,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun } LoadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); ComputeMass(); return true; } @@ -10496,7 +10498,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam { // pusto lub rozładowano żądaną ilość LoadStatus = 4; // skończony rozładunek - LoadAmount = std::clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny } if (LoadAmount == 0.f) { @@ -14370,7 +14372,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); return OK; } @@ -14996,7 +14998,7 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/application/application.cpp b/application/application.cpp index 2a024bfd6..bc4b7dc1d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -54,6 +57,7 @@ http://mozilla.org/MPL/2.0/. #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "version.lib") +#include #endif #ifdef __unix__ @@ -65,6 +69,36 @@ eu07_application Application; screenshot_manager screenshot_man; ui_layer uilayerstaticinitializer; +namespace +{ +#ifdef _WIN32 +// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms. +// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up +// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or +// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the +// main loop, as it costs some power for as long as it's held +bool timer_period_set{false}; +#endif + +// asks for the finer timer once, when fpslimit is set +void begin_timer_period() +{ +#ifdef _WIN32 + if (!timer_period_set && Global.minframetime.count() > 0.f) + timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR); +#endif +} + +void end_timer_period() +{ +#ifdef _WIN32 + if (timer_period_set) + timeEndPeriod(1); + timer_period_set = false; +#endif +} +} // namespace + #ifdef _WIN32 extern "C" { @@ -140,6 +174,28 @@ void char_callback(GLFWwindow *window, unsigned int c) Application.on_char(c); } +namespace +{ + +// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no +// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context, +// is told once. glfw may call this from any thread that uses it +void glfw_error_callback(int const Code, char const *Description) +{ + auto message{std::format("GLFW error 0x{:08X}: {}", static_cast(Code), Description != nullptr ? Description : "(no description)")}; + + static std::mutex reportedmutex; + static std::set reported; + { + std::scoped_lock lock(reportedmutex); + if (false == reported.insert(message).second) + return; + } + ErrorLog(message); +} + +} // namespace + // public: void eu07_application::queue_screenshot() @@ -222,7 +278,8 @@ int eu07_application::run_crashgui() return 0; } } - return -1; + // the player closed the window: the simulator closes with it, as it always has, but that is no failed start + return 1; } #if WITH_DISCORD_RPC void eu07_application::DiscordRPCService() @@ -352,6 +409,8 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; } + // fpslimit is known now + begin_timer_period(); // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is @@ -407,7 +466,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { - ErrorLog("Failed to run crash gui!"); + // above 0 the player closed the window, which is no error + if (result < 0) + ErrorLog("Failed to run crash gui!"); + else + WriteLog("Crash report window closed, closing"); return result; } } @@ -474,6 +537,11 @@ int eu07_application::init(int Argc, char *Argv[]) if (!init_network()) return -1; + // glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the + // platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key + // codes of its launchers), every frame + glfwSetErrorCallback(nullptr); + return result; } @@ -690,6 +758,8 @@ int eu07_application::run() // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { + // fpslimit may come from the config block of the scenery, read after the settings + begin_timer_period(); std::this_thread::sleep_until(*nextframe); } } @@ -751,7 +821,7 @@ void eu07_application::exit() step("the black box"); simulation::Blackbox.close(); step("the physics logs"); - // what is kept of them, the black box's written last, waited for a second at most: the rest is dropped + // what is kept of them, the black box's written last PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) @@ -786,6 +856,7 @@ void eu07_application::exit() if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + end_timer_period(); step("done"); StopLogService(); auto it = Global.threads.find("LogService"); @@ -1359,6 +1430,9 @@ int eu07_application::init_locale() int eu07_application::init_glfw() { + // set before glfwInit(), so a failure of the start itself is told too + glfwSetErrorCallback(glfw_error_callback); + { int glfw_major, glfw_minor, glfw_rev; glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); diff --git a/application/application.h b/application/application.h index 850b66e1e..881d4f073 100644 --- a/application/application.h +++ b/application/application.h @@ -33,6 +33,7 @@ public: // constructors eu07_application() = default; // methods + // 0 when the simulator started, below 0 when its start failed, above 0 when the player closed it before it started int init( int Argc, char *Argv[] ); int diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 47ab3ae0c..b47a1d4df 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" + +#include + /* namespace input { @@ -627,6 +630,12 @@ bool driver_mode::is_command_processor() const return true; } +double driver_mode::shake_fraction() const +{ + // how far the simulation time has got from the last step of the shake towards the next one + return std::clamp(m_secondaryupdateaccumulator / m_secondaryupdaterate, 0.0, 1.0); +} + void driver_mode::update_camera(double const Deltatime) { @@ -775,7 +784,8 @@ void driver_mode::update_camera(double const Deltatime) // ale bez odbicia Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 } - auto const shakeangles{simulation::Train->Dynamic()->shake_angles()}; + auto const *dynamic{simulation::Train->Dynamic()}; + auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* @@ -796,8 +806,9 @@ void driver_mode::update_camera(double const Deltatime) } float const shakescale{FreeFlyModeFlag ? 5.0f : 1.0f}; - auto shakencamerapos{Camera.m_owneroffset + - shakescale * glm::vec3(1.5 * Camera.m_owner->ShakeState.offset.x, 2.0 * Camera.m_owner->ShakeState.offset.y, 1.5 * Camera.m_owner->ShakeState.offset.z)}; + // the shake steps at a fixed rate, the frames come at their own: taken at the frame's moment between the steps, it moves as smoothly as the vehicle + auto const shake{Camera.m_owner->shake_between(shake_fraction())}; + auto shakencamerapos{Camera.m_owneroffset + shakescale * glm::vec3(1.5 * shake.offset.x, 2.0 * shake.offset.y, 1.5 * shake.offset.z)}; Camera.Pos = Camera.m_owner->GetWorldPosition(FreeFlyModeFlag ? glm::dvec3(shakencamerapos) : // TODO: vehicle collision box for the external vehicle camera simulation::Train->clamp_inside(shakencamerapos)); @@ -805,7 +816,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index 7e86e99f6..7e5b48573 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -97,6 +97,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/application/editormode.cpp b/application/editormode.cpp index ab150cb7b..a40c6e081 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "application/editormode.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" @@ -600,6 +601,9 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); }); Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // with the heightmap terrain, a new tile waits while a chunk under it is still to come; where none is nor will be, or the walk of + // the chunks doesn't reach, it lies on the other ground or on the NMT guess as before. A scenery without it as before + Layer.coming_source([](glm::dvec2 const &Min, glm::dvec2 const &Max) { return EditorTerrain.active() && EditorTerrain.ground_coming(Min, Max); }); // the imagery often comes before the terrain made from the model: it lies where the terrain will be Layer.guess_source([this](double const X, double const Z, double &Height) { if (nmt_ground(X, Z, Height)) @@ -614,6 +618,8 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) editor_mode::~editor_mode() { editor_track::observe(nullptr); + // the capabilities of a WMS service being read are given up rather than waited for to their timeouts + m_wms_adding.closing = true; } std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const @@ -1412,6 +1418,15 @@ bool editor_mode::update() ui()->set_status(text, false); WriteLog("Editor: " + text, logtype::generic); } + // the drives left without their switches are told once, as the scenery is opened + if (auto const stray{stray_drives().size()}; stray > 0) + { + auto const text{format(STR_P("%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view", + "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view", static_cast(stray)), + stray)}; + ui()->set_notice(text); + WriteLog("Editor: " + text, logtype::generic); + } } } // after the tool has told its own status @@ -1652,6 +1667,7 @@ bool editor_mode::update() draw_build_overlay(); steps.step("laying drawn"); draw_blade_tips(); + draw_stray_drives(); draw_track_intent(); draw_tape(); steps.step("track drawn"); @@ -3309,7 +3325,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) return; } scene::Layers.removed(Instance, false == included.removed); - m_drives_standing.reset(); + drives_changed(); ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } @@ -3346,7 +3362,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } - m_drives_standing.reset(); + drives_changed(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -3391,7 +3407,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - m_drives_standing.reset(); + drives_changed(); std::string file; std::vector values; if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && @@ -4087,7 +4103,7 @@ void editor_mode::render_wms_adding() adding.info.reset(); adding.ticked.clear(); adding.service = url; - adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + adding.reading = std::async(std::launch::async, [url, closing = &adding.closing]() { return editor_orthophoto::describe(url, [closing]() { return closing->load(); }); }); } if (adding.reading.valid()) { @@ -4248,6 +4264,11 @@ void editor_mode::render_view_menu() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + if (ImGui::BeginMenu(STR_C("Camera speed"))) + { + render_camera_settings(); + ImGui::EndMenu(); + } ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); @@ -6979,6 +7000,8 @@ void editor_mode::enter() simulation::Blackbox.close(); // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen ui_layer::draw_cursor(m_draw_cursor); + apply_camera_settings(); + Global.EditorCameraOn = true; if (simulation::Region != nullptr) { @@ -7080,6 +7103,7 @@ void editor_mode::exit() track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there ui_layer::draw_cursor(false); + Global.EditorCameraOn = false; Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -7479,6 +7503,22 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in lay_switch_mode(); break; + case GLFW_KEY_GRAVE_ACCENT: + // ~ (left of 1): the orthophoto shown or hidden; with Ctrl what the camera sees downloaded before anything else + if (false == is_press(Action) || ImGui::GetIO().WantTextInput) + break; + if (Mods & GLFW_MOD_CONTROL) + { + orthophoto_hurry(); + break; + } + if (false == anyModifier) + { + m_orthophoto.enabled(false == m_orthophoto.enabled()); + ui()->set_status(m_orthophoto.enabled() ? STR("Orthophoto on (~)") : STR("Orthophoto off (~)")); + } + break; + case GLFW_KEY_BACKSPACE: // the switch being clicked off the view: the last point taken back if (m_switch_designer.open && m_switch_designer.picking) @@ -8084,3 +8124,113 @@ void editor_mode::render_top_tracks_choice(bool const Combo) if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); } + +void editor_mode::apply_camera_settings() +{ + auto const &camera{EditorSettings.camera()}; + Global.EditorCameraSpeed = camera.speed; + Global.EditorCameraFast = camera.fast; + Global.EditorCameraZoomed = camera.zoomed; +} + +void editor_mode::render_camera_settings() +{ + auto &camera{EditorSettings.camera()}; + auto changed{false}; + auto release{false}; + ImGui::PushItemWidth(180.0f * Global.ui_scale); + auto speed{static_cast(camera.speed)}; + if (ImGui::SliderFloat(STR_C("Speed of the camera"), &speed, 0.05f, 10.0f, "x %.2f", ImGuiSliderFlags_Logarithmic)) + { + camera.speed = speed; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was")); + auto fast{static_cast(camera.fast)}; + if (ImGui::SliderFloat(STR_C("Ctrl speeds it up"), &fast, 1.0f, 30.0f, "x %.1f", ImGuiSliderFlags_Logarithmic)) + { + camera.fast = fast; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was")); + ImGui::PopItemWidth(); + if (ImGui::Checkbox(STR_C("In the top view as fast as the view is zoomed"), &camera.zoomed)) + changed = release = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("As it was"))) + { + camera = {}; + changed = release = true; + } + if (changed) + apply_camera_settings(); + if (release) + EditorSettings.save(); +} + +void editor_mode::orthophoto_hurry() +{ + if (false == m_orthophoto.enabled()) + m_orthophoto.enabled(true); + // what the camera sees of the ground: rays through a grid over the screen to the level of the ground under the camera, or as far + // as the reach of the orthophoto along it where they don't come down to it (the sky) + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + auto const camera{GfxRenderer->Camera_Position()}; + // the level of the ground under the camera: the terrain, else the scenery; with neither the rays go as far as the reach + std::optional level; + // only a level below the camera: one above it (in a tunnel, or flown under the terrain) would put the hits behind it + if (double ground{0.0}; m_streamer.active() && m_streamer.height_at(camera.x, camera.z, ground) && ground < camera.y) + level = ground; + else if (std::vector found; Global.EditorOrtho == false) + { + auto const heights{ground_heights({camera}, true, &found)}; + if (false == found.empty() && found.front() != 0 && heights.front() < camera.y) + level = heights.front(); + } + double constexpr reach{2500.0}; + glm::dvec2 low{camera.x, camera.z}; + glm::dvec2 high{camera.x, camera.z}; + for (int j = 0; j <= 6; ++j) + for (int i = 0; i <= 6; ++i) + { + glm::vec2 const ndc{static_cast(i) / 3.0f - 1.0f, static_cast(j) / 3.0f - 1.0f}; + auto const point = [&inverse, &ndc](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + if (Global.EditorOrtho) + { + // the view straight down: the corners of the screen are where it reaches on the ground + auto const corner{camera + point(0.0f)}; // the view matrix is camera-relative + low = glm::min(low, glm::dvec2{corner.x, corner.z}); + high = glm::max(high, glm::dvec2{corner.x, corner.z}); + continue; + } + auto direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + continue; + direction = glm::normalize(direction); + glm::dvec2 flat{direction.x, direction.z}; + auto distance{reach}; + if (level && direction.y < -1e-6) + distance = std::min(reach, (camera.y - *level) / -direction.y * glm::length(flat)); + if (glm::length(flat) < 1e-6) + continue; + flat = glm::normalize(flat) * distance; + glm::dvec2 const hit{camera.x + flat.x, camera.z + flat.y}; + low = glm::min(low, hit); + high = glm::max(high, hit); + } + auto const count{m_orthophoto.hurry(low, high, camera)}; + ui()->set_status(count > 0 ? format(STR_C("Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)"), count) + : std::string{STR("Orthophoto: the view is all shown already (Ctrl+~)")}); +} diff --git a/application/editormode.h b/application/editormode.h index 81347c950..d25840e18 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -871,6 +872,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); + // View > Camera speed: the speed of the free camera, the Ctrl multiplier, in the top view as fast as it's zoomed; kept in the + // settings of the editor and handed to the camera + void render_camera_settings(); + void apply_camera_settings(); + // ~ (Ctrl): the orthophoto of what the camera sees downloaded before the rest, the ones which failed tried again at once + void orthophoto_hurry(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor void render_environment_window(); bool m_environment_open{false}; @@ -909,6 +916,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri { std::array url{}; std::array filter{}; + // the reading is given up: the editor goes. before the reading, so it outlives the future waiting for the reading to end + std::atomic closing{false}; std::future reading; std::optional info; std::string service; // the address the capabilities were read of @@ -2635,8 +2644,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri struct switch_drive { standing_template standing; - int family{-1}; - int index{0}; + int family{-1}; // -1: a drive not described for the editor, e.g. of Rainsted; it can be replaced, not turned over or moved + int index{-1}; }; std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches @@ -2656,10 +2665,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri void switch_drives_committed(std::vector const &Tracks); // the drives of the switches deleted go with them, in the step of the undo history the deletion made last void drives_deleted(std::vector const &Switches); + // the file of a drive not described for the editor throwing one of the switches, empty when there's none; also one the editor + // kept beside a drive described for it + std::string undescribed_drive(std::vector const &Switches); // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved std::size_t drives_to_blade_tips(); bool m_drives_checked{false}; + // the file of each variant of the drives scanned: its family and its index in the family + std::map, std::less<>> drive_variants() const; + // the switches a template of a drive throws, by what follows its first parameter in their names: "" for a variant described for the + // editor, and for any other template whose switch events throw the track named by its first parameter, as the drives of Rainsted do; + // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not + // described for the editor have no family (-1) + std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); + std::map, std::less<>> m_drive_templates; // read once for each file + // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events + // throw nothing + struct stray_drive + { + scene::instance_handle instance{0}; + std::vector switches; // the names of the switches it throws, as its include gives them + std::string name; // of the switches missing from them + std::string file; + glm::dvec3 location{0.0}; + }; + // all the drives standing in the scenery, read from the files once while no include comes or goes + struct drives_named + { + std::vector drives; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_named; + // the include of a drive or a template changed: what's kept of the drives standing is read again + void drives_changed(); + // the drives whose switch isn't in the scenery, checked against the tracks each time + std::vector stray_drives(bool Wait = false); + void render_stray_drives(); + void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; // places them in the active layer or the given one, as one step of the undo. returns: how many were placed std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index 1c2fc9e9c..8f4f5209c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -253,7 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) { - m_drives_standing.reset(); + drives_changed(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -341,7 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { - m_drives_standing.reset(); + drives_changed(); EditorSnapshot snap; for (auto const instance : Instances) { diff --git a/application/editormodeselftestswitch.cpp b/application/editormodeselftestswitch.cpp index 891ca6d68..b9c502d17 100644 --- a/application/editormodeselftestswitch.cpp +++ b/application/editormodeselftestswitch.cpp @@ -549,6 +549,25 @@ editor_mode::selftest_result editor_mode::selftest_switch(std::string const &com WriteLog("SELFTEST drives " + name + ": chosen " + (m_switch.drive >= 0 ? m_switch.drives[m_switch.drive].name : std::string{"none"}) + ", side " + std::to_string(m_switch.drive_side) + ", standing" + files + ", steps " + std::to_string(m_history.size())); return selftest_result::handled; } + if (command == "straydrives") + { + auto const stray{stray_drives(true)}; + std::string names; + for (auto const &drive : stray) + names += " " + drive.name + "(" + drive.file + ")"; + WriteLog(format("SELFTEST straydrives: %zu", stray.size()) + names); + return selftest_result::handled; + } + if (command == "drivewhose") + { + // the drive the editor tells for the switch: its file and family, -1 for one not described + std::string name; + words >> name; + auto *track{simulation::Paths.find(name)}; + auto const found{track != nullptr ? find_switch_drive(*track) : std::nullopt}; + WriteLog("SELFTEST drivewhose " + name + ": " + (found.has_value() ? found->standing.file + " family " + std::to_string(found->family) : std::string{"none"})); + return selftest_result::handled; + } if (command == "driveflip") { std::string name; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 3e0a67854..931350af1 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editormodeshared.h" +#include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" @@ -25,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "imgui/imgui.h" #include +#include #include #include #include @@ -44,6 +46,21 @@ std::string drive_file(std::string Text) return Text; } +// the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as +// they're written +TTrack *track_named(std::string const &Name) +{ + auto *track{simulation::Paths.find(Name)}; + return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); +} + +// a template by the name of its file, with no folder: told to the user, who picks the drives by their names +std::string file_name(std::string const &File) +{ + auto const slash{File.find_last_of('/')}; + return slash != std::string::npos ? File.substr(slash + 1) : File; +} + int drive_side(std::string const &Side) { if (Side == "left") @@ -168,7 +185,8 @@ void editor_mode::switch_drives_committed(std::vector const &Tracks) drives = switch_drives_standing(); auto const found{drives->find(drive_file(track->name()))}; auto const spot{editor_track::drive_spot_of(*track)}; - if (found == drives->end() || false == spot.has_value()) + // a drive not described for the editor has no parameters known to set it with, nor a height above the rail; it stays put + if (found == drives->end() || found->second.family < 0 || false == spot.has_value()) continue; auto const &drive{found->second.standing}; auto const &included{scene::Layers.instance(drive.instance)}; @@ -221,7 +239,15 @@ bool editor_mode::place_switch_drive(TTrack &Switch) item.track = Switch.name(); item.tilt = spot->tilt; if (auto const present{find_switch_drive(Switch)}) + { + // one not described for the editor is kept: it may set the speed over the switch or carry its ballast too + if (present->family < 0) + { + tool.status = format(STR_C("Switch %s keeps its drive %s, which isn't described for the editor"), Switch.name().c_str(), file_name(present->standing.file).c_str()); + return false; + } return replace_switch_drive(Switch, tool.drive, (present->index & 1) != (driveright ? 1 : 0)); + } std::string error; if (place_templates({item}, error) == 0) { @@ -255,22 +281,147 @@ std::map const &editor_mode::switch_driv return included.removed || included.dead; })) return kept->by_switch; + auto const variants{drive_variants()}; + kept.emplace(); + kept->frame = ImGui::GetFrameCount(); + kept->revision = tool.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + auto const variant{variants.find(standing.file)}; + auto const [family, index]{variant != variants.end() ? variant->second : std::pair{-1, -1}}; + // the drive of a double switch of Rainsted stands for each of its switches, a..d + for (auto const &suffix : drive_switches(standing.file, variants)) + { + // a drive described for the editor goes before one of Rainsted set to the same switch, which the editor kept beside it + auto const [entry, fresh]{kept->by_switch.try_emplace(drive_file(standing.values[0] + suffix), switch_drive{standing, family, index})}; + if (false == fresh && entry->second.family < 0 && family >= 0) + entry->second = switch_drive{standing, family, index}; + } + } + return kept->by_switch; +} + +std::vector const &editor_mode::drive_switches(std::string const &File, std::map, std::less<>> const &Variants) +{ + static std::vector const single{std::string{}}; + if (Variants.contains(File)) + return single; + auto const [found, fresh]{m_drive_templates.try_emplace(File)}; + if (fresh) + editor_includes::switched_tracks(File, found->second); + return found->second; +} + +std::map, std::less<>> editor_mode::drive_variants() const +{ + auto const &tool{m_switch}; std::map, std::less<>> variants; for (int family = 0; family < static_cast(tool.drives.size()); ++family) for (int index = 0; index < 4; ++index) if (false == tool.drives[family].files[index].empty()) variants[drive_file(tool.drives[family].files[index])] = {family, index}; - kept.emplace(); - kept->frame = ImGui::GetFrameCount(); - kept->revision = tool.drives_revision; - kept->instances = instances; - for (auto &standing : standing_templates([&](std::string const &File) { return variants.contains(File); })) + return variants; +} + +void editor_mode::drives_changed() +{ + m_drives_standing.reset(); + m_drives_named.reset(); +} + +std::vector editor_mode::stray_drives(bool const Wait) +{ + scan_switch_drives(Wait); + auto const instances{static_cast(scene::Layers.instance_count())}; + auto &kept{m_drives_named}; + if (false == kept.has_value() || kept->revision != m_switch.drives_revision || kept->instances != instances) { - auto const &[family, index]{variants[standing.file]}; - auto name{drive_file(standing.values[0])}; - kept->by_switch.try_emplace(std::move(name), switch_drive{std::move(standing), family, index}); + auto const variants{drive_variants()}; + kept.emplace(); + kept->revision = m_switch.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + stray_drive drive{standing.instance, {}, {}, standing.file, standing.location}; + for (auto const &suffix : drive_switches(standing.file, variants)) + drive.switches.push_back(standing.values[0] + suffix); + kept->drives.push_back(std::move(drive)); + } + } + // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its + // switches gone, while one stands it still throws it + std::vector stray; + for (auto const &drive : kept->drives) + { + auto const &included{scene::Layers.instance(drive.instance)}; + // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts + if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { + auto const *track{track_named(Name)}; + return track != nullptr && false == track->m_editorremoved; + })) + continue; + std::string missing; + for (auto const &name : drive.switches) + missing += (missing.empty() ? "" : ", ") + name; + stray.push_back(drive); + stray.back().name = std::move(missing); + } + return stray; +} + +void editor_mode::render_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + ImGui::PushID("straydrives"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.55f, 0.25f, 1.0f)); + auto const open{ImGui::TreeNode("##straydrives", STR_P("%zu drive with no switch", "%zu drives with no switch", static_cast(stray.size())), stray.size())}; + ImGui::PopStyleColor(); + item_tooltip("Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name"); + if (open) + { + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + auto const label{format("%s (%s, %.0f m)##%d", drive.name.c_str(), file_name(drive.file).c_str(), glm::length(drive.location - camera), static_cast(drive.instance))}; + if (ImGui::Selectable(label.c_str(), m_instance == drive.instance)) + { + select_include(drive.instance); + fly_to(drive.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 25.0); + } + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list +void editor_mode::draw_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + // the ones far off would only crowd the view of the whole line + auto constexpr range{3000.0}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + ImVec2 at; + if (glm::length(drive.location - camera) > range || false == projection.project(drive.location, at)) + continue; + auto const selected{m_instance == drive.instance}; + drawlist->AddCircleFilled(at, 8.0f, IM_COL32(0, 0, 0, 170)); + drawlist->AddCircle(at, 7.0f, selected ? overlay_color::selected : overlay_color::invalid, 0, 3.0f); + auto const text{format(STR_C("%s: no switch of this name"), drive.name.c_str())}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const corner{at.x + 12.0f, at.y - 0.5f * size.y}; + drawlist->AddRectFilled({corner.x - 3.0f, corner.y - 1.0f}, {corner.x + size.x + 3.0f, corner.y + size.y + 1.0f}, IM_COL32(0, 0, 0, 160), 3.0f); + drawlist->AddText(corner, selected ? overlay_color::selected : overlay_color::invalid, text.c_str()); } - return kept->by_switch; } void editor_mode::apply_switch_drive_choice(TTrack &Switch) @@ -280,7 +431,10 @@ void editor_mode::apply_switch_drive_choice(TTrack &Switch) place_switch_drive(Switch); return; } - if (auto const found{find_switch_drive(Switch)}; found.has_value() && remove_templates({found->standing.instance}) > 0) + auto const found{find_switch_drive(Switch)}; + if (found.has_value() && found->family < 0) + m_switch.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found->standing.file).c_str())); + else if (found.has_value() && remove_templates({found->standing.instance}) > 0) m_switch.status = format(STR_C("Switch %s without a drive now"), Switch.name().c_str()); } @@ -299,7 +453,15 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return false; } auto const &found{present->standing}; + // a drive not described for the editor, as one of a double switch, may set the speed over the switch or carry its ballast too: it's kept as it is + if (present->family < 0) + { + tool.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found.file).c_str())); + return false; + } auto const family{Family >= 0 ? Family : present->family}; + if (family >= static_cast(tool.drives.size())) + return false; auto const index{Flip ? present->index ^ 1 : present->index}; template_item item; item.file = tool.drives[family].files[index]; @@ -334,19 +496,82 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return true; } +std::string editor_mode::undescribed_drive(std::vector const &Switches) +{ + // the drives described for the editor read first: before they are, every drive would pass for one not described + scan_switch_drives(true); + std::vector names; + for (auto const *track : Switches) + if (track != nullptr) + names.push_back(drive_file(track->name())); + auto const variants{drive_variants()}; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == variants.contains(File) && false == drive_switches(File, variants).empty(); })) + { + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return std::find(names.begin(), names.end(), drive_file(standing.values[0] + Suffix)) != names.end(); })) + return file_name(standing.file); + } + return {}; +} + void editor_mode::drives_deleted(std::vector const &Switches) { if (m_history.empty()) return; + // the names of the switches deleted, as the game finds them; they're retired already + std::vector deleted; for (auto const *track : Switches) + if (track != nullptr && track->eType == tt_Switch) + deleted.push_back(drive_file(track->name())); + if (deleted.empty()) + return; + auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; + // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, + // still has the drive and the ballast, so it's looked for too + auto const stands = [](std::string const &Name) { + if (auto const *track{track_named(Name)}; track != nullptr) + return false == track->m_editorremoved; + auto const name{drive_file(Name)}; + auto const &tracks{simulation::Paths.sequence()}; + return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); + }; + auto const take_away = [&](scene::instance_handle const Instance) { + if (false == scene::Layers.removable(Instance)) + return; + scene::Layers.removed(Instance, true); + m_history.back().instances.push_back(Instance); + }; + auto const variants{drive_variants()}; + // each drive throwing a switch deleted, also one the editor kept beside a drive described for it; the drive of a double switch throws + // the others too, so it goes with the last of them + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) { - if (track == nullptr || track->eType != tt_Switch) + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return named(standing.values[0] + Suffix); }) && + std::none_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return stands(standing.values[0] + Suffix); })) + take_away(standing.instance); + } + // the sleepers and the ballast laid by a switch, named by it as its drive is: of a double switch by the name its switches have in + // common, a..d or _a.._d, so they go with the last of them + static std::array const parts{"", "a", "b", "c", "d", "_a", "_b", "_c", "_d"}; + std::map> beds; + for (auto const &standing : standing_templates([](std::string const &) { return true; })) + { + auto const &name{standing.values[0]}; + // named by a single switch, it's this switch's alone; a switch named a beside it may be another single one + if (named(name)) + { + if (stands(name)) + continue; + } + else if (std::none_of(parts.begin(), parts.end(), [&](char const *Part) { return named(name + Part); }) || + std::any_of(parts.begin(), parts.end(), [&](char const *Part) { return stands(name + Part); })) continue; - auto const found{find_switch_drive(*track)}; - if (false == found.has_value() || false == scene::Layers.removable(found->standing.instance) || scene::Layers.instance(found->standing.instance).removed) - continue; - scene::Layers.removed(found->standing.instance, true); - m_history.back().instances.push_back(found->standing.instance); + auto const [bed, fresh]{beds.try_emplace(standing.file)}; + if (fresh) + bed->second = drive_switches(standing.file, variants).empty() && editor_includes::switch_bed(standing.file); + if (bed->second) + take_away(standing.instance); } } @@ -359,7 +584,7 @@ std::size_t editor_mode::drives_to_blade_tips() { if (track == nullptr || track->m_editorremoved || track->eType != tt_Switch) continue; - if (auto const found{find_switch_drive(*track)}; found.has_value() && scene::Layers.removable(found->standing.instance)) + if (auto const found{find_switch_drive(*track)}; found.has_value() && found->family >= 0 && scene::Layers.removable(found->standing.instance)) { switches.push_back(track); before.emplace_back(found->standing.instance, scene::Layers.directive(found->standing.instance)); diff --git a/application/editormodeswitchplace.cpp b/application/editormodeswitchplace.cpp index b35ef8c48..82028a943 100644 --- a/application/editormodeswitchplace.cpp +++ b/application/editormodeswitchplace.cpp @@ -1609,6 +1609,13 @@ bool editor_mode::replace_double_slip(TTrack &Part, editor_track::switch_templat return false; } } + // a drive not described for the editor may set the speed or carry the ballast of the slip too: the editor can neither take it + // away nor move it to the switches laid anew, which get other names, so the slip is left as it is + if (auto const drive{undescribed_drive({switches.begin(), switches.end()})}; false == drive.empty()) + { + state.status = refused(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); + return false; + } struct end { TTrack *track; diff --git a/application/editormodeswitchtemplate.cpp b/application/editormodeswitchtemplate.cpp index e6a8496bd..6edef6a65 100644 --- a/application/editormodeswitchtemplate.cpp +++ b/application/editormodeswitchtemplate.cpp @@ -286,6 +286,9 @@ bool editor_mode::change_slip_template(TTrack &Part, int const Index) for (auto const *part : parts) if (false == part->Dynamics.empty()) return fail(STR_C("The slip can't be laid again while vehicles stand on it")); + // its drives go with it and the new one gets its own: a drive not described for the editor can't be told apart from them + if (auto const drive{slip.has_value() ? undescribed_drive(slip->switches) : std::string{}}; false == drive.empty()) + return fail(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); // a single slip laid again joins the pair of the tracks it joined: the point given by them auto const &ends{slip.has_value() ? slip->ends : std::array{}}; auto const pair{slip.has_value() && record.type == "Rkp" ? 0.5 * (ends[0] + ends[3]) : glm::dvec3{0.0}}; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index a37c98f70..878e18aa3 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -282,6 +282,7 @@ void editor_mode::render_switch_ui() ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", tool.status.c_str()); ImGui::PopTextWrapPos(); } + render_stray_drives(); if (ImGui::Button(STR_C("Template editor..."))) m_switch_designer.open = true; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 91bf9c027..6e0fe60c7 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1171,22 +1171,34 @@ void editor_mode::render_turnout_ui() { auto const family{drive->family}; auto const variant{drive->index}; + // a drive not described for the editor is shown by its file + auto const described{family >= 0 && family < static_cast(m_switch.drives.size())}; + auto const &file{drive->standing.file}; + auto const shown{described ? m_switch.drives[family].name : format("%s (%s)", file.substr(file.find_last_of('/') + 1).c_str(), STR_C("not described"))}; if (begin_fields("##standingdrive", 0.3f)) { field_row("Drive##standing"); - if (ImGui::BeginCombo("##standing", m_switch.drives[family].name.c_str())) + if (false == described) + ImGui::TextUnformatted(shown.c_str()); + else if (ImGui::BeginCombo("##standing", shown.c_str())) { for (int i = 0; i < static_cast(m_switch.drives.size()); ++i) if (ImGui::Selectable(m_switch.drives[i].name.c_str(), family == i) && i != family) replace_switch_drive(Switch, i, false); ImGui::EndCombo(); } - if (ImGui::IsItemHovered()) + if (described && ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", STR_C("Puts another drive in place of the drive of this switch, on the same side"), format(STR_C("Drive: events %s+ and %s- switch it, also in the map"), Switch.name().c_str(), Switch.name().c_str()).c_str()); ImGui::EndTable(); } int side{((variant >> 1) == (variant & 1)) ? 0 : 1}; - if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, + if (false == described) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted")); + ImGui::PopTextWrapPos(); + } + else if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, {1, STR_C("other side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}})) flip_switch_drive(Switch); } diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 207a1756e..87366757f 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -88,7 +88,7 @@ std::vector scenarioloader_ui::get_random_trivia() json triviaData = json::parse(fileContent); // select random - int i = Random(0, static_cast(triviaData.size()) - 1); + int i = RandomInt(0, static_cast(triviaData.size()) - 1); std::string triviaStr = triviaData[i]["text"]; std::string background = triviaData[i]["background"]; if (triviaData[i].contains("scenery")) diff --git a/blackbox_doc.md b/blackbox_doc.md index 126cea033..9314b94e6 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -9,9 +9,8 @@ starter, a viewer) can replay the session on the map, or set the user's driving `blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no `blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. -The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are -hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail -vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +The latter writes the `.dat` logs of the trains only: of each driver who drives rail vehicles, not of the +passengers nor of the vehicles of the roads, so a big scenery gives far fewer of them. It is never written in an editor session. The file goes to `physicslog/_.blackbox` (the local time the recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. @@ -27,17 +26,10 @@ goes on in that driver's log, begun then if it is the first time. Back with a dr the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of the driver of its train. So the speed recorder's tape can be read from them as before, also while the simulator runs, without a log of every vehicle. A driver who writes a log of its own, with -`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the -user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the -user drives has no log. Like those of `physicslog yes`, they are written every +`physicslog.trains yes`, isn't written twice. Like those of `physicslog yes`, they are written every two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds -of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +of real time of them (at a higher time speed, more of the simulated time). A file another program holds for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. -The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of -those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as -long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. -Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, -and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no diff --git a/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index ab7f74b24..68b153559 100644 --- a/editor/editorGeoMap.cpp +++ b/editor/editorGeoMap.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorGeoMap.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorHttp.hpp" #include "editor/editorOrthophoto.hpp" #include "utilities/translation.h" @@ -164,6 +165,8 @@ bool parse_place(std::string const &Text, glm::dvec2 &Point) editor_map::~editor_map() { + // the download running is broken off rather than waited for to its end or its timeout + m_closing = true; if (m_request.valid()) m_request.wait(); release(); @@ -328,12 +331,13 @@ void editor_map::request(glm::vec2 const &Size) char bbox[160]; std::snprintf(bbox, sizeof(bbox), "%.1f,%.1f,%.1f,%.1f", low.x, low.y, high.x, high.y); auto const url{kMapService + "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=osm&STYLES=&SRS=EPSG:2180&BBOX=" + bbox + "&WIDTH=" + std::to_string(width) + "&HEIGHT=" + std::to_string(height) + "&FORMAT=image/png"}; - m_request = std::async(std::launch::async, [url, low, high]() { + m_request = std::async(std::launch::async, [url, low, high, closing = &m_closing]() { image result; result.low = low; result.high = high; std::vector data; - if (false == editor_http_get(url, data, result.error)) + thread_local editor_http::client client; + if (false == client.get(url, data, result.error, [closing]() { return closing->load(); })) return result; int w{0}, h{0}, components{0}; // the texture loader turns the stb flip on for the whole process only once it loads its first texture: this thread diff --git a/editor/editorGeoMap.hpp b/editor/editorGeoMap.hpp index 5c160095b..a1dd07124 100644 --- a/editor/editorGeoMap.hpp +++ b/editor/editorGeoMap.hpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -86,6 +87,7 @@ class editor_map glm::vec2 m_pressed{0.f}; bool m_dragging{false}; std::future m_request; + std::atomic m_closing{false}; // the download of the map is given up: the map goes std::uint64_t m_texture{0}; glm::dvec2 m_image_low{0.0}; glm::dvec2 m_image_high{0.0}; diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 81a195aeb..cbda581f0 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -45,15 +45,209 @@ struct client::platform #if defined(_WIN32) +namespace +{ + +DWORD constexpr kStopCheck{50}; // ms between the looks at whether the transfer is to be given up + +// what the callback of WinHTTP hands over to the thread waiting for it +struct transfer_state +{ + HANDLE done{::CreateEventW(nullptr, FALSE, FALSE, nullptr)}; // the operation begun finished or failed + HANDLE closed{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; // the request is called back no more + DWORD error{ERROR_SUCCESS}; // of the operation that failed + DWORD size{0}; // bytes available or read + + transfer_state() = default; + transfer_state(transfer_state const &) = delete; + transfer_state &operator=(transfer_state const &) = delete; + ~transfer_state() + { + if (done != nullptr) + ::CloseHandle(done); + if (closed != nullptr) + ::CloseHandle(closed); + } +}; + +void CALLBACK on_status(HINTERNET, DWORD_PTR const Context, DWORD const Status, LPVOID const Info, DWORD const Length) +{ + auto *state{reinterpret_cast(Context)}; + if (state == nullptr) + return; + switch (Status) + { + case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: + case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: + break; + case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: + state->size = *static_cast(Info); + break; + case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: + state->size = Length; + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + state->error = static_cast(Info)->dwError; + break; + case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: + ::SetEvent(state->closed); + return; + default: + return; + } + ::SetEvent(state->done); +} + +// one GET on a connection of its own. the steps of WinHTTP are asynchronous and waited for while the stop is looked at, so a +// transfer is given up at once also while a service keeps the connection waiting: the closing of the editor doesn't wait for +// the timeouts of a service that doesn't answer +class transfer +{ + public: + transfer(stop_check const &Stop, std::string &Error) : + m_stop(Stop), + m_error(Error) + { + } + ~transfer() + { + close(); + } + transfer(transfer const &) = delete; + transfer &operator=(transfer const &) = delete; + + bool open(HINTERNET const Session, std::wstring const &Host, INTERNET_PORT const Port, std::wstring const &Path, bool const Secure) + { + if (m_state.done == nullptr || m_state.closed == nullptr) + return failed(::GetLastError()); + m_connection = ::WinHttpConnect(Session, Host.c_str(), Port, 0); + if (m_connection == nullptr) + return failed(::GetLastError()); + m_request = ::WinHttpOpenRequest(m_connection, L"GET", Path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, Secure ? WINHTTP_FLAG_SECURE : 0); + if (m_request == nullptr) + return failed(::GetLastError()); + auto context{reinterpret_cast(&m_state)}; + if (false == ::WinHttpSetOption(m_request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context))) + return failed(::GetLastError()); + if (::WinHttpSetStatusCallback(m_request, on_status, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, 0) == WINHTTP_INVALID_STATUS_CALLBACK) + return failed(::GetLastError()); + m_called_back = true; + return true; + } + + bool send() + { + return step([this]() { return ::WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast(&m_state)); }); + } + + bool receive() + { + return step([this]() { return ::WinHttpReceiveResponse(m_request, nullptr); }); + } + + DWORD status() const + { + DWORD status{0}; + DWORD size{sizeof(status)}; + ::WinHttpQueryHeaders(m_request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + return status; + } + + // the whole body of the response + bool read_all(std::vector &Out) + { + while (true) + { + if (m_stop()) + { + m_error = "cancelled"; + return false; + } + if (false == step([this]() { return ::WinHttpQueryDataAvailable(m_request, nullptr); })) + return false; + auto const available{m_state.size}; + if (available == 0) + return true; + if (Out.size() + available > kLargest) + { + m_error = kTooLarge; + Out.clear(); + return false; + } + auto const offset{Out.size()}; + Out.resize(offset + available); + auto const read{step([this, &Out, offset, available]() { return ::WinHttpReadData(m_request, Out.data() + offset, available, nullptr); })}; + Out.resize(offset + (read ? m_state.size : 0)); + if (false == read) + return false; + } + } + + void close() + { + if (m_request != nullptr) + { + ::WinHttpCloseHandle(m_request); + m_request = nullptr; + // the closing is the last callback: after it the state, and the buffer of a read broken off, are no longer written to + if (m_called_back) + ::WaitForSingleObject(m_state.closed, INFINITE); + m_called_back = false; + } + if (m_connection != nullptr) + { + ::WinHttpCloseHandle(m_connection); + m_connection = nullptr; + } + } + + private: + bool failed(DWORD const Code) + { + m_error = "WinHTTP error " + std::to_string(Code); + return false; + } + + // begins an operation and waits for it: false when it failed, or a stop was asked for meanwhile + template bool step(Begin const &Operation) + { + m_state.error = ERROR_SUCCESS; + if (false == Operation()) + return failed(::GetLastError()); + while (::WaitForSingleObject(m_state.done, kStopCheck) != WAIT_OBJECT_0) + { + if (m_stop()) + { + // closed at once: the operation broken off doesn't write into the buffer any more once this returns + close(); + m_error = "cancelled"; + return false; + } + } + if (m_state.error != ERROR_SUCCESS) + return failed(m_state.error); + return true; + } + + stop_check const &m_stop; + std::string &m_error; + transfer_state m_state; + HINTERNET m_connection{nullptr}; + HINTERNET m_request{nullptr}; + bool m_called_back{false}; // the closing of the request is called back +}; + +} // namespace + client::client() : m_platform(std::make_unique()) { wchar_t const *agent = L"MaSzyna-editor"; #ifdef WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); #endif if (m_platform->session == nullptr) // automatic proxy needs windows 8.1+ - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (m_platform->session != nullptr) ::WinHttpSetTimeouts(m_platform->session, 10000, 10000, 15000, 20000); } @@ -94,64 +288,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st std::wstring const host(parts.lpszHostName, parts.dwHostNameLength); std::wstring const path = std::wstring(parts.lpszUrlPath, parts.dwUrlPathLength) + std::wstring(parts.lpszExtraInfo, parts.dwExtraInfoLength); - HINTERNET connection = ::WinHttpConnect(m_platform->session, host.c_str(), parts.nPort, 0); - HINTERNET request = connection ? ::WinHttpOpenRequest(connection, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) - : nullptr; - auto const close = [&]() { - if (request != nullptr) - ::WinHttpCloseHandle(request); - if (connection != nullptr) - ::WinHttpCloseHandle(connection); - }; - - if (request == nullptr || !::WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || !::WinHttpReceiveResponse(request, nullptr)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); + transfer request{Stop, Error}; + if (false == request.open(m_platform->session, host, parts.nPort, path, parts.nScheme == INTERNET_SCHEME_HTTPS) || false == request.send() || false == request.receive()) return false; - } - - DWORD status{0}; - DWORD statussize{sizeof(status)}; - ::WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statussize, WINHTTP_NO_HEADER_INDEX); - - for (;;) - { - if (Stop()) - { - Error = "cancelled"; - close(); - return false; - } - DWORD available{0}; - if (!::WinHttpQueryDataAvailable(request, &available)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - if (available == 0) - break; - if (Out.size() + available > kLargest) - { - Error = kTooLarge; - close(); - Out.clear(); - return false; - } - std::size_t const offset = Out.size(); - Out.resize(offset + available); - DWORD received{0}; - if (!::WinHttpReadData(request, Out.data() + offset, available, &received)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - Out.resize(offset + received); - } - close(); + auto const status{request.status()}; + if (false == request.read_all(Out)) + return false; + request.close(); if (status != 200) { diff --git a/editor/editorIncludeInfo.cpp b/editor/editorIncludeInfo.cpp index ca532f1ce..450cde5a2 100644 --- a/editor/editorIncludeInfo.cpp +++ b/editor/editorIncludeInfo.cpp @@ -548,6 +548,71 @@ bool event_names(std::string const &File, std::vector &Names) return true; } +bool switched_tracks(std::string const &File, std::vector &Suffixes) +{ + Suffixes.clear(); + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + // event switch + auto const tokens{tokenize(text.content)}; + std::string const first{"(p1)"}; + // a drive has the events thrown by the keys and the map, (p1)+ and (p1)-, or moves a model, lights its lamps or throws a double switch at + // once; the sleepers or the ballast of a switch may throw it on their own events too, with nothing else, but they don't drive it + bool driven{false}; + for (std::size_t idx = 0; idx + 2 < tokens.size() && false == driven; ++idx) + { + if (tokens[idx] != "event") + { + continue; + } + auto const &name{tokens[idx + 1]}; + auto const &kind{tokens[idx + 2]}; + driven = (name.size() > first.size() && name.compare(0, first.size(), first) == 0 && (name.back() == '+' || name.back() == '-')) || (kind != "switch" && kind != "trackvel"); + } + if (false == driven) + { + return true; + } + for (std::size_t idx = 0; idx + 4 < tokens.size(); ++idx) + { + if (tokens[idx] != "event" || tokens[idx + 2] != "switch" || tokens[idx + 4].compare(0, first.size(), first) != 0) + { + continue; + } + auto suffix{tokens[idx + 4].substr(first.size())}; + if (std::find(Suffixes.begin(), Suffixes.end(), suffix) == Suffixes.end()) + { + Suffixes.push_back(std::move(suffix)); + } + } + return true; +} + +bool switch_bed(std::string const &File) +{ + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + auto const tokens{tokenize(text.content)}; + for (std::size_t idx = 0; idx < tokens.size(); ++idx) + { + // node track ... + if (tokens[idx] == "include" || (tokens[idx] == "node" && idx + 4 < tokens.size() && tokens[idx + 4] == "track") || + (tokens[idx] == "event" && idx + 2 < tokens.size() && tokens[idx + 2] != "switch" && tokens[idx + 2] != "trackvel")) + { + return false; + } + } + return true; +} + bool signal_speeds(std::string const &File, std::vector &Speeds) { Speeds.clear(); diff --git a/editor/editorIncludeInfo.hpp b/editor/editorIncludeInfo.hpp index 7a2da9dfa..96b84b44a 100644 --- a/editor/editorIncludeInfo.hpp +++ b/editor/editorIncludeInfo.hpp @@ -90,6 +90,13 @@ int parameter_count(std::string const &File); bool signal_speeds(std::string const &File, std::vector &Speeds); // the names of the events the template defines, as they're written after "event", lower case. returns: false if the file can't be read bool event_names(std::string const &File, std::vector &Names); +// the tracks the switch events of the template throw, named by its first parameter: what follows (p1) in their names, lower case, "" +// for the track named (p1) itself, "a" for (p1)a of a double switch; none for the sleepers or the ballast of a switch, whose events only +// throw it or set its speed, with no (p1)+ or (p1)-. returns: false if the file can't be read +bool switched_tracks(std::string const &File, std::vector &Suffixes); +// true if the template can be the sleepers or the ballast of a switch: it puts no track, includes nothing and has no events but those +// throwing a switch or setting its speed. false if the file can't be read +bool switch_bed(std::string const &File); // the aspects of a block signal of the template: 4 where its events give S3, the green light flashing with the next signal at S5, // the warning two signals ahead, else 3. returns: 0 if the file can't be read int block_aspects(std::string const &File); diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index f663dd012..d3254a2c1 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -63,12 +63,6 @@ double steady_seconds() } // namespace -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error) -{ - thread_local http_client client; - return client.get(Url, Out, Error, []() { return false; }); -} - namespace { @@ -688,7 +682,7 @@ std::string xml_element(std::string const &Xml, std::string const &Tag, std::siz } // namespace -editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service) +editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service, std::function const &Stop) { service_info info; auto url{Service}; @@ -700,8 +694,10 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S // a few tries, the services drop connections and time out now and then std::vector data; auto read{false}; - for (int attempt = 0; attempt < 3 && false == read; ++attempt) - read = editor_http_get(url, data, info.error); + stop_check const stopping{Stop ? Stop : stop_check{[]() { return false; }}}; + thread_local http_client client; + for (int attempt = 0; attempt < 3 && false == read && false == stopping(); ++attempt) + read = client.get(url, data, info.error, stopping); if (false == read) return info; info.error.clear(); @@ -937,23 +933,47 @@ void editor_orthophoto::ground_arrived() { if (!m_height) return; - for (auto &entry : m_tiles) + for (auto &[key, t] : m_tiles) { - auto &t{entry.second}; - if (!t.grounded || !t.guessed) - continue; - // the middle and the corners: a chunk of the terrain is much larger than a tile, it covers some of these when it comes. A tile - // lying flat, with nothing to go by, also goes onto the model once it's in - glm::dvec2 const corner = tile_corner(entry.first); - for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) - if (double y; m_height(corner.x - u * tile_size, corner.y - v * tile_size, y) || (t.heights.empty() && m_guess && m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y))) - { - t.grounded = false; - break; - } + if (t.grounded && ground_came(key, t)) + t.grounded = false; } } +bool editor_orthophoto::waits_for_ground(tile_key const &Key) const +{ + // a tile laid out already stays, sampled again when its ground comes (ground_came) + if (!m_coming || m_tiles.contains(Key)) + return false; + glm::dvec2 const corner = tile_corner(Key); + return m_coming(corner - glm::dvec2{tile_size}, corner); +} + +bool editor_orthophoto::ground_came(tile_key const &Key, tile const &Tile) const +{ + glm::dvec2 const corner = tile_corner(Key); + // a tile lying flat, with nothing to go by, also goes onto the model once it's in: the middle and the corners + if (Tile.guessed && Tile.heights.empty() && m_guess) + for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) + if (double y; m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y)) + return true; + // the points the ground didn't answer, every second one of the grid (16 m) and the edges: a chunk of the terrain is about as + // large as a tile and comes over a part of it, often a band along a side; partly answered tiles count too, not only the guessed + static_assert(ground_grid % 2 == 0, "the edges of the grid are among its even points"); + int constexpr samples{ground_grid + 1}; + double constexpr step{tile_size / ground_grid}; + for (auto const index : Tile.unanswered) + { + int const i{index % samples}; + int const j{index / samples}; + if (i % 2 != 0 || j % 2 != 0) + continue; + if (double y; m_height(corner.x - i * step, corner.y - j * step, y)) + return true; + } + return false; +} + void editor_orthophoto::detach_scene() { for (auto &entry : m_tiles) @@ -1032,6 +1052,20 @@ editor_orthophoto::statistics editor_orthophoto::stats() const return out; } +int editor_orthophoto::first_level(tile const &Tile, int const Level) +{ + // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow + // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk + if (Level > standard_pixels && Tile.level < standard_pixels) + return standard_pixels; + return Level; +} + +bool editor_orthophoto::outside_area(tile_key const &Key) const +{ + return false == m_area.empty() && 0 == m_area_tiles.count(Key); +} + int editor_orthophoto::level_for(int Distance, bool Hires) { // coarser imagery further away keeps the memory use of large radii in check @@ -1233,6 +1267,7 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) Tile.scene_dirty = true; Tile.heights.clear(); Tile.surface.clear(); + Tile.unanswered.clear(); glm::dvec2 const corner = tile_corner(Key); glm::dvec2 const min(corner.x - tile_size, corner.y - tile_size); @@ -1304,6 +1339,21 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) } } + // the points the ground didn't answer: the ground coming there later (the terrain loaded after the imagery, which comes from the + // disk cache at once) has the tile sampled again, rather than left at the heights filled in or guessed now + Tile.unanswered.clear(); + auto const columns{static_cast(samples)}; + for (std::size_t index = 0; index < heights.size(); ++index) + { + if (heights[index] != no_height) + continue; + // in the scene the heights come from the triangles, and a steep spot (a wall, a quarry face) gives none: where the heightmap + // terrain answers the point, its ground is there already, and ground_came() would find it again on every chunk that comes + if (double y; surface && m_height && m_height(corner.x - static_cast(index % columns) * step, corner.y - static_cast(index / columns) * step, y)) + continue; + Tile.unanswered.push_back(static_cast(index)); + } + // holes (places without ground) take the average of their neighbours, spreading inwards std::size_t missing = std::count(heights.begin(), heights.end(), no_height); if (missing == heights.size()) @@ -1630,7 +1680,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) { tile_key const key{centre.first + dx, centre.second + dy}; // outside the download area: nothing asked for, nothing shown - if (false == m_area.empty() && 0 == m_area_tiles.count(key)) + if (outside_area(key)) { if (auto const found{m_tiles.find(key)}; found != m_tiles.end()) { @@ -1639,14 +1689,12 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) } continue; } + if (waits_for_ground(key)) + continue; tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; - int level = level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires); - // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow - // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk - if (level > standard_pixels && t.level < standard_pixels) - level = standard_pixels; + int const level = first_level(t, level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires)); if (t.empty || (t.level == level && t.alpha == m_alpha) || (t.requested == level && t.requested_alpha == m_alpha) || now < t.retry_at) continue; schedule(key, t, level, m_alpha); @@ -1713,7 +1761,8 @@ void editor_orthophoto::worker() continue; long long const dx = it->key.first - m_focus.first; long long const dy = it->key.second - m_focus.second; - long long const d = dx * dx + dy * dy; + // the tiles hurried (Ctrl+~) before all the others, the nearest of them first + long long const d = dx * dx + dy * dy - (m_urgent.count(it->key) > 0 ? (1LL << 40) : 0LL); if (d < bestdistance) { bestdistance = d; @@ -1730,6 +1779,7 @@ void editor_orthophoto::worker() { current = *best; m_queue.erase(best); + m_urgent.erase(current.key); m_running.insert(current.key); if (current.level >= hires_pixels) ++m_running_hires; @@ -1957,3 +2007,58 @@ void editor_orthophoto::draw(glm::mat4 const &ViewProjection, glm::dvec3 const & drawlist->PopTextureID(); } } + +bool editor_orthophoto::hurry_tile(tile_key const &Key, int const Distance) +{ + // as update() does: nothing asked for outside the download area, nor outside the area the service covers, where the requests + // can't be answered + if (outside_area(Key)) + return false; + auto &t{m_tiles[Key]}; + if (false == in_service_area(Key.first, Key.second)) + t.empty = true; + if (t.empty) + return false; + auto const level{first_level(t, level_for(Distance, m_config.hires))}; + t.retry_at = 0.0; + if (t.level == level && t.alpha == m_alpha) + return false; // already shown as it should be + if (false == (t.requested == level && t.requested_alpha == m_alpha)) + schedule(Key, t, level, m_alpha); + return true; +} + +std::size_t editor_orthophoto::hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera) +{ + if (false == m_enabled) + return 0; + // the tile of the camera as it is now: it isn't followed while the layer is off + m_camera_tile = camera_tile(Camera); + { + std::lock_guard lock(m_mutex); + m_focus = m_camera_tile; + } + auto const a{camera_tile(glm::dvec3{Min.x, 0.0, Min.y})}; + auto const b{camera_tile(glm::dvec3{Max.x, 0.0, Max.y})}; + tile_key const first{std::min(a.first, b.first), std::min(a.second, b.second)}; + tile_key const last{std::max(a.first, b.first), std::max(a.second, b.second)}; + auto const centre{m_camera_tile}; + int const radius = m_config.radius; + std::vector keys; + for (int y = first.second; y <= last.second; ++y) + for (int x = first.first; x <= last.first; ++x) + { + tile_key const key{x, y}; + auto const distance{std::max(std::abs(x - centre.first), std::abs(y - centre.second))}; + if (distance <= radius && hurry_tile(key, distance)) + keys.push_back(key); + } + auto const count{keys.size()}; + { + std::lock_guard lock(m_mutex); + m_urgent.clear(); + m_urgent.insert(keys.begin(), keys.end()); + } + m_wakeup.notify_all(); + return count; +} diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index d6fd43f8d..b56052e7e 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -28,8 +28,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" // material_handle #include "rendering/geometrybank.h" // gfx::geometry_handle -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error); - namespace scene { class basic_region; @@ -102,6 +100,9 @@ class editor_orthophoto editor_orthophoto(editor_orthophoto const &) = delete; editor_orthophoto &operator=(editor_orthophoto const &) = delete; + // the tiles over a rectangle of the world (x, z; what the camera sees), within the reach around the camera, asked for before anything + // else, the ones which failed tried again at once. returns: how many were put at the front of the queue + std::size_t hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera); bool enabled() const { return m_enabled; } // disabling drops the queue and returns the gpu memory of the resident tiles void enabled(bool State); @@ -117,6 +118,10 @@ class editor_orthophoto // the heights the ground will have where there's none yet, as of the terrain model on its way: a tile laid out before its // ground comes lies there, or level with the tiles beside, rather than at the height of the layer far below or above void guess_source(height_query Query) { m_guess = std::move(Query); } + // true while the ground under an XZ rectangle (Min/Max are x,z) is still to come. A new tile there waits for it, rather than + // being laid out at the height of the layer; elsewhere it lies on whatever ground there is, or on the guess, as without it + using coming_query = std::function; + void coming_source(coming_query Query) { m_coming = std::move(Query); } // the area the imagery is downloaded in, a polygon of PUWG 1992 (easting, northing): its tiles go to the disk cache in the // background, the products the settings ask for, and no tile outside it is asked for around the camera. Empty: no area, the // tiles around the camera as before @@ -176,7 +181,8 @@ class editor_orthophoto bool puwg{false}; std::string error; }; - static service_info describe(std::string const &Service); + // Stop: true to give the reading up + static service_info describe(std::string const &Service, std::function const &Stop = {}); static std::string cache_directory(); private: @@ -236,6 +242,9 @@ class editor_orthophoto float height_max{0.0f}; std::vector surface; // upward facing ground triangles clipped to the tile (3 vertices each) bool guessed{false}; // no ground under it when sampled: the heights guessed, from the terrain model or the tiles beside + // the points of the grid of the heights the ground didn't answer when sampled (rows north->south, as heights): filled from + // the points beside or guessed, and sampled again once the ground comes under one of them + std::vector unanswered; // scene geometry scene::basic_section *section{nullptr}; // section holding the shape (nullptr = not in the scene) scene::basic_cell *cell{nullptr}; // set instead of the section's shape list when the shape is translucent @@ -245,6 +254,12 @@ class editor_orthophoto }; static int level_for(int Distance, bool Hires); + // the level a tile is asked for at first: a tile showing nothing yet takes the standard image before the 4K one + static int first_level(tile const &Tile, int Level); + // the tile is outside the download area set, which then has no imagery asked for it + bool outside_area(tile_key const &Key) const; + // a tile of the view hurried: put at the front of the queue unless it's shown as it should be. true: counted among the hurried + bool hurry_tile(tile_key const &Key, int Distance); tile_key camera_tile(glm::dvec3 const &Camera) const; glm::dvec2 tile_corner(tile_key const &Key) const; // world (x,z) of the north-west corner void schedule(tile_key const &Key, tile &Tile, int Level, std::uint8_t Alpha); @@ -253,6 +268,10 @@ class editor_orthophoto void release_tile(tile &Tile); texture_slot acquire_slot(); void sample_ground(tile_key const &Key, tile &Tile); + // the ground has come under a point of the tile which had none when it was sampled + bool ground_came(tile_key const &Key, tile const &Tile) const; + // a new tile isn't asked for yet: the ground under it is still to come + bool waits_for_ground(tile_key const &Key) const; // the height of the ground sampled under a tile beside Own at the point, the tiles with guessed heights left out bool sampled_height(tile_key const &Own, double const X, double const Z, float &Height) const; void build_shape(tile_key const &Key, tile &Tile); @@ -272,6 +291,7 @@ class editor_orthophoto ground_query m_ground; height_query m_height; height_query m_guess; + coming_query m_coming; scene::basic_region *m_region{nullptr}; // region the scene geometry was put into std::multimap m_free_chunks; // geometry chunks by capacity, reused between tiles // the scene opacity is baked into the textures, which means reading the tiles again; applied once the value settles @@ -300,6 +320,7 @@ class editor_orthophoto bool m_prefetch_paused{false}; source m_prefetch_source; std::uint32_t m_prefetch_generation{0}; + std::set m_urgent; // asked for by hurry(): workers take these first; guarded by m_mutex std::atomic m_stop{false}; std::atomic m_generation{1}; diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index c7e162c46..dd475b183 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -198,6 +198,18 @@ bool editorSettings::load() layer.terms = fields[5]; m_wms_layers.push_back(layer); } + else if (key == "camera_speed") + { + parse(value, m_camera.speed); + m_camera.speed = std::clamp(m_camera.speed, 0.05, 10.0); + } + else if (key == "camera_fast") + { + parse(value, m_camera.fast); + m_camera.fast = std::clamp(m_camera.fast, 1.0, 30.0); + } + else if (key == "camera_zoomed") + m_camera.zoomed = (value == "1"); else if (key.rfind(origin_prefix, 0) == 0) { // northing;easting @@ -269,6 +281,9 @@ bool editorSettings::save() stream << "laying_heights " << (m_heights == lay_heights::points ? "points" : m_heights == lay_heights::level ? "level" : "fitted") << "\n"; for (auto const &layer : m_wms_layers) stream << "wms_layer " << (layer.visible ? 1 : 0) << ";" << layer.opacity << ";" << encoded(layer.url) << ";" << encoded(layer.layers) << ";" << encoded(layer.title) << ";" << encoded(layer.terms) << "\n"; + stream << "camera_speed " << m_camera.speed << "\n"; + stream << "camera_fast " << m_camera.fast << "\n"; + stream << "camera_zoomed " << (m_camera.zoomed ? 1 : 0) << "\n"; stream << std::fixed << std::setprecision(3); for (auto const &origin : m_orthophoto_origins) stream << origin.first << " " << origin.second.first << ";" << origin.second.second << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index 548f12b61..5223fca51 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -119,10 +119,19 @@ public: }; lay_heights heights() const { return m_heights; } void heights(lay_heights Heights) { m_heights = Heights; } + // the free camera: its speed, how many times faster Ctrl makes it, and in the top view as fast as the view is zoomed + struct camera_settings + { + double speed{1.0}; + double fast{30.0}; + bool zoomed{false}; // off as the editor was before: "As it was" means it + }; + camera_settings &camera() { return m_camera; } private: movement_scheme m_movement{movement_scheme::wsad}; orthophoto_settings m_orthophoto; + camera_settings m_camera; std::map> m_orthophoto_origins; std::vector m_wms_layers; double m_platform_edge{1.725}; diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a681b1a9e..9c00017de 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include terrain_streamer EditorTerrain; @@ -907,6 +908,44 @@ bool terrain_streamer::owns(gfx::geometry_handle const &Geometry) const return false; } +bool terrain_streamer::in_walk(chunk_key const &Key) const +{ + // the circle update() walks around the camera and around where it's heading + auto const within = [this, &Key](chunk_key const &Centre) { + auto const dx{Key.first - Centre.first}; + auto const dz{Key.second - Centre.second}; + return std::abs(dx) <= m_walkradius && std::abs(dz) <= m_walkradius && dx * dx + dz * dz <= (m_walkradius + 1) * (m_walkradius + 1); + }; + return within(m_walkhere) || within(m_walkthere); +} + +bool terrain_streamer::chunk_coming(chunk_key const &Key) const +{ + if (m_chunks.contains(Key) || m_removed.contains(Key)) + return false; + if (m_loading.contains(Key)) + return true; + // a chunk the walk doesn't reach at this distance isn't loaded, so it isn't waited for: it's taken in when the camera comes near + if (false == in_walk(Key)) + return false; + // still to come while its pack isn't read yet, or it's in its pack; not there where the pack is read without it + auto const pack{m_packs.find(heightmap::pack_of(Key))}; + if (pack == m_packs.end() || pack->second.status == pack_state::state::unknown || pack->second.status == pack_state::state::loading) + return true; + return pack->second.status == pack_state::state::ready && pack->second.file->has(Key); +} + +bool terrain_streamer::ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const first{heightmap::chunk_at(Low.x, Low.y)}; + auto const last{heightmap::chunk_at(High.x, High.y)}; + for (auto z{std::min(first.second, last.second)}; z <= std::max(first.second, last.second); ++z) + for (auto x{std::min(first.first, last.first)}; x <= std::max(first.first, last.first); ++x) + if (chunk_coming(chunk_key{x, z})) + return true; + return false; +} + bool terrain_streamer::exists(chunk_key const &Key) const { if (m_chunks.count(Key) > 0) diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index cf8407ac1..760335a75 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -81,6 +81,10 @@ class terrain_streamer std::string stats() const; // chunks in the pack files and in memory, less the removed ones; the files known so far bool exists(chunk_key const &Key) const; + // true while a chunk over an XZ rectangle (Low/High are x,z) is still to come at this distance of the camera: being loaded, or + // within the walk around the camera and in its pack or with its pack not read yet. False where all of them are in memory, where + // none is nor will be, and where the walk doesn't reach + bool ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const; // editing; the chunks changed are written to the files by save() heightmap::manifest const &manifest() const { return m_manifest; } @@ -235,6 +239,11 @@ class terrain_streamer scene::basic_cell *cell{nullptr}; }; + // within the circle of chunks the last walk of update() asked for + bool in_walk(chunk_key const &Key) const; + // the chunk is still to come at this distance of the camera (see ground_coming) + bool chunk_coming(chunk_key const &Key) const; + void start_workers(); void stop_workers(); void worker(); diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index ce123829f..f5b4d29a5 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -21,6 +21,19 @@ struct ITexture virtual void set_components_hint(int hint) = 0; virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) = 0; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; + // uploads an image from a thread with a gl context of its own, sharing the objects with the drawing one. a texture that + // can keeps the image apart until commit_thread_upload(), called on the drawing thread, puts it in place + virtual void upload_from_thread(size_t width, size_t height, const uint8_t *data) + { + update_from_memory(width, height, data); + } + // puts in place the image of the last upload_from_thread() once the gpu has it, without waiting for it. called on the + // drawing thread; false while the upload isn't done yet, to be asked again later + virtual bool commit_thread_upload() + { + // the image went in place right away + return true; + } static ITexture *null_texture() { struct NullTexture : public ITexture diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4a5bc4759..6484fdd75 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14023,6 +14023,36 @@ msgstr "PPM wciśnięty, W / S" msgid "RMB held, A / D" msgstr "PPM wciśnięty, A / D" +msgid "%zu drive with no switch" +msgid_plural "%zu drives with no switch" +msgstr[0] "%zu napęd bez zwrotnicy" +msgstr[1] "%zu napędy bez zwrotnicy" +msgstr[2] "%zu napędów bez zwrotnicy" + +msgid "Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name" +msgstr "Napędy ustawione na zwrotnicę, której w scenerii nie ma: zostały po zwrotnicy usuniętej lub przemianowanej ręcznie albo we wcześniejszym edytorze, ich eventy niczego nie przestawiają.\nKliknięcie przenosi do napędu i go zaznacza, Delete go usuwa; można też nadać jakiejś zwrotnicy jego nazwę" + +msgid "%s: no switch of this name" +msgstr "%s: brak zwrotnicy o tej nazwie" + +msgid "%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view" +msgid_plural "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view" +msgstr[0] "%zu napęd nie ma zwrotnicy o swojej nazwie: jest na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[1] "%zu napędy nie mają zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[2] "%zu napędów nie ma zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" + +msgid "The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is" +msgstr "Napęd %s nie ma opisu dla edytora: może też ustawiać prędkość albo nieść podsypkę zwrotnicy, więc zostaje bez zmian" + +msgid "The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew" +msgstr "Rozjazd krzyżowy ma napęd %s bez opisu dla edytora, który może też ustawiać prędkość albo nieść jego podsypkę: nie zostanie ułożony od nowa" + +msgid "Switch %s keeps its drive %s, which isn't described for the editor" +msgstr "Zwrotnica %s zostaje przy swoim napędzie %s, który nie ma opisu dla edytora" + +msgid "A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted" +msgstr "Napęd bez opisu dla edytora, np. rozjazdu krzyżowego, który może też ustawiać prędkość albo nieść podsypkę zwrotnicy: edytor go nie zmienia, zostaje na miejscu, gdy zwrotnica się przesuwa, i znika razem z ostatnią zwrotnicą, którą przestawia" + # the wizard of a new scenery: the range of the aerial photos, given on the map and changed in the editor msgid "A fictional scenery needs no place on the map" @@ -14236,3 +14266,39 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" + +msgid "Camera speed" +msgstr "Prędkość kamery" + +msgid "Speed of the camera" +msgstr "Prędkość kamery" + +msgid "How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was" +msgstr "Jak szybko strzałki albo WSAD przesuwają kamerę, z Shiftem trochę szybciej; 1 = jak dotąd" + +msgid "Ctrl speeds it up" +msgstr "Przyspieszenie z Ctrl" + +msgid "How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was" +msgstr "Ile razy szybciej jedzie kamera z wciśniętym Ctrl, także Ctrl+Shift; 30 = jak dotąd" + +msgid "In the top view as fast as the view is zoomed" +msgstr "W widoku z góry prędkość zależna od powiększenia" + +msgid "Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom" +msgstr "Przybliżona mapa jedzie wolno, oddalona szybko: po ekranie zawsze w tym samym tempie" + +msgid "As it was" +msgstr "Przywróć domyślne" + +msgid "Orthophoto on (~)" +msgstr "Ortofoto włączone (~)" + +msgid "Orthophoto off (~)" +msgstr "Ortofoto wyłączone (~)" + +msgid "Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)" +msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" + +msgid "Orthophoto: the view is all shown already (Ctrl+~)" +msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 23af295e4..757ccd2b8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -597,6 +597,10 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { if( Framestamp == m_framestamp ) { return; } auto const timedelta { Timer::GetDeltaTime() }; + // the opacities change step by step from where they are, and they start at 1. the first time the instance is + // drawn its lights take their current state at once, whether it came from the definition or from an event since: + // a fade from 1 showed a light that is off as lit for a moment, the first time it came into view + bool const transition { m_transition && m_lightsanimated }; // interpretacja ułamka zależnie od typu // case ls_Off: ustalenie czasu migotania, t<1s (f>1Hz), np. 0.1 => t=0.1 (f=10Hz) @@ -637,12 +641,13 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { const float transitionontime = std::min(0.25f, std::min(ontime, offtime) * 0.95f); const float transitionofftime = std::min(0.45f, std::min(ontime, offtime) * 0.95f); if (on) - opacity += m_transition ? timedelta / transitionontime : 1.f; // increase to max value + opacity = static_cast( opacity + ( transition ? timedelta / transitionontime : 1.0 ) ); // increase to max value else - opacity -= m_transition ? timedelta / transitionofftime : 1.f; // reduce to zero + opacity = static_cast( opacity - ( transition ? timedelta / transitionofftime : 1.0 ) ); // reduce to zero // Clamp the opacity opacity = std::clamp(opacity, 0.f, 1.f); } + m_lightsanimated = true; // Ra 2F1I: to by można pomijać dla modeli bez animacji, których jest większość for (const auto entry : m_animlist) { diff --git a/model/AnimModel.h b/model/AnimModel.h index e5a6841b6..7cf50fa44 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -225,6 +225,7 @@ public: float fOffTime { 1.f / 2 };// { 60.f / 45.f / 2 }; // były stałymi, teraz mogą być zmienne dla każdego egzemplarza // float fTransitionTime { fOnTime * 0.9f }; // time bool m_transition { true }; // smooth transition between light states + bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame // true if this instance is eligible for the batched/instanced render path: diff --git a/model/Texture.cpp b/model/Texture.cpp index 9b428202b..bba3ba763 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -323,6 +324,7 @@ GLint readback_format( GLint const Internalformat ) { std::array opengl_texture::units = { 0 }; GLint opengl_texture::m_activeunit = -1; +std::atomic opengl_texture::m_unitcachestale { false }; std::unordered_map opengl_texture::precompressed_formats = { @@ -729,9 +731,104 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 is_static = true; is_ready = true; } - // the name may be a new one, and the unit active took the texture past the unit cache + // the name may be a new one, and the unit active took the texture past the unit cache. this runs on the python upload + // thread too (python.threadedupload), so the cache is only marked here: clearing it outright raced the drawing thread + // filling it for a multi-bind, and an object got the texture of the one drawn before it for a frame + invalidate_unit_cache(); +} + +namespace +{ +// gl objects of an image uploaded by another thread that was never put in place +void delete_thread_upload(GLuint const Texture, GLsync const Fence) +{ + if (Fence != nullptr) + glDeleteSync(Fence); + glDeleteTextures(1, &Texture); +} +} // namespace + +void opengl_texture::upload_from_thread(size_t width, size_t height, const uint8_t *raw) +{ + // a texture of its own each time: the one drawn from may be in use by the gpu for the drawing context, and writing it from + // here, with nothing to order the two contexts, could leave it incomplete or half written for a frame + texture_thread_upload upload; + upload.width = width; + upload.height = height; + glGenTextures(1, &upload.id); + glBindTexture(target, upload.id); + set_filtering(); + glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap_mode_s); + glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap_mode_t); + if (!glGenerateMipmap) + glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); + glTexImage2D(target, 0, GL_SRGB8_ALPHA8, static_cast(width), static_cast(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, raw); + if (glGenerateMipmap) + glGenerateMipmap(target); + glBindTexture(target, 0); + if (glFenceSync) + { + upload.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + } + if (upload.fence == nullptr) + { + // no sync objects, or no fence made: the drawing context can only be sure of the image once the upload is done + glFinish(); + } + else + { + // the drawing context asks for the fence, which signals only once it is on its way to the gpu + glFlush(); + } + + std::optional superseded; + { + std::scoped_lock lock{m_threaduploadmutex}; + superseded = std::exchange(m_threadupload, upload); + } + if (superseded.has_value()) + { + // the drawing thread didn't take it, so nothing drew from it + delete_thread_upload(superseded->id, superseded->fence); + } +} + +bool opengl_texture::commit_thread_upload() +{ + texture_thread_upload upload; + { + std::scoped_lock lock{m_threaduploadmutex}; + if (false == m_threadupload.has_value()) + return true; + // asked without waiting. the image goes in place only once the upload is done, so every context binding it after + // has it whole: the extra viewports and the windows of python.displaywindows draw in contexts of their own + if (m_threadupload->fence != nullptr) + { + // a failed query (GL_WAIT_FAILED) isn't asked again: the image would never go in place + if (glClientWaitSync(m_threadupload->fence, 0, 0) == GL_TIMEOUT_EXPIRED) + return false; + glDeleteSync(m_threadupload->fence); + } + upload = *m_threadupload; + m_threadupload.reset(); + } + + if (id != invalid_id) + glDeleteTextures(1, &id); + id = upload.id; + data_width = static_cast(upload.width); + data_height = static_cast(upload.height); + data_format = GL_SRGB8_ALPHA8; + data_components = GL_RGBA; + if (type == "internalsrc:") + { + is_static = true; + is_ready = true; + } + // the name deleted may come back for another texture, and a deleted texture isn't bound any more for (auto &unit : units) unit = -1; + return true; } void @@ -1263,6 +1360,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; if (GLAD_GL_ARB_direct_state_access) @@ -1630,6 +1728,25 @@ opengl_texture::reset_unit_cache() { m_activeunit = -1; } +void +opengl_texture::invalidate_unit_cache() { + + m_unitcachestale.store( true ); +} + +void +opengl_texture::sync_unit_cache() { + + // a plain load first: bind() calls this for every texture, and a read-modify-write each time would cost more + if( ( false == m_unitcachestale.load() ) + || ( false == m_unitcachestale.exchange( false ) ) ) { + return; + } + for( auto &unit : units ) { + unit = -1; + } +} + void opengl_texture::set_filtering() const { diff --git a/model/Texture.h b/model/Texture.h index 20221fcea..3934565a5 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,8 +9,11 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include +#include +#include #include "winheaders.h" #include #include "model/ResourceManager.h" @@ -19,6 +22,14 @@ http://mozilla.org/MPL/2.0/. struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming +// an image uploaded by another thread into a texture of its own, waiting for the drawing thread to put it in place +struct texture_thread_upload { + GLuint id { 0 }; + GLsync fence { nullptr }; // set after the upload in the uploading context; none where the driver has no sync objects + size_t width { 0 }; + size_t height { 0 }; +}; + struct opengl_texture : public ITexture { static DDSURFACEDESC2 deserialize_ddsd(std::istream&); static DDCOLORKEY deserialize_ddck(std::istream&); @@ -47,6 +58,13 @@ struct opengl_texture : public ITexture { set_components_hint( GLint hint ) override; static void reset_unit_cache(); + // marks the unit cache as not to be trusted. safe to call from any thread: the cache itself is + // cleared by the thread drawing with it, the next time it binds textures (sync_unit_cache) + static void + invalidate_unit_cache(); + // clears the unit cache if a thread marked it as not to be trusted since. called before the cache is read + static void + sync_unit_cache(); virtual int get_width() const override { return data_width; } @@ -85,6 +103,10 @@ struct opengl_texture : public ITexture { virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override; + // the image goes into a texture of its own, and the drawing thread swaps it in after the gpu has it (commit_thread_upload). + // the texture drawn from is never written by the uploading thread + void upload_from_thread(size_t width, size_t height, const uint8_t *data) override; + bool commit_thread_upload() override; // members static constexpr GLuint invalid_id { std::numeric_limits::max() }; // id value of texture without GL resource @@ -100,6 +122,11 @@ struct opengl_texture : public ITexture { GLenum target = GL_TEXTURE_2D; static std::array units; static GLint m_activeunit; + // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread + static std::atomic m_unitcachestale; + + std::mutex m_threaduploadmutex; + std::optional m_threadupload; // guarded by m_threaduploadmutex public: // methods diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..3a3008a44 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2457,6 +2457,8 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel if (GLAD_GL_ARB_multi_bind) { + // the cache may have been marked stale by the python upload thread + opengl_texture::sync_unit_cache(); GLuint lastdiff = 0; size_t i; for (i = 0; i < gl::MAX_TEXTURES; i++) @@ -4338,7 +4340,7 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) }; if( Lightlevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place - light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * std::clamp( 1.25f - (float)luminance, 0.f, 1.f ) ); + light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ); light_ubo->update( light_ubs ); } diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 3b8de9469..706e5d871 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -65,7 +65,9 @@ opengl_particles::update( opengl_camera const &Camera ) { vertex.color[ 0 ] = static_cast( particlecolor.r ); vertex.color[ 1 ] = static_cast( particlecolor.g ); vertex.color[ 2 ] = static_cast( particlecolor.b ); - vertex.color[ 3 ] = static_cast( std::clamp( particle.opacity * 255, 0.f, 255.f ) ); + // as up to 26.05.1, when clamp made the alpha a byte before clamping it: an opacity over 1 wraps + // round. through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion + vertex.color[ 3 ] = static_cast( static_cast( particle.opacity * 255 ) ); auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 5083c6f2f..8bef3352d 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -4370,8 +4370,8 @@ glm::dvec3 opengl_renderer::Update_Mouse_Position() { glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size; - mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 ); - mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); + mousepos.x = safe_clamp( mousepos.x, 0, Global.fb_size.x - 1 ); + mousepos.y = safe_clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); GLfloat pointdepth; ::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth ); diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 8ccb728dd..517fec751 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -168,9 +168,9 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { if( m_ownertype == owner_type::vehicle ) { auto const &mover { *m_owner.vehicle->MoverParameters }; - if( Global.AirTemperature <= 5.f || mover.dizel_heat.Ts < 45.f ) { - m_emitter.color = glm::vec3{ 128, 128, 128 }; - } + // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant + // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the + // emitter colour, so the smoke turned pure white, glowing at night, and never changed back // a vehicle taken off the tracks (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 m_spawncount = ( diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fac540019..b95b310d8 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -142,18 +142,24 @@ void render_task::run() } else { - std::lock_guard guard(m_target->mutex); + // the lock may be held by the drawing thread for a whole upload: waited for without the gil. the bytes stay + // valid without it, the object is immutable and held by its reference here + Py_BEGIN_ALLOW_THREADS + { + std::scoped_lock guard(m_target->mutex); - if (m_target->image.size() != expectedBytes) - m_target->image.resize(expectedBytes); + if (m_target->image.size() != expectedBytes) + m_target->image.resize(expectedBytes); - std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); + std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); - m_target->width = screenWidth; - m_target->height = screenHeight; - m_target->components = glComponents; - m_target->format = glFormat; - m_target->timestamp = std::chrono::high_resolution_clock::now(); + m_target->width = screenWidth; + m_target->height = screenHeight; + m_target->components = glComponents; + m_target->format = glFormat; + m_target->timestamp = std::chrono::high_resolution_clock::now(); + } + Py_END_ALLOW_THREADS } } @@ -232,6 +238,35 @@ void render_task::upload() const } } +void render_task::upload_from_thread() +{ + m_uploadedbyworker = true; + if (Global.python_uploadmain && m_target && m_target->shared_tex) + { + m_target->shared_tex->upload_from_thread(m_target->width, m_target->height, reinterpret_cast(m_target->image.data())); + } +} + +bool render_task::finish_upload() const +{ + if (false == Global.python_uploadmain || nullptr == m_target || nullptr == m_target->shared_tex) + return true; + // the old texture is deleted and the new name published under the lock the windows of python.displaywindows bind under, + // so none of them binds the old name once it is gone: a name bound before stays alive in its context while bound there + std::scoped_lock lock(m_target->mutex); + if (m_uploadedbyworker) + { + if (false == m_target->shared_tex->commit_thread_upload()) + return false; + } + else + { + upload(); + } + m_target->texture_id = m_target->shared_tex->get_id(); + return true; +} + void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success @@ -569,9 +604,11 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo // execute python code task->run(); if (Context) - task->upload(); - else { + task->upload_from_thread(); + } + { + // the drawing thread uploads the image, or puts in place the one uploaded here std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } @@ -609,10 +646,8 @@ void python_taskqueue::update() { std::scoped_lock lock(m_uploadtasks.mutex); - for (auto const &task : m_uploadtasks.data) - task->upload(); - - m_uploadtasks.data.clear(); + // a task whose image a worker uploaded stays until the gpu has the image + std::erase_if(m_uploadtasks.data, [](std::shared_ptr const &Task) { return Task->finish_upload(); }); } void python_taskqueue::error() diff --git a/scripting/PyInt.h b/scripting/PyInt.h index c8c410397..3259b418a 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -67,6 +67,9 @@ struct python_rt int width; int height; std::string image; + // gl name of the texture with the last image put in place, for the windows of python.displaywindows (0: none yet). the image + // uploaded by a worker gets a texture of its own, so the name changes with each one + size_t texture_id{0}; std::chrono::high_resolution_clock::time_point timestamp; }; @@ -80,7 +83,13 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); + // uploads the image on the drawing thread void upload() const; + // uploads the image on a worker with a gl context of its own (python.threadedupload); finish_upload() puts it in place + void upload_from_thread(); + // on the drawing thread: uploads the image, or puts in place the one a worker uploaded. false while the gpu hasn't got + // the latter yet, to be called again + bool finish_upload() const; void cancel() const; auto target() const -> std::shared_ptr { @@ -92,6 +101,8 @@ class render_task PyObject *m_renderer{nullptr}; std::shared_ptr m_input{nullptr}; std::shared_ptr m_target{nullptr}; + // set by upload_from_thread(); read by the drawing thread after the task was handed over under the lock of the queue + bool m_uploadedbyworker{false}; }; class python_taskqueue diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4da50151e..5a3491af7 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -30,7 +30,7 @@ void texture_window_cursor_pos(GLFWwindow *win, double x, double y) } python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) - : m_rt(rt), m_touchlist(touchlist) + : m_rt(rt), m_touchlist(touchlist), m_initialtexture(rt->shared_tex->get_id()) { for (const auto &viewport : Global.python_viewports) { @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); + bind_shared_texture(); } else { GLuint tex; @@ -146,6 +146,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -188,6 +190,16 @@ void python_screen_viewer::threadfunc() } } +void python_screen_viewer::bind_shared_texture() const +{ + // bound each frame: each image uploaded by a worker comes in a texture of its own, and a name deleted comes back for + // a later one, so a name seen before may be another texture already. bound under the lock the drawing thread deletes + // the old texture under, so the name read here is never one already gone + std::scoped_lock guard(m_rt->mutex); + size_t const texture = m_rt->texture_id; + glBindTexture(GL_TEXTURE_2D, static_cast(texture != 0 ? texture : m_initialtexture)); +} + void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { for (auto const &conf : m_windows) { diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index ccd78f0ef..41b52a7e2 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -31,8 +31,12 @@ class python_screen_viewer gl::scene_ubs m_ubs; std::atomic_bool m_exit = false; + // the texture of the screen when the viewer was made, read on the drawing thread: shown until an image is put in place + size_t m_initialtexture{0}; void threadfunc(); + // with python.sharectx, binds the texture with the last image of the screen, in the context of the window made current + void bind_shared_texture() const; public: python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 9e979e2ca..5b224b666 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -247,10 +247,9 @@ void blackbox_recorder::update(double const Deltatime) { std::scoped_lock lock{m_mutex}; m_time += Deltatime; - // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a - // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with - // a recording which couldn't be made - if (m_time >= m_tapedue) { + // with the physics logs on, each driver writes its own all the time. the tapes are files of their own: they go on + // after the recording ends in the editor, and with a recording which couldn't be made + if (false == WriteLogFlag && m_time >= m_tapedue) { keep_tape_line(); m_tapedue = std::max(m_tapedue + tapeinterval, m_time); } @@ -510,13 +509,10 @@ void blackbox_recorder::keep_tape_line() { auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; if (driver == nullptr) return; - auto const &name{driver->physicslog_name()}; - // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has - // no time for, on a hard disk with hundreds of them - PhysicsLogs.put_first(name); // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice if (driver->writes_physicslog()) return; + auto const &name{driver->physicslog_name()}; if (m_tapes.insert(name).second) { PhysicsLogs.begin(name, TController::physicslog_header()); WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 18ee052c4..a3aaf5d0f 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -88,9 +88,8 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); - // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road - // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would - // have it. a driver's log is begun at the first line given for that driver, and goes on + // with the physics logs off, the line of the log of the driver the user is with, to its log, physicslog/.dat, + // as the physics logs would have it. a driver's log is begun at the first line given for that driver, and goes on // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..4e8c0e5f7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -26,11 +26,12 @@ namespace { float turbidity_of( float const Overcast ) { + if( Overcast <= 0.10 ) { return 3.f; } if( Overcast <= 0.20 ) { return 4.f; } - if( Overcast <= 0.40 ) { return 5.f; } - if( Overcast <= 0.60 ) { return 6.f; } - if( Overcast <= 0.70 ) { return 7.f; } - if( Overcast <= 0.80 ) { return 8.f; } + if( Overcast <= 0.60 ) { return 5.f; } + if( Overcast <= 0.70 ) { return 6.f; } + if( Overcast <= 0.80 ) { return 7.f; } + if( Overcast <= 0.90 ) { return 8.f; } return 9.f; } diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 2efa57291..d32fd0e72 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -17,7 +17,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "utilities/utilities.h" -#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -46,15 +45,6 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } -// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of -// the other drivers: the closing at the end of the run drops those it has no time for -void put_physicslog_first(TDynamicObject const &Vehicle) -{ - auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; - if (driver != nullptr) - PhysicsLogs.put_first(driver->physicslog_name()); -} - } // namespace namespace simulation { @@ -135,13 +125,11 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - auto const *vehicle { simulation::Vehicles.find(name) }; - if (vehicle == nullptr) + if (simulation::Vehicles.find(name) == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } - put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index e24db024f..d06c83445 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -32,6 +32,8 @@ add_executable(${UNIT_TESTS_NAME} # and the fouling points of the switches, widened in the curves as the gauge is "${CMAKE_SOURCE_DIR}/editor/editorGauge.cpp" "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" + # and the http client the editor fetches its aids with + "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp new file mode 100644 index 000000000..7102d06e0 --- /dev/null +++ b/tests/unit/test_braking_curve.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakingcurve.h" + +#include +#include + +// the deceleration the AI asks for on its way down to a stop or a lower speed ahead, outside of the final approach +// (TController::adjust_desired_speed_for_braking_curve). in shunting the brake table of the consist isn't worked out +// and stays at zero; planned from it, the curve asked for next to no braking, and shunting engines ran through the +// signals they were to stop at. + +namespace { + +auto constexpr tablesize{20}; +using brake_values = std::array; + +// what the AI holds in shunting: nothing worked out +struct zeroed_table { + brake_values a0{}; + brake_values a1{}; + + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 100.0}; } +}; + +// a train brake that gives the same deceleration at every speed, full service 0.05 + 12 * 0.1 = 1.25 m/s2 +struct flat_table { + brake_values a0{}; + brake_values a1{}; + + flat_table() { + a0.fill(0.05); + a1.fill(0.1); + } + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 120.0}; } +}; + +braking_curve::approach stop_at(double const Speed, double const Distance) { + braking_curve::approach approach{}; + approach.speed = Speed; + approach.target = 0.0; + approach.distance = Distance; + approach.offset = 0.0; // the braking point of a stop, outside of a train, is the stop itself (VelNext * multiplier) + approach.speedup_horizon = 30.0 / 3.6; + approach.fill_horizon = 30.0 / 3.6; + return approach; +} + +// the AI in shunting leaves the brake alone for a demand weaker than this (TController::fAccThreshold) +auto constexpr shunting_brake_threshold{-0.2}; + +struct shunting_run { + double speed; // [km/h] + double left; // to the stop point [m] + bool braked_at_once; +}; + +// a shunting engine braking to a stop point the way the AI drives it: the brake follows the demand once it is past +// the threshold, the engine coasts otherwise. the braking curve gives way near the point to the final approach, at +// walking pace (10 km/h, 5 km/h in the last 10 m) +shunting_run brake_to_point(double const Speed, double const Distance, zeroed_table const &Table) { + auto const table{Table.table()}; + auto const timestep{0.1}; + shunting_run run{Speed, Distance, false}; + run.braked_at_once = braking_curve::demand(stop_at(run.speed, run.left), &table) < shunting_brake_threshold; + while ((run.speed > (run.left > 10.0 ? 10.0 : 5.0)) && (run.left > -50.0)) { + auto const demand{braking_curve::demand(stop_at(run.speed, run.left), &table)}; + auto const acceleration{demand < shunting_brake_threshold ? demand : 0.0}; + run.speed = std::max(0.0, run.speed + 3.6 * acceleration * timestep); + run.left -= run.speed / 3.6 * timestep; + } + return run; +} + +} // namespace + +TEST_CASE("braking curve: a brake table left at zero isn't known, one worked out is") { + CHECK_FALSE(zeroed_table{}.table().known()); + CHECK(flat_table{}.table().known()); +} + +TEST_CASE("braking curve: shunting to a point asks for the constant deceleration over the distance left") { + zeroed_table const shunting; + auto const table{shunting.table()}; + auto approach{stop_at(33.0, 186.0)}; + SUBCASE("coasting") { approach.acceleration = 0.0; } + SUBCASE("still speeding up") { approach.acceleration = 0.2; } + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(-33.0 * 33.0 / (25.92 * 186.0 + 0.1))); + CHECK(demand == doctest::Approx(braking_curve::demand(approach, nullptr))); + // enough for the AI to put the brake on + CHECK(demand < shunting_brake_threshold); +} + +TEST_CASE("braking curve: a shunting engine braking to a point gets down to walking pace short of it") { + zeroed_table const shunting; + auto speed{0.0}; + auto distance{0.0}; + SUBCASE("33 km/h, 186 m") { + speed = 33.0; + distance = 186.0; + } + SUBCASE("40 km/h, 186 m") { + speed = 40.0; + distance = 186.0; + } + SUBCASE("33 km/h, 120 m") { + speed = 33.0; + distance = 120.0; + } + SUBCASE("25 km/h, 60 m") { + speed = 25.0; + distance = 60.0; + } + CAPTURE(speed); + CAPTURE(distance); + + auto const run{brake_to_point(speed, distance, shunting)}; + + CHECK(run.braked_at_once); + CHECK(run.left > 0.0); + CHECK(run.speed <= 10.0); +} + +TEST_CASE("braking curve: a train with a worked out brake table plans along the shape of its brake") { + flat_table const train; + auto const table{train.table()}; + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.fill_horizon = 6.0; + approach.speedup_horizon = 5.0; + + SUBCASE("before the brake is applied, the room it takes to fill is kept") { + auto const room{580.0 - 80.0 / 3.6 * 6.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, room + 0.1 / 25.92, 0.0, table))); + // with the same deceleration at every speed the shape is the constant deceleration over that room + CHECK(demand == doctest::Approx(-(80.0 / 3.6) * (80.0 / 3.6) / (2.0 * room)).epsilon(0.01)); + } + SUBCASE("once the brake is applied, the whole distance is used") { + approach.brake_applied = true; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, 580.0 + 0.1 / 25.92, 0.0, table))); + } + SUBCASE("still speeding up, it plans from the speed reached once the brake acts") { + approach.acceleration = 0.3; + auto const reached{80.0 + 3.6 * 5.0 * 0.3}; + auto const distance{600.0 - (80.0 + reached) * 0.5 / 3.6 * 5.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(reached, 0.0, distance - 20.0 + 0.1 / 25.92, 0.0, table))); + } +} + +TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { + // a table that grips harder as the train slows, on a gradient; the demands were worked out with the + // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) + brake_values a0{}; + brake_values a1{}; + for (auto i{1}; i <= tablesize; ++i) { + a0[i] = 0.12 - 0.003 * i; + a1[i] = 0.06 - 0.001 * i; + } + braking_curve::brake_table const table{a0.data(), a1.data(), tablesize, 120.0}; + REQUIRE(table.full_braking(80.0) == doctest::Approx(0.645)); + REQUIRE(table.full_braking(10.0) == doctest::Approx(0.825)); + + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.gravity = 0.1; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + auto expected{0.0}; + SUBCASE("downhill, coasting, the brake still to be applied") { expected = -0.4926656801067293; } + SUBCASE("downhill, the brake applied") { + approach.brake_applied = true; + expected = -0.37739905908238147; + } + SUBCASE("downhill, still speeding up") { + approach.acceleration = 0.3; + expected = -0.5330117415264249; + } + SUBCASE("uphill, down to 40 km/h") { + approach = stop_at(100.0, 900.0); + approach.target = 40.0; + approach.gravity = -0.08; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + expected = -0.40930710539221765; + } + + CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); +} diff --git a/tests/unit/test_crashsignals.cpp b/tests/unit/test_crashsignals.cpp new file mode 100644 index 000000000..4c4dd1e86 --- /dev/null +++ b/tests/unit/test_crashsignals.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/crashsignals.h" + +// the stack of a crash on Linux (utilities/crashsignals.h): written to the log and to the standard error, after which +// the signal ends the process as it always did. the crash happens in a child process, which the test watches +#if defined(__linux__) + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +std::string read_all(int const File) { + std::string text; + std::array buffer{}; + for (auto count{::read(File, buffer.data(), buffer.size())}; count > 0; count = ::read(File, buffer.data(), buffer.size())) + text.append(buffer.data(), static_cast(count)); + return text; +} + +std::string read_file(std::string const &Path) { + std::ifstream file{Path, std::ios::binary}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +// the child: the report goes to the pipe in place of the standard error, no core dump is left behind +[[noreturn]] void crash_in_child(std::array const &Pipe, std::string const &Log) { + // a child stuck before the crash (a lock some other thread held at the fork) ends anyway, and the test with it + alarm(10); + dup2(Pipe[1], STDERR_FILENO); + close(Pipe[0]); + close(Pipe[1]); + rlimit const nocore{0, 0}; + setrlimit(RLIMIT_CORE, &nocore); + + crash_signals::install("test version 1.2"); + crash_signals::set_log_path(Log); + raise(SIGSEGV); + _exit(0); // not reached: the signal ends the child +} + +} // namespace + +TEST_CASE("crash signals: a crash writes its stack to the log and to the standard error, and still ends by its signal") { + test::scratch_folder const folder{"crash_signals"}; + auto const log{folder.write("log.txt", "the last line of the log\n")}; + + std::array pipe_ends{}; + REQUIRE(pipe(pipe_ends.data()) == 0); + auto const child{fork()}; + REQUIRE(child >= 0); + if (child == 0) + crash_in_child(pipe_ends, log); + + close(pipe_ends[1]); + auto const errors{read_all(pipe_ends[0])}; + close(pipe_ends[0]); + int status{0}; + REQUIRE(waitpid(child, &status, 0) == child); + + CAPTURE(errors); + // the process ends as it would without the handler + CHECK(WIFSIGNALED(status)); + CHECK(WTERMSIG(status) == SIGSEGV); + // the report on the standard error, which the starter shows + CHECK(errors.find("Crash: signal 11 (SIGSEGV) at address 0x") != std::string::npos); + CHECK(errors.find("Version: test version 1.2") != std::string::npos); + CHECK(errors.find("Stack (addr2line") != std::string::npos); + // with the frames of the program that crashed + CHECK(errors.find("eu07_unit_tests") != std::string::npos); + // and the same at the end of the log, after what it held + auto const logtext{read_file(log)}; + CAPTURE(logtext); + CHECK(logtext.starts_with("the last line of the log\n")); + CHECK(logtext.find("Crash: signal 11 (SIGSEGV)") != std::string::npos); + CHECK(logtext.find("eu07_unit_tests") != std::string::npos); +} + +#endif diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp new file mode 100644 index 000000000..ffdfe9959 --- /dev/null +++ b/tests/unit/test_editor_http.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorHttp.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// a service on this machine. with no reply it takes the connection and the request and never answers, as geoportal.gov.pl +// does now and then +class local_server { + public: + explicit local_server(std::string Reply = {}) : + m_reply(std::move(Reply)) { + m_acceptor.open(asio::ip::tcp::v4()); + m_acceptor.bind({asio::ip::address_v4::loopback(), 0}); + m_acceptor.listen(); + m_port = m_acceptor.local_endpoint().port(); + m_thread = std::jthread{[this]() { serve(); }}; + } + ~local_server() { + m_done = true; + // a connection of its own wakes the server waiting for one + asio::ip::tcp::socket wake{m_context}; + asio::error_code ignored; + wake.connect({asio::ip::address_v4::loopback(), m_port}, ignored); + wake.close(ignored); + m_thread.join(); + } + local_server(local_server const &) = delete; + local_server &operator=(local_server const &) = delete; + + std::string url() const { + return std::format("http://127.0.0.1:{}/wcs?REQUEST=GetCapabilities", m_port); + } + + private: + void serve() { + while (false == m_done) { + asio::ip::tcp::socket socket{m_context}; + asio::error_code error; + m_acceptor.accept(socket, error); + if (error) + return; + if (false == m_reply.empty()) { + answer(socket); + continue; + } + // the request is left without an answer, the connection open, until the server goes + while (false == m_done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + // the reply once the whole request is read, then the connection closed + void answer(asio::ip::tcp::socket &Socket) const { + asio::error_code error; + asio::streambuf request; + asio::read_until(Socket, request, "\r\n\r\n", error); + if (!error) + asio::write(Socket, asio::buffer(m_reply), error); + Socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); + } + + std::string const m_reply; + asio::io_context m_context; + asio::ip::tcp::acceptor m_acceptor{m_context}; + unsigned short m_port{0}; + std::atomic m_done{false}; + std::jthread m_thread; +}; + +// the requests to the local server would go to a proxy named in the environment, which can't reach it +bool proxied() { + for (char const *variable : {"http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"}) { + if (char const *value{std::getenv(variable)}; value != nullptr && *value != '\0') + return true; + } + return false; +} + +} // namespace + +TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { + if (false == editor_http::available() || proxied()) + return; // a build with no http client, or a proxy in the way + local_server server; + auto const start{std::chrono::steady_clock::now()}; + auto const elapsed = [start]() { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); }; + editor_http::client client; + std::vector data; + std::string error; + // the stop comes while the client waits for the answer, long before any of its timeouts + auto const got{client.get(server.url(), data, error, [&elapsed]() { return elapsed() > 0.3; })}; + CHECK_FALSE(got); + CHECK_FALSE(error.empty()); + // the receive timeout is 20 s; the transfer ends within a moment of the stop (libcurl looks at it about once a second) + CHECK(elapsed() < 5.0); +} + +TEST_CASE("editor http: the whole body of a response is read") { + if (false == editor_http::available() || proxied()) + return; + std::string body(100000, '\0'); + for (std::size_t i = 0; i < body.size(); ++i) + body[i] = static_cast('a' + i % 26); + local_server server{std::format("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK(client.get(server.url(), data, error, []() { return false; })); + CHECK(error.empty()); + CHECK(std::string(data.begin(), data.end()) == body); +} + +TEST_CASE("editor http: the body of an error is kept with the status in the error") { + if (false == editor_http::available() || proxied()) + return; + // the terrain model service tells a place outside of its coverage in the body of an error + std::string const body{"outside requested coverage"}; + local_server server{std::format("HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get(server.url(), data, error, []() { return false; })); + CHECK(error == "HTTP 400"); + CHECK(std::string(data.begin(), data.end()) == body); +} diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index 32fadec03..7a341b4f1 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -7,14 +7,10 @@ #include #include #include -#include -#include #include #include #include #include -#include -#include // the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to @@ -126,18 +122,6 @@ TEST_CASE("physicslog: stopping writes what is kept at once, and what comes afte CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); } -TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { - log_folder folder{"closingwait"}; - { - physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.stop(); - // the writing of the stop, left behind, is waited for by the writer going - } - CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); -} - TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { log_folder folder{"failed"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -157,63 +141,6 @@ TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); } -TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { - log_folder folder{"failedvalues"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values second; - second.time = 0.10; - physicslog_values last; - last.time = 0.20; - std::filesystem::create_directories(folder.path() / "EU07-008.dat"); - logs.begin("EU07-008", header); - logs.append("EU07-008", first); - logs.flush(); - // given while the file can't be written: after the lines kept, as text and as values - logs.append("EU07-008", second); - logs.append("EU07-008", "text\r\n"); - logs.append("EU07-008", last); - logs.flush(); - CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); - - std::filesystem::remove(folder.path() / "EU07-008.dat"); - logs.flush(); - auto const text{folder.read("EU07-008")}; - CHECK(text.starts_with(std::string{header} + "0.0500 ")); - CHECK(text.find("\r\n0.1000 ") != std::string::npos); - CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); - CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); -} - -TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { - // the logs of a writing as the writer has them, by their names - std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; - std::vector *> order; - for (auto &log : taken) - order.push_back(&log); - physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); - std::vector names; - for (auto const *log : order) - names.push_back(log->first); - CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); -} - -TEST_CASE("physicslog: a log put first is written as the others are") { - log_folder folder{"first"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.put_first("SM42-002"); - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.begin("SM42-002", header); - logs.append("SM42-002", "0.0500 1.0000\r\n"); - logs.flush(); - CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); - CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); -} - TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { log_folder folder{"failedbegun"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -311,75 +238,3 @@ TEST_CASE("physicslog: what is kept is written when the writer goes") { } CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); } - -TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { - log_folder folder{"after"}; - std::filesystem::create_directories(folder.path()); - { - std::ofstream before{folder.path() / "SU45-001.dat"}; - before << "earlier run\n"; - } - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.append("SU45-001", "0.0500 0.0000\r\n"); - logs.flush(); - logs.append("SU45-001", "0.1000 0.0000\r\n"); - logs.flush(); - CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); -} - -TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { - using namespace std::chrono_literals; - using duration = std::chrono::steady_clock::duration; - // quick: the interval - CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); - CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); - // a third of the interval: still the interval - CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); - // longer: three times the writing, the disk busy with the logs a quarter of the time - CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); - // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still - CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); -} - -TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { - log_folder folder{"values"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values line; - line.time = 0.05; - line.wheelspeed = 1.23456; - line.acceleration = -0.5; - line.mainctrl = 3; - line.direction = 1; - line.command = "ShuntVelocity"; - line.value1 = 40.0; - // a float of the vehicle, widened as the stream widened it - line.enginetemperature = 50.1f; - line.vehiclespeed = 36.0; - logs.begin("SM31-001", header); - logs.append("SM31-001", line); - logs.flush(); - CHECK(folder.read("SM31-001") == std::string{header} + - "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " - "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); -} - -TEST_CASE("physicslog: lines given as values and as text are written in the order given") { - log_folder folder{"order"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values last; - last.time = 0.15; - logs.append("EP09-001", first); - logs.append("EP09-001", "text\r\n"); - logs.append("EP09-001", last); - logs.flush(); - auto const text{folder.read("EP09-001")}; - CHECK(text.starts_with("0.0500 ")); - CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); -} diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp index b55de1644..a97791a32 100644 --- a/tests/unit/test_track_uneven.cpp +++ b/tests/unit/test_track_uneven.cpp @@ -63,7 +63,8 @@ TEST_CASE("uneven track: the cab keeps what the ride on the track doesn't stand TEST_CASE("uneven track: measures as the Id-14 limits for its value") { // appendix 1, class C at 80 km/h: 18 mm vertically, 17 mm sideways, 16 mm of twist on 5 m, gauge +10/-8 mm, 20 mm of cross level, J = 5.3 - auto const amplitude{track_uneven::stray_per_mm * 18.0 * 1000.0}; // mm + auto const amplitude{track_uneven::stray_up_per_mm * 18.0 * 1000.0}; // mm + auto const sideways{track_uneven::stray_side_per_mm * 18.0 * 1000.0}; // mm double const gauge{1.435}; double const step{0.5}; int const steps{4000}; @@ -76,6 +77,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") double level{0.0}; double j{0.0}; double away{0.0}; + double aside{0.0}; for (int line = 0; line < lines; ++line) { auto const heading{glm::pi() * (line + 0.37) / lines}; @@ -85,6 +87,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") std::array, 2> up; std::array, 2> side; std::vector middle; + std::vector across_middle; for (int i = 0; i < steps; ++i) { auto const point{start + along * (i * step)}; @@ -93,9 +96,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") auto const sign{rail == 0 ? 1.0 : -1.0}; auto const stray{track_uneven::field(point + across * (sign * 0.5 * gauge))}; up[rail].push_back((stray.y - sign * 0.5 * track_uneven::level(point, across)) * amplitude); - side[rail].push_back(glm::dot(stray, across) * amplitude); + side[rail].push_back(glm::dot(stray, across) * sideways); } - middle.push_back(track_uneven::field(point).y * amplitude); + auto const centre{track_uneven::field(point)}; + middle.push_back(centre.y * amplitude); + across_middle.push_back(glm::dot(centre, across) * sideways); } std::vector verticals; std::vector horizontals; @@ -120,6 +125,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") wander += peak(gauges) / lines; level += peak(levels) / lines; away += peak(middle) / lines; + aside += peak(across_middle) / lines; j += (deviation(verticals) + deviation(horizontals) + deviation(twists) + 0.5 * deviation(gauges)) / 3.5 / lines; } CHECK(vertical == doctest::Approx(18.0).epsilon(0.1)); @@ -128,7 +134,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") CHECK(wander == doctest::Approx(10.0).epsilon(0.2)); CHECK(level == doctest::Approx(20.0).epsilon(0.1)); CHECK(j == doctest::Approx(5.3).epsilon(0.2)); - CHECK(away < 40.0); // the long waves go past the 15 mm off the survey marks of appendix 1a + // the long waves go past the 15 mm off the survey marks of appendix 1a: most of the height of a track spectrum is in them, the 10 m chord + // hardly sees them + CHECK(away < 60.0); + // and sideways: about 4.5 cm, which a platform edge or the panels of a level crossing laid on the design are off the rails by + CHECK(aside < 50.0); } TEST_CASE("uneven track: a place strays the same every time") @@ -136,11 +146,11 @@ TEST_CASE("uneven track: a place strays the same every time") // no random numbers: changing these changes how every uneven track in every scenery looks glm::dvec3 const place{1234.5, 0.0, -678.9}; auto const stray{track_uneven::field(place)}; - CHECK(stray.x == doctest::Approx(0.309777548158).epsilon(1e-9)); - CHECK(stray.y == doctest::Approx(0.311350299745).epsilon(1e-9)); - CHECK(stray.z == doctest::Approx(-0.328429734019).epsilon(1e-9)); - CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.53 * -0.178598957983).epsilon(1e-9)); - CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.53 * -0.868291889902).epsilon(1e-9)); + CHECK(stray.x == doctest::Approx(0.158385385505).epsilon(1e-9)); + CHECK(stray.y == doctest::Approx(0.356190053667).epsilon(1e-9)); + CHECK(stray.z == doctest::Approx(0.200372098150).epsilon(1e-9)); + CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.35 * -0.178598957983).epsilon(1e-9)); + CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.35 * -0.868291889902).epsilon(1e-9)); } TEST_CASE("uneven track: tracks laid towards each other meet at one cant") diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 48d10e8b1..458b79eed 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -2,9 +2,15 @@ #include "doctest.h" #include "scratch.h" +#include +#include + #include "utilities/Globals.h" #include "utilities/utilities.h" +#include +#include + // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their // oddities included. the ones which look like mistakes are listed in COVERAGE.md. the helpers which read from a // parser (LoadPoint, the sets, the map) are in test_parser.cpp @@ -112,16 +118,31 @@ TEST_CASE("utilities: clearing a flag needs all of its bits set") { TEST_CASE("utilities: random whole numbers are within the bounds, both included, given in any order") { std::set seen; for (auto draw{0}; draw < 200; ++draw) { - auto const value{Random(3, 7)}; + auto const value{RandomInt(3, 7)}; CHECK(value >= 3); CHECK(value <= 7); seen.insert(value); - auto const swapped{Random(7, 3)}; + auto const swapped{RandomInt(7, 3)}; CHECK(swapped >= 3); CHECK(swapped <= 7); } CHECK(seen.size() == 5); - CHECK(Random(5, 5) == 5); + CHECK(RandomInt(5, 5) == 5); +} + +TEST_CASE("utilities: whole-number bounds still give a real number in between") { + // the wind, the wheel flats, the truck hunting and the tachometer draw with whole-number bounds + static_assert(std::is_same_v); + auto fractions{0}; + for (auto draw{0}; draw < 50; ++draw) { + auto const value{Random(0, 4)}; + CHECK(value >= 0.0); + CHECK(value <= 4.0); + if (value != std::floor(value)) { + ++fractions; + } + } + CHECK(fractions > 0); } TEST_CASE("utilities: random numbers are within the bounds given in any order") { @@ -154,17 +175,37 @@ TEST_CASE("utilities: random numbers are within the bounds given in any order") } TEST_CASE("utilities: the same seed gives the same random numbers") { - std::vector first; + std::vector first; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - first.push_back(Random(0, 1000000)); + first.push_back(Random(0.0, 1000000.0)); } - std::vector second; + std::vector second; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - second.push_back(Random(0, 1000000)); + second.push_back(Random(0.0, 1000000.0)); } CHECK(first == second); + std::vector localfirst; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localfirst.push_back(RandomInt(0, 1000000)); + } + std::vector localsecond; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localsecond.push_back(RandomInt(0, 1000000)); + } + CHECK(localfirst == localsecond); +} + +TEST_CASE("utilities: the whole numbers are drawn from the local engine, not from that of the run's seed") { + // the trivia of the loading screen is drawn before a network client gets the seed of the session + Global.random_engine.seed(5); + auto const first{Random()}; + Global.random_engine.seed(5); + RandomInt(0, 9); + CHECK(Random() == first); } TEST_CASE("utilities: the local random numbers have an engine of their own") { @@ -681,12 +722,30 @@ TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one" CHECK(Round(-2.5) == -2); } -TEST_CASE("utilities: a value is kept within bounds, given in any order") { +TEST_CASE("utilities: a value is kept within bounds; inverted bounds give the upper one, as the old clamp did") { CHECK(safe_clamp(5, 0, 3) == 3); - CHECK(safe_clamp(5, 3, 0) == 3); - CHECK(safe_clamp(-1, 3, 0) == 0); - CHECK(safe_clamp(2.0, 3.0, 1.0) == 2.0); + CHECK(safe_clamp(-1, 0, 3) == 0); + CHECK(safe_clamp(2, 0, 3) == 2); CHECK(safe_clamp(2.0, 2.0, 2.0) == 2.0); + // inverted bounds: always the upper bound, whatever the value + CHECK(safe_clamp(5, 3, 0) == 0); + CHECK(safe_clamp(-1, 3, 0) == 0); + CHECK(safe_clamp(2.0, 3.0, 1.0) == 1.0); + // NaN as the old clamp had it: a NaN value stays NaN, a NaN bound doesn't clamp + auto const notanumber{std::numeric_limits::quiet_NaN()}; + CHECK(std::isnan(safe_clamp(notanumber, 0.0, 1.0))); + CHECK(safe_clamp(2.0, 0.0, notanumber) == 2.0); + CHECK(safe_clamp(-1.0, notanumber, 1.0) == -1.0); + // what the helper gives for arguments in the order and of the signs of two calls (these checks don't call + // them): the AI braking test, whose demand is the stronger of the two (negative) bounds, as up to 26.05.1 + double const threshold{-0.45}; + CHECK(safe_clamp(0.3, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + CHECK(safe_clamp(-0.6, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + // and the bump at a rail joint, 0 in place of the value as up to 26.05.1: the figure is capped from above + // only, and above 68% of the top speed it is negative + CHECK(safe_clamp(0.0, 160.0, 160.0 - (150.0 + 160.0 * 0.32)) == doctest::Approx(-41.2)); + CHECK(safe_clamp(0.0, 4.0, -0.5) == -0.5); + CHECK(safe_clamp(0.0, 4.0, 5.0) == 4.0); } TEST_CASE("utilities: a value is wrapped into a range, as an angle into the full circle") { diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index 81df2ce2a..ba60be900 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -38,10 +38,10 @@ CURVE_STEP = 1.0 / 2500.0 # a difference of curvature that counts as a change, RISE = 0.0273 * 4.5 # how fast pressure lifts a pantograph, m/s, by TDynamicObject::Update GAP_MOST = 0.006 # the gap to the wire allowed; at 0.01 m the voltage goes and the main breaker trips OVERSPEED = 1.1 # a driver can go this much over the speed of the track -# as up_waves and the dip of the joints in world/TrackUneven.h -STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0 +# as up_waves, stray_up_per_mm and the dip of the joints in world/TrackUneven.h +STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00229, 0.4, 3.0 GOLDEN = math.pi * (3.0 - math.sqrt(5.0)) -UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))] +UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0), (.0761, .1058, .1393, .176, .2175, .2651, .3215, .3887)))] TOKEN = re.compile(r"//[^\n]*|\S+") NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$") diff --git a/track_uneven_doc.md b/track_uneven_doc.md index e4822b971..1899abdc3 100644 --- a/track_uneven_doc.md +++ b/track_uneven_doc.md @@ -46,15 +46,17 @@ A track with `uneven 18` measures as follows (`tests/unit/test_track_uneven.cpp` | parameter | result | Id-14 | |--------------------------|--------|-----------| | vertical irregularities | 18 mm | 18 mm | -| horizontal irregularities | 19 mm | 17 mm | +| horizontal irregularities | 17 mm | 17 mm | | twist on a 5 m base | 15 mm | 16 mm | | gauge | ±10 mm | +10/-8 mm | -| cross level | 20 mm | 20 mm | -| J index | 6.1 | 5.3 | +| cross level | 21 mm | 20 mm | +| J index | 5.7 | 5.3 | + +Id-14 only gives the scale of the value: how a track at that value measures. What the waves look like follows the track spectra of the literature, see "How it works". ## How it works -Unevenness is a displacement field that depends on the position on the map, made of waves 5-42 m long. Vertically there are fewer short waves, so the rails come near the peak value more often, and there are also waves of 47-83 m: they hardly count on the 10 m chord, the body rises and falls on them, and a pantograph keeps up with them. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. +Unevenness is a displacement field that depends on the position on the map, made of waves 7-90 m long sideways and 8-110 m long vertically, about the bands D1-D3 of EN 13848. Their heights follow the shape of the track spectra of the US FRA and of ORE B176 (the German spectrum): a power spectral density of `Wc² / (W² (W² + Wc²))`, `Wc = 0.8245 rad/m`, so the longer a wave, the higher it is. Most of the height is in the long waves: they hardly count on the 10 m chord, the body rises and falls on them slowly, and the cab hardly feels them. At `uneven 18` a track goes up to about 5 cm up or down and about 4.5 cm sideways off its design over the long waves, and the short ones of 7-10 m, the ones the cab shakes on, are a few millimetres. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. Each component joins separately: @@ -67,7 +69,7 @@ The ends of joined paths meet in the middle between them, with one vector across The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the body and the cab shake follow the unevenness. The slope of the ballast takes up the difference, and its foot stays as designed, on the ground. -Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres. +Models from includes (e.g. switch drives and timbers), platform edges, level crossing panels, the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres, sideways up to about 4.5 cm at `uneven 18`. On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before, as far as it has something to put in their place. It goes by the track under the vehicle, and on a switch by the path set and what its joined tracks allow. Dips at the joints and cross level replace nothing, as they don't shake the cab all the way along or sideways. On tracks with no unevenness everything works as before. @@ -83,7 +85,7 @@ On a track with unevenness the track itself shakes the cab, in place of two of t This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration. -A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. +A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 1150, for example 9.6 mm at 120 km/h, 16 mm at 70 km/h and 29 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. The physics takes the curve radius and the grade from the design, so unevenness doesn't change them. It adds only the cross level towards derailment, about 0.06 m/s² at `uneven 18` against a threshold of about 3.2 m/s². diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 90c206dfa..e920849b2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1410,6 +1410,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "crashdump.full") + { + ParseOne(Parser, CrashDumpFull); + return true; + } + if (token == "showsystemconsole") { ParseOne(Parser, ShowSystemConsole); @@ -1890,6 +1896,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); + export_as_text( Output, "crashdump.full", CrashDumpFull ); export_as_text( Output, "showsystemconsole", ShowSystemConsole ); export_as_text( Output, "logs.filter", DisabledLogTypes ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index ceb9948c4..3b1441240 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,6 +119,10 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; + // the dump written when the simulator crashes (Windows): a small one by default, with the stacks, the threads, the + // modules, the memory the stacks point to and the modules' data. "crashdump.full yes" writes all the memory of the + // simulator instead, as large as the memory it took + bool CrashDumpFull{ false }; // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" // never, and with no entry it is written along with the physics logs std::optional BlackBox; @@ -201,6 +205,12 @@ struct global_settings { bool EditorOrtho{ false }; float EditorOrthoExtent{ 150.f }; int EditorOrthoTracks{ 0 }; // the railway in the top view of the editor: 0 whole, 1 without the ballast, 2 the rails alone + // the free camera of the editor: its speed set in the View menu, the Ctrl multiplier of it, and in the top view whether it goes as far + // as the view reaches, so the map moves across the screen as fast zoomed in as out + bool EditorCameraOn{ false }; // the editor is on: its camera goes by the settings below + double EditorCameraSpeed{ 1.0 }; + double EditorCameraFast{ 30.0 }; + bool EditorCameraZoomed{ false }; GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury GLint iMaxCabTextureSize{ 4096 }; // largest allowed texture in vehicle cab int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index e0949aba6..f4032d808 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include @@ -115,6 +116,8 @@ void LogService() { std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); + // the stack of a crash on Linux goes to the end of this file + crash_signals::set_log_path(filename); } output << msg << "\n"; output.flush(); diff --git a/utilities/crashsignals.cpp b/utilities/crashsignals.cpp new file mode 100644 index 000000000..fa62e8955 --- /dev/null +++ b/utilities/crashsignals.cpp @@ -0,0 +1,234 @@ +/* +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 "utilities/crashsignals.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// the handler may only call what is safe in a signal: no allocation, no locks, no streams. so what it needs is +// kept in fixed buffers, filled in beforehand, and written with write() + +constexpr std::array crash_signal_list{SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT}; +// a handler that hangs (a crash inside the allocator or the loader, which backtrace() may need) ends this long after +constexpr unsigned int crash_report_timeout_seconds{5}; + +// a text of fixed size, filled outside the handler and read in it +template struct fixed_text { + std::array text{}; + std::atomic ready{false}; + + void set(std::string_view const Text) { + ready = false; + auto const length{std::min(Text.size(), text.size() - 1)}; + std::copy_n(Text.data(), length, text.data()); + text[length] = '\0'; + ready = true; + } + char const *get() const { return ready ? text.data() : nullptr; } +}; + +fixed_text<1024> &log_path() { + static fixed_text<1024> path; + return path; +} + +fixed_text<256> &version_text() { + static fixed_text<256> version; + return version; +} + +// the stack the handler runs on, so an overflow of the main thread's own stack is reported too +std::array &alternate_stack() { + static std::array stack{}; + return stack; +} + +void write_all(int const File, std::string_view Text) { + while (false == Text.empty()) { + auto const written{::write(File, Text.data(), Text.size())}; + if (written <= 0) + return; + Text.remove_prefix(static_cast(written)); + } +} + +void write_hex(int const File, std::uintptr_t const Value) { + constexpr std::size_t digits{sizeof(Value) * 2}; + constexpr std::string_view hexdigits{"0123456789abcdef"}; + std::array text{'0', 'x'}; + for (std::size_t digit = 0; digit < digits; ++digit) + text[2 + digit] = hexdigits[(Value >> (4 * (digits - 1 - digit))) & 0xF]; + write_all(File, {text.data(), text.size()}); +} + +void write_decimal(int const File, int const Value) { + std::array text{}; + auto position{text.size()}; + auto rest{static_cast(Value < 0 ? -Value : Value)}; + do { + text[--position] = static_cast('0' + rest % 10); + rest /= 10; + } while (rest != 0 && position > 1); + if (Value < 0) + text[--position] = '-'; + write_all(File, {text.data() + position, text.size() - position}); +} + +std::string_view signal_name(int const Signal) { + switch (Signal) { + case SIGSEGV: + return "SIGSEGV"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGABRT: + return "SIGABRT"; + default: + return "?"; + } +} + +// the signal being reported, for a report that hangs +std::atomic &crash_signal() { + static std::atomic signal{0}; + return signal; +} + +// a report that hangs is given up: the process ends by the signal of the crash, as it would have without the handler +void handle_report_timeout(int) { + auto const crashsignal{crash_signal().load()}; + raise(crashsignal); + // it is blocked while its own handler runs, which this one interrupted + sigset_t unblocked; + sigemptyset(&unblocked); + sigaddset(&unblocked, crashsignal); + sigprocmask(SIG_UNBLOCK, &unblocked, nullptr); +} + +struct crash_stack { + std::array frames{}; + int count{0}; +}; + +void write_report(int const File, int const Signal, siginfo_t const *Info, crash_stack const &Stack) { + write_all(File, "\nCrash: signal "); + write_decimal(File, Signal); + write_all(File, " ("); + write_all(File, signal_name(Signal)); + write_all(File, ")"); + // the address of the fault; an abort has none + if (Signal != SIGABRT && Info != nullptr) { + write_all(File, " at address "); + write_hex(File, reinterpret_cast(Info->si_addr)); + } + write_all(File, "\n"); + if (auto const *version{version_text().get()}) { + write_all(File, "Version: "); + write_all(File, version); + write_all(File, "\n"); + } + write_all(File, "Stack (addr2line -f -C -e ):\n"); + backtrace_symbols_fd(Stack.frames.data(), Stack.count, File); +} + +void handle_crash_signal(int const Signal, siginfo_t *Info, void *) { + crash_signal() = Signal; + struct sigaction timeout{}; + timeout.sa_handler = handle_report_timeout; + sigemptyset(&timeout.sa_mask); + sigaction(SIGALRM, &timeout, nullptr); + alarm(crash_report_timeout_seconds); + + crash_stack stack; + stack.count = backtrace(stack.frames.data(), static_cast(stack.frames.size())); + + if (auto const *path{log_path().get()}) { + if (auto const log{::open(path, O_WRONLY | O_APPEND | O_CLOEXEC)}; log >= 0) { + write_report(log, Signal, Info, stack); + ::close(log); + } + } + write_report(STDERR_FILENO, Signal, Info, stack); + + // the handler was taken off as it was called (SA_RESETHAND): the signal does what it always did + raise(Signal); +} + +} // namespace + +namespace crash_signals { + +void install(std::string_view const Version) { + static std::atomic installed{false}; + if (installed.exchange(true)) + return; + + version_text().set(Version); + + // backtrace() loads what it needs on its first call, which allocates: done here, not in the handler + std::array warmup{}; + backtrace(warmup.data(), static_cast(warmup.size())); + + stack_t alternate{}; + alternate.ss_sp = alternate_stack().data(); + alternate.ss_size = alternate_stack().size(); + sigaltstack(&alternate, nullptr); + + struct sigaction action{}; + action.sa_sigaction = handle_crash_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESETHAND; + // another crash signal of the same thread waits until the report is written, rather than starting a second one in + // its middle (a fault that comes while it is blocked still ends the process). a crash of another thread at the + // same moment may still write its report alongside + sigemptyset(&action.sa_mask); + for (auto const crashsignal : crash_signal_list) + sigaddset(&action.sa_mask, crashsignal); + for (auto const crashsignal : crash_signal_list) + sigaction(crashsignal, &action, nullptr); +} + +void set_log_path(std::string_view const Path) { + // whole, so the report finds the file wherever the simulator stands then + std::error_code error; + auto const path{std::filesystem::absolute(std::filesystem::path{Path}, error)}; + log_path().set(error ? std::string{Path} : path.string()); +} + +} // namespace crash_signals + +#else + +namespace crash_signals { + +void install(std::string_view) {} +void set_log_path(std::string_view) {} + +} // namespace crash_signals + +#endif diff --git a/utilities/crashsignals.h b/utilities/crashsignals.h new file mode 100644 index 000000000..feb526869 --- /dev/null +++ b/utilities/crashsignals.h @@ -0,0 +1,25 @@ +/* +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 + +// the stack of a crash on Linux, where no dump is written: a signal of a fault (SIGSEGV, SIGBUS, SIGFPE, SIGILL) or +// SIGABRT writes the stack of the thread that took it to the log and to the standard error, which the starter shows, +// and then ends the simulator as the signal always did (a core dump where the system makes one). the addresses are +// read with addr2line on the eu07 file of the same version, which carries its symbols. elsewhere it does nothing +namespace crash_signals { + +// sets the handlers up, once. Version goes into the report, to tell which eu07 file the addresses belong to +void install(std::string_view Version); +// the log file the report is added to, once the log has opened it +void set_log_path(std::string_view Path); + +} // namespace crash_signals diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index d37ea69e7..208fc7b01 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -14,22 +14,13 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include #include -#include -#include #include -#include #include #include #include -#if defined(__linux__) -#include -#include -#endif - physicslog_writer PhysicsLogs; namespace { @@ -76,64 +67,14 @@ void tell(std::string const &Text) noexcept { } } -// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the -// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking -// when there are hundreds of them -void lower_disk_priority() noexcept { -#ifdef _WIN32 - // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of - // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a - // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without - // end. a thread which can't have it writes as it did before - static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); -#elif defined(__linux__) && defined(SYS_ioprio_set) - // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the - // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has - constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 - constexpr int classbesteffort{2}; - constexpr int classshift{13}; - constexpr int lowest{7}; - static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); -#endif -} - } // namespace -void physicslog_values::append_to(std::string &Text) const { - std::ostringstream line; - line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " - << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " - << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " - << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " - << wateraux << " " << vehiclespeed << "\r\n"; - Text.append(line.str()); -} - -void physicslog_writer::pending::to_text() { - if (values.empty()) - return; - // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was - std::string lines; - for (auto const &line : values) - line.append_to(lines); - text.append(lines); - values.clear(); -} - -physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : - m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { try { stop(); - // the writings left behind by the stops use the object, which goes - std::vector> closings; - { - std::scoped_lock lock{m_mutex}; - closings.swap(m_closings); - } - for (auto const &closing : closings) - closing.wait(); } catch (...) { // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse } @@ -145,33 +86,18 @@ void physicslog_writer::begin(std::string const &Name, std::string_view const He lines.fresh = true; lines.header.assign(Header); lines.text.clear(); - lines.values.clear(); start(); } void physicslog_writer::append(std::string const &Name, std::string_view const Line) { std::scoped_lock lock{m_mutex}; - auto &lines{m_pending[Name]}; - // after the lines given as values before it - lines.to_text(); - lines.text.append(Line); + m_pending[Name].text.append(Line); start(); } -void physicslog_writer::append(std::string const &Name, physicslog_values Values) { - std::scoped_lock lock{m_mutex}; - m_pending[Name].values.push_back(std::move(Values)); - start(); -} - -void physicslog_writer::put_first(std::string const &Name) { - std::scoped_lock lock{m_mutex}; - m_first.insert(Name); -} - void physicslog_writer::flush() { std::scoped_lock files{m_filemutex}; - write(writing::flush); + write(); } bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { @@ -180,7 +106,7 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { auto done{std::make_shared>()}; auto ended{done->get_future()}; std::thread([this, done] { - flush_safely(writing::flush); + flush_safely(); done->set_value(); }).detach(); return ended.wait_for(Timeout) == std::future_status::ready; @@ -189,16 +115,12 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { void physicslog_writer::stop() { std::jthread thread; bool itself; - closing_time closeby; { std::scoped_lock lock{m_mutex}; m_stopped = true; // taken by the first to stop, so it's joined once thread = std::move(m_thread); itself = m_writer == std::this_thread::get_id(); - // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun - // ends at the log at hand, leaving the others to it - closeby = closing_begun(); } // the stop asked outside the lock, which waking the writer takes if (thread.joinable()) @@ -209,55 +131,9 @@ void physicslog_writer::stop() { thread.detach(); return; } - if (close_aside(thread, closeby)) - return; - // no thread for it, out of memory say: written here, the logs past the time dropped all the same if (thread.joinable()) thread.join(); - flush_safely(writing::closing); -} - -physicslog_writer::closing_time physicslog_writer::closing_begun() { - std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); - // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the - // longer, nor give the writing of the first more of it - if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) - return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; - auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; - m_closeby = closeby.time_since_epoch().count(); - return {closeby, true}; -} - -bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { - // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which - // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, - // the writing with it - auto started{false}; - try { - auto done{std::make_shared>()}; - std::shared_future const closing{done->get_future()}; - { - std::scoped_lock lock{m_mutex}; - m_closings.push_back(closing); - } - // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it - std::thread([this, done, writer = std::move(Thread)]() mutable { - if (writer.joinable()) - writer.join(); - flush_safely(writing::closing); - done->set_value(); - }).detach(); - started = true; - // told by the stop which gave the time, not again by one after it - if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) - tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", - std::chrono::duration{m_closingwait}.count())); - return true; - } catch (...) { - // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun - // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it - return started; - } + flush_safely(); } std::filesystem::path physicslog_writer::file(std::string const &Name) const { @@ -279,12 +155,6 @@ std::string physicslog_writer::shown(std::string const &Name) const { return m_shownfolder + '/' + file_name(Name); } -std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { - // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the - // waits growing with no end, and a crash would lose more of them - return std::clamp(Took * 3, Interval, Interval * 5); -} - void physicslog_writer::start() { if (m_stopped || m_thread.joinable()) return; @@ -293,199 +163,101 @@ void physicslog_writer::start() { } void physicslog_writer::run(std::stop_token const &Stop) { - lower_disk_priority(); // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is // either about to wait, and sees the stop, or waiting already std::stop_callback const wake{Stop, [this] { { std::scoped_lock lock{m_mutex}; } m_wake.notify_all(); }}; - std::chrono::steady_clock::duration wait{m_interval}; while (false == Stop.stop_requested()) { { std::unique_lock lock{m_mutex}; // woken early only to stop, which writes the rest itself - if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + if (m_wake.wait_for(lock, m_interval, [&Stop] { return Stop.stop_requested(); })) return; } - auto const start{std::chrono::steady_clock::now()}; - // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's - auto const logs{flush_safely(writing::thread)}; - auto const took{std::chrono::steady_clock::now() - start}; - wait = wait_after(m_interval, took); - if (wait > m_interval && false == m_slowtold) { - m_slowtold = true; - using seconds = std::chrono::duration; - try { - WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " - "written less often from now on, every {:.1f} s at most", - logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); - } catch (...) { - // out of memory for a line of the log: the logs are written all the same - } - } + flush_safely(); } } -std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { +void physicslog_writer::flush_safely() noexcept { try { - std::scoped_lock files{m_filemutex}; - return write(Mode); + flush(); } catch (std::exception const &Error) { tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); } catch (...) { tell("Bad physics log: the writing failed, the lines taken for it are lost"); } - return 0; } -bool physicslog_writer::past_closing() const { - auto const closeby{m_closeby.load()}; - return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; -} - -void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { - // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it - auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; - for (auto &[name, lines] : Failed) { - // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as - // text they go before what came since - try { - lines.to_text(); - } catch (std::exception const &) { - // kept as values, below - } - keep_last(lines.text, most); - } - // tried again the next time, before what came since; a file held by another program for a while doesn't lose - // them, nor its header - std::scoped_lock lock{m_mutex}; - for (auto &[name, lines] : Failed) - put_back(name, lines); - for (auto *log : Left) - put_back(log->first, log->second); -} - -void physicslog_writer::put_back(std::string const &Name, pending &Lines) { - auto &now{m_pending[Name]}; - // a log begun anew since drops them - if (now.fresh) - return; - // the lines in the order given: those kept, then those come since, as text and as values. values kept before text - // come since are made into text first, as those before a line given as text are; values which can't be, out of - // memory, are dropped then, as the order can't be kept otherwise - if (false == now.text.empty() && false == Lines.values.empty()) { - try { - Lines.to_text(); - } catch (std::exception const &) { - Lines.values.clear(); - } - } - Lines.text.append(now.text); - // added at once, allocated first: one failing moves none of them - if (Lines.values.empty()) - Lines.values = std::move(now.values); - else - Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); - now = std::move(Lines); -} - -std::size_t physicslog_writer::write(writing const Mode) { +void physicslog_writer::write() { std::map taken; - std::set first; - std::vector *> order; { std::scoped_lock lock{m_mutex}; - if (m_pending.empty()) - return 0; - // a stop come before the thread's writing: the lines are all the closing's, left as they are - if (Mode == writing::thread && m_closeby.load() != 0) - return 0; - // had before the lines are taken: without the memory for it they're left for the next writing - first = m_first; - order.reserve(m_pending.size()); taken.swap(m_pending); } - auto const logs{taken.size()}; + if (taken.empty()) + return; std::error_code error; std::filesystem::create_directories(m_folder, error); - std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); - writing_order(order, first); std::map failed; - std::size_t dropped{0}; - std::size_t reached{0}; - for (auto *log : order) { - // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has - // them with the lines given since, those put first first - if (Mode == writing::thread && m_closeby.load() != 0) - break; - ++reached; - auto &[name, lines]{*log}; - // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer - if (Mode == writing::closing && past_closing()) { - ++dropped; + for (auto &[name, lines] : taken) { + if (lines.text.empty() && false == lines.fresh) + continue; + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + written = write_log(name, lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(name) > 0) + WriteLog("Physics log: " + shown(name) + " written again"); continue; } - if (false == write_taken(name, lines)) - failed.emplace(name, std::move(lines)); + if (m_failed.insert(name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(name) + ", its last lines are kept for the next try"); + failed.emplace(name, std::move(lines)); } - if (dropped > 0) - tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, - std::chrono::duration{m_closingwait}.count())); - // what is left of the order: the logs the thread hasn't come to - order.erase(order.begin(), order.begin() + static_cast(reached)); - if (false == failed.empty() || false == order.empty()) - keep(failed, order); - return logs; -} - -bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { - // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: - // the others are written still, and the writer goes on - auto written{false}; - std::string problem{"can't write"}; - try { - // the text of the lines given as values, here on the writer's thread rather than the simulation's - Lines.to_text(); - if (Lines.text.empty() && false == Lines.fresh) - return true; - written = write_log(Name, Lines); - } catch (std::exception const &Error) { - problem = std::string{"failed ("} + Error.what() + ") to write"; + if (failed.empty()) + return; + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / failed.size())}; + for (auto &[name, lines] : failed) + keep_last(lines.text, most); + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header. a log begun anew since drops them + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : failed) { + auto &now{m_pending[name]}; + if (now.fresh) + continue; + lines.text.append(now.text); + now = std::move(lines); } - if (written) { - if (m_failed.erase(Name) > 0) - WriteLog("Physics log: " + shown(Name) + " written again"); - return true; - } - if (m_failed.insert(Name).second) - ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); - return false; } bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { auto const path{file(Name)}; - // one write to the file: the header of a log begun with its lines, not the one after the other - std::string begun; - if (Lines.fresh) - begun = Lines.header + Lines.text; - std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; - // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". - // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines - // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't - // asked for the length before, one access less of hundreds of logs - std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; - if (false == stream.is_open()) - return false; - auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; - stream.write(text.data(), static_cast(text.size())); + std::error_code error; + // how long it was, to be cut back to if the lines are written in part only, a disk filling up say: else they'd be + // written twice, the next time + auto const before{Lines.fresh ? 0 : std::filesystem::file_size(path, error)}; + auto const existed{false == Lines.fresh && false == static_cast(error)}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; + if (stream.is_open()) { + if (Lines.fresh) + stream << Lines.header; + stream << Lines.text; + } stream.close(); if (false == stream.fail()) return true; - // a log begun is written anew from its header the next time anyway - if (false == Lines.fresh && before >= 0) { - std::error_code error; - std::filesystem::resize_file(path, static_cast(before), error); - } + if (existed) + std::filesystem::resize_file(path, before, error); return false; } diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 286df7e87..0f397d27c 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -9,12 +9,9 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include -#include #include #include #include -#include #include #include #include @@ -22,60 +19,18 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include - -// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which -// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty -// lines a second each. the columns as physicslog_header of the driver names them -struct physicslog_values { - double time{0.0}; - double wheelspeed{0.0}; - double acceleration{0.0}; - double couplerdistance{0.0}; - double couplerforce{0.0}; - double tractionforce{0.0}; - double frictionforce{0.0}; - double brakeforce{0.0}; - double brakepressure{0.0}; - double pipepressure{0.0}; - double motorcurrent{0.0}; - int mainctrl{0}; - int scndctrl{0}; - double brakectrl{0.0}; - double localbrake{0.0}; - int direction{0}; - std::string command; - double value1{0.0}; - double value2{0.0}; - int security{0}; - int wheelslip{0}; - double enginetemperature{0.0}; - double oiltemperature{0.0}; - double watertemperature{0.0}; - double wateraux{0.0}; - double vehiclespeed{0.0}; - - // the line, as the logs always had it, at the end of Text - void append_to(std::string &Text) const; -}; // the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's // has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, // each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the -// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk -// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next -// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the -// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind -// them. the closing waits for the writing a second at most (below) +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them. lines whose file can't +// be written, held by another program say, are kept for the next try: the last 64 MB of them all at most class physicslog_writer { public: - explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, - std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); physicslog_writer(physicslog_writer const &) = delete; physicslog_writer &operator=(physicslog_writer const &) = delete; - // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, - // global, never goes this way: the process ends with _Exit + // stops, writing what is kept ~physicslog_writer(); // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. @@ -83,20 +38,12 @@ public: void begin(std::string const &Name, std::string_view Header); // Line at the end of the log Name. a log not begun is added to as its file stands void append(std::string const &Name, std::string_view Line); - // the same, a line of the values, made into text by the writer's thread when it writes the log - void append(std::string const &Name, physicslog_values Values); - // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the - // tested trains, which a closing short of time would otherwise drop by the order of their names - void put_first(std::string const &Name); // writes what is kept, now void flush(); // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left // behind. for the end of the process, the files held up or the disk not answering bool flush_for(std::chrono::milliseconds Timeout); - // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by - // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a - // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with - // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a @@ -105,84 +52,36 @@ public: std::filesystem::path file(std::string const &Name) const; // the same, for the log of the simulator std::string shown(std::string const &Name) const; - // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long - // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the - // logs a quarter of the time rather than all of it, and their lines wait in memory the longer - static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); - // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: - // those put first (First) before the others, each in the order they were - template static void writing_order(std::vector &Logs, std::set const &First) { - std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); - } private: - // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the - // closing's, which drops the logs past the time the stop gives it - enum class writing { flush, thread, closing }; - - // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way - struct closing_time { - std::chrono::steady_clock::time_point by; - bool fresh{true}; - }; - struct pending { bool fresh{false}; // its file is to be emptied first, and the header written into it std::string header; std::string text; - // the lines given as values since, after the text: made into text when written - std::vector values; - - // the lines of the values at the end of the text - void to_text(); }; - // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held - closing_time closing_begun(); - // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no - // thread could be had for it, out of memory say; Thread may be the writer still then - bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; // the thread, on the first line given, unless stopped. called with m_mutex held void start(); void run(std::stop_token const &Stop); // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the - // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. - // returns: the number of logs there were to write - std::size_t flush_safely(writing Mode) noexcept; - // called with m_filemutex held. returns: the number of logs there were to write - std::size_t write(writing Mode); - // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if - // it wasn't, its lines to be kept for the next try - bool write_taken(std::string const &Name, pending &Lines); - // whether the time a stop gave the writing is over - bool past_closing() const; - // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, - // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as - // they were taken: their values are made into text by that writing, which drops them past its time, not on the way - // unless text was given since - void keep(std::map &Failed, std::vector *> const &Left); - // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held - void put_back(std::string const &Name, pending &Lines); + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since + void flush_safely() noexcept; + // called with m_filemutex held + void write(); // the lines of the log Name written into its file. returns: true if they all were bool write_log(std::string const &Name, pending const &Lines) const; std::filesystem::path const m_folder; std::string const m_shownfolder; std::chrono::milliseconds const m_interval; - std::chrono::milliseconds const m_closingwait; - // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop - std::atomic m_closeby{0}; std::mutex m_mutex; // the lines kept and the thread std::map m_pending; - std::set m_first; // the logs put first bool m_stopped{false}; std::condition_variable m_wake; std::jthread m_thread; std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it - std::vector> m_closings; // the writings of the stops, which may outlast them std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order std::set m_failed; // the logs whose file couldn't be written, told once - bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own }; // the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index edc694852..61a059e35 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -150,11 +150,11 @@ double Random(double min, double max) return dist(Global.random_engine); } -int Random(int min, int max) +int RandomInt(int min, int max) { if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB) std::uniform_int_distribution dist(min, max); - return dist(Global.random_engine); + return dist(Global.local_random_engine); } std::uint64_t true_random_seed() diff --git a/utilities/utilities.h b/utilities/utilities.h index 25ee3882c..0cefb6c11 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -64,7 +64,12 @@ inline long Round(double const f) } double Random(double a, double b); -int Random(int min, int max); +// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number +// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the +// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it +// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would +// put that engine out of step with the other machines of a network session +int RandomInt(int min, int max); /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. @@ -293,17 +298,18 @@ template bool is_equal(T const &Left, T const &Right, T const Epsil return Left == Right; } -// Tolerant clamp. Unlike std::clamp, this does NOT invoke undefined behaviour when -// the bounds are inverted (Lo > Hi) - it normalizes them instead. This restores the -// pre-refactor behaviour of the old custom clamp() for code paths where the bounds are -// computed at runtime and can legitimately cross (e.g. AI acceleration/braking limits, -// physics jolt calculations), where std::clamp's UB produced wrong results. +// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike +// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted +// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted +// bounds give the upper bound, as the old clamp() did. Every call of the old clamp() +// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are +// computed from such values) uses it, so it gives what it gave before the move to +// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same. +// New code uses std::clamp. template constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi ) { - return ( Hi < Lo ) - ? std::clamp( Value, Hi, Lo ) - : std::clamp( Value, Lo, Hi ); + return std::min( std::max( Value, Lo ), Hi ); } // keeps the provided value in specified range 0-Range, as if the range was circular buffer diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index e2fe58464..fe1a85c9a 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -62,6 +62,30 @@ TCamera::OnCommand( command_data const &Command ) { // threshold position on stick between walk lerp and walk/run lerp auto const stickthreshold = 2.0 / 3.0; + // the free camera of the editor as fast as its View menu sets it, Ctrl by the multiplier set there, in the top view by how far it reaches + auto editorscale { 1.0 }; + auto editorfast { -1.0 }; + if( Global.EditorCameraOn && m_owner == nullptr ) { + editorscale = Global.EditorCameraSpeed; + if( Global.EditorOrtho && Global.EditorCameraZoomed ) { + editorscale *= std::clamp( static_cast( Global.EditorOrthoExtent ) / 150.0, 0.02, 200.0 ); + } + editorfast = Global.EditorCameraFast; + } + // how many times faster the fast command of a move makes it: the editor's own, or the free fly's (Default) and the cab's (Cab) + auto const fastness = [&]( bool const Fast, double const Editor, double const Default, double const Cab ) { + if( false == Fast ) { + return 1.0; + } + if( editorfast > 0.0 ) { + return Editor; + } + if( false == FreeFlyModeFlag ) { + return 1.0; + } + return m_owner == nullptr ? Default : Cab; + }; + bool iscameracommand { true }; switch( Command.command ) { @@ -82,7 +106,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::movehorizontalfast ? m_owner == nullptr ? 30.0 : 5.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::movehorizontalfast, editorfast, 30.0, 5.0 ); // left-right m_moverate.x = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -101,7 +125,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::moveverticalfast ? m_owner == nullptr ? 10.0 : 3.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::moveverticalfast, std::max( 1.0, editorfast / 3.0 ), 10.0, 3.0 ); // up-down m_moverate.y = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -192,9 +216,12 @@ void TCamera::Update() bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { + // the roll (z) is multiplied in first, so it acts last, about the line of sight: the sway of the cab tilts the view + // the same way wherever the head is turned, as it did in 26.05. the order matters only with a roll (the cab shake, + // or the angles of a camera entry of the scenery) + Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia - Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie if( m_owner != nullptr && false == DebugCameraFlag ) { diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 2b3633433..99c6a951e 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" @@ -212,6 +213,7 @@ void TSpeedPos::Clear() fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; fDist = 0.0; + bSeenAhead = false; vPos = glm::dvec3(0, 0, 0); trTrack = nullptr; // brak wskaźnika }; @@ -328,6 +330,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -413,9 +418,18 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } +// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] +constexpr double SeenAheadTolerance { 5.0 }; + bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) { // zapamiętanie zdarzenia fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the + // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head + // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than + // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't + // be told from one stopped just short of it, which really passes the signal if it goes on + bSeenAhead = ( dist >= -SeenAheadTolerance ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -910,6 +924,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { if( Passedbefore || false == TestFlag( Point.iFlags, spElapsed ) + || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -2346,10 +2361,10 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, } TableClear(); - // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line - // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles - // are made passive before it starts, so they get no file with only the header - if( WriteLogFlag && false == drives_road_vehicle() ) { + // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every + // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive + // before it starts, so they get no file with only the header + if( WriteLogFlag ) { begin_physicslog(); } @@ -5387,38 +5402,38 @@ std::string_view TController::physicslog_header() { "\r\n"; } -physicslog_values TController::physicslog_line() const { - // the values only: the writer of the logs makes them into text on its own thread - physicslog_values line; - line.time = ElapsedTime; - line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); - line.acceleration = mvControlling->AccS; - line.couplerdistance = mvOccupied->Couplers[1].Dist; - line.couplerforce = mvOccupied->Couplers[1].CForce; - line.tractionforce = mvOccupied->Ft; - line.frictionforce = mvOccupied->Ff; - line.brakeforce = mvOccupied->Fb; - line.brakepressure = mvOccupied->BrakePress; - line.pipepressure = mvOccupied->PipePress; - line.motorcurrent = mvControlling->Im; - line.mainctrl = static_cast(mvControlling->MainCtrlPos); - line.scndctrl = static_cast(mvControlling->ScndCtrlPos); - line.brakectrl = mvOccupied->fBrakeCtrlPos; - line.localbrake = mvOccupied->LocalBrakePosA; - line.direction = static_cast(mvControlling->DirActive); - line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); - line.value1 = mvOccupied->CommandIn.Value1; - line.value2 = mvOccupied->CommandIn.Value2; - line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); - line.wheelslip = static_cast(mvControlling->SlippingWheels); - // floats, as the stream wrote them: widened to double - line.enginetemperature = mvControlling->dizel_heat.Ts; - line.oiltemperature = mvControlling->dizel_heat.To; - line.watertemperature = mvControlling->dizel_heat.temperatura1; - line.wateraux = 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 - line.vehiclespeed = mvOccupied->V * 3.6; - return line; +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << ElapsedTime << " " + << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " + << mvControlling->AccS << " " + << mvOccupied->Couplers[1].Dist << " " + << mvOccupied->Couplers[1].CForce << " " + << mvOccupied->Ft << " " + << mvOccupied->Ff << " " + << mvOccupied->Fb << " " + << mvOccupied->BrakePress << " " + << mvOccupied->PipePress << " " + << mvControlling->Im << " " + << int(mvControlling->MainCtrlPos) << " " + << int(mvControlling->ScndCtrlPos) << " " + << mvOccupied->fBrakeCtrlPos << " " + << mvOccupied->LocalBrakePosA << " " + << int(mvControlling->DirActive) << " " + << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " + << mvOccupied->CommandIn.Value1 << " " + << mvOccupied->CommandIn.Value2 << " " + << int(mvControlling->SecuritySystem.is_blinking()) << " " + << int(mvControlling->SlippingWheels) << " " + << mvControlling->dizel_heat.Ts << " " + << mvControlling->dizel_heat.To << " " + << mvControlling->dizel_heat.temperatura1 << " " + << 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"; + return line.str(); } void TController::begin_physicslog() @@ -8213,54 +8228,6 @@ 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 @@ -8287,43 +8254,19 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( 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 } ); - } + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // 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 fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { return; @@ -8374,7 +8317,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { AccDesired = ( BrakeSystem == TBrakeSystem::Pneumatic ? // cast iron blocks grip harder as the train comes to a stand - shaped_braking_demand( + braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 113be3b94..0aaf70707 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,7 +20,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" -#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -165,6 +164,7 @@ class TSpeedPos int iFlags{ spNone }; // flagi typu wpisu do tabelki bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) + bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train glm::dvec3 vPos; // współrzędne XYZ do liczenia odległości struct { @@ -739,22 +739,17 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } - // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with - // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. - // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + // the physics log (physicslog/.dat): the name of its file without the extension, its first line and + // a line of it as the vehicle is now, each with its line end. the black box keeps the lines of the vehicle the + // user is in, to write its log at the end when the logs of all the vehicles are off std::string const &physicslog_name() const { return VehicleName; } - // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with - // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of - // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes - // the log of one the user is in + // whether it writes its physics log itself: all with "physicslog yes", with "physicslog.trains yes" one who drives + // rail vehicles. a driver made primary later begins its log then bool writes_physicslog() const { - return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } - // a driver of a road vehicle; not one of no vehicle - bool drives_road_vehicle() const { - return mvOccupied != nullptr && is_car(); } + return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); - physicslog_values physicslog_line() const; + std::string physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index ce94a0609..7a301930a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -1162,7 +1163,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) continue; } - auto const dist { std::clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -2446,6 +2447,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ShakeSpring.Init( 125.0 ); BaseShake = baseshake_config {}; ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; // McZapkie-250202 /* @@ -2604,7 +2606,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = std::clamp( + fAxleDist = safe_clamp( std::max( MoverParameters->BDist, MoverParameters->ADist ), 0.2, //żeby się dało wektory policzyć MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" @@ -3202,7 +3204,7 @@ TDynamicObject::update_load_offset() { 0.0 : 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, loadpercentage * 0.01, 1.0 ) ); + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void @@ -3849,20 +3851,21 @@ bool TDynamicObject::Update(double dt, double dt1) // crude bump simulation, drop down on even axles, move back up on // the odd ones // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - double const headroom = std::clamp( - MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ), - 0.0, MoverParameters->Vmax ); + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { - double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1); + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); MoverParameters->AccS += accHorizontal; MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } ++axleindex; @@ -8337,6 +8340,8 @@ void TDynamicObject::OverheadTrack(float o) void TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu @@ -8461,9 +8466,32 @@ TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int con std::pair TDynamicObject::shake_angles() const { + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + return { - std::atan( ShakeState.velocity.x * BaseShake.angle_scale.x ), - std::atan( ShakeState.velocity.z * BaseShake.angle_scale.z ) }; + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } void diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index db427e34d..4db7d32c3 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -925,6 +925,11 @@ public: glm::dvec3 velocity{}; // current shaking vector glm::dvec3 offset{}; // overall shake-driven offset from base position } ShakeState; + shake_state ShakeStateBefore; // the state before the last step of update_shake + // the shake between the last two steps of update_shake: 0 the state before the last step, 1 the state after it. + // the steps are fixed and the frames aren't, so the camera takes the state at its own moment between the two + shake_state shake_between( double const Fraction ) const; + std::pair shake_angles( shake_state const &State ) const; glm::dvec3 modelShake; }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 24d3132f6..8bf948096 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9828,7 +9828,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = std::clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9836,7 +9836,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = std::clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9844,7 +9844,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = std::clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -11463,8 +11463,11 @@ glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const return Point; } - return {std::clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), std::clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - std::clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; } const TTrain::screenentry_sequence &TTrain::get_screens() diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp new file mode 100644 index 000000000..d39ee2868 --- /dev/null +++ b/vehicle/brakingcurve.cpp @@ -0,0 +1,86 @@ +/* +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/brakingcurve.h" + +#include +#include + +namespace braking_curve { + +double brake_table::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]); +} + +bool brake_table::known() const { + // a worked out table holds at least the rolling resistance term at every speed + return a0[size] > 0.0; +} + +double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { + + auto const travel = [Velocity, Target, Gravity, &Table](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 * Table.full_braking(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 * Table.full_braking(Velocity); + } + for (auto i{0}; i < 30; ++i) { + auto const middle{0.5 * (low + high)}; + (travel(middle) > Distance ? low : high) = middle; + } + return Gravity - high * Table.full_braking(Velocity); +} + +double demand(approach const &Approach, brake_table const *Pneumatictable) { + + // 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 + // both plans are made from the brake table of the consist; with none (in shunting it isn't worked out, and planning + // from its zeroes would ask for no braking at all) the braking curve is the constant deceleration over the distance left + auto const *table{(Pneumatictable != nullptr) && Pneumatictable->known() ? Pneumatictable : nullptr}; + auto velocity{Approach.speed}; + auto distance{Approach.distance}; + if ((table != nullptr) && (Approach.acceleration > 0.0)) { + auto const horizon{Approach.speedup_horizon}; + velocity = Approach.speed + 3.6 * horizon * Approach.acceleration; + distance = std::max(0.5 * Approach.distance, Approach.distance - (Approach.speed + velocity) * 0.5 / 3.6 * horizon); + } + auto const brakingroom{std::max(distance - Approach.offset, std::min(distance, Approach.offset))}; + if ((table == nullptr) || (velocity <= Approach.target)) { + return (Approach.target * Approach.target - velocity * velocity) / (25.92 * brakingroom + 0.1); + } + // 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 ((Approach.acceleration <= 0.0) && (false == Approach.brake_applied)) { + // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + room = std::max(0.5 * brakingroom, brakingroom - Approach.speed / 3.6 * Approach.fill_horizon); + } + return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); +} + +} // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h new file mode 100644 index 000000000..6ed40d9bb --- /dev/null +++ b/vehicle/brakingcurve.h @@ -0,0 +1,54 @@ +/* +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 deceleration the AI asks for on its way down to a lower speed or a stop ahead, outside of the final +// approach (TController::adjust_desired_speed_for_braking_curve) +namespace braking_curve { + +// the deceleration table of the consist brake, by speed (TController::fBrake_a0, fBrake_a1). it is worked out +// for a train only (Obey_train, Bank); in shunting it stays at zero +struct brake_table { + double const *a0; // deceleration at handle position 1, by speed; a0[1..size] + 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 Kmh) const; + // whether the table is worked out + bool known() const; +}; + +// 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 +// table says it does (cast iron blocks grip harder as the train slows) +double shaped_demand(double Velocity, double Target, double Distance, double Gravity, brake_table const &Table); + +// where the train is on its way down to Target +struct approach { + double speed; // present speed in the direction of travel [km/h] + double target; // speed to get down to [km/h] + double distance; // to where the speed is to be down [m] + double offset; // the braking point that far short of it [m] + double gravity; // tangential acceleration of the gradient [m/s2], negative uphill + double acceleration; // present acceleration of the train [m/s2] + bool brake_applied; // the train brake handle is past running + double speedup_horizon; // how long the present acceleration lasts while speeding up [s] + double fill_horizon; // how long the brake takes to fill once applied [s] +}; + +// acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake +// (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has +// responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at +// zero, as in shunting) it is the constant deceleration over the distance left +double demand(approach const &Approach, brake_table const *Pneumatictable); + +} // namespace braking_curve diff --git a/world/Segment.cpp b/world/Segment.cpp index 5e0f47116..1398b3347 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -439,7 +439,10 @@ glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const glm::dvec3 result { 0.0 }; if( m_setting.uneven ) { auto const field { track_uneven::field( Point ) }; - result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result = glm::dvec3 { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); } if( m_setting.buckled && m_pieces.empty() ) { @@ -493,7 +496,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } @@ -532,7 +535,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist From f15ea40575cc4062e6e8bea01e917dca431b46ee Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 22 Nov 2026 19:23:40 +0100 Subject: [PATCH 11/22] test(scripting): the image memory test makes fewer images, to finish in time under coverage (#427) The dropped images were 20 of 64 MB, each filled pixel by pixel. Under the GCC -O0 --coverage build that sometimes took longer than the 20 s a screen has to draw, so the check got -1. 4 dropped images, twice the memory of a screen, still prove that dropped images don't count. --- tests/unit/test_script_screen_host.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 6add4f008..dc1cfa2f8 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1239,7 +1239,10 @@ return { } )"}; -// white when the images a screen holds are held to its memory, and the images it dropped don't count +// white when the images a screen holds are held to its memory, and the images it dropped don't count. an image of +// 4096 x 4096 is 64 MB, half the memory of a screen: the second one kept is refused, and the 4 dropped ones (twice +// the memory) would be refused too if the dropped ones counted. no more of them: each is filled pixel by pixel, slowly +// in the coverage build (GCC -O0 --coverage), and with 20 of them the screen sometimes didn't draw in its 20 s there constexpr std::string_view image_memory_script{R"( local kept = {} local ok, message = pcall(function() @@ -1248,7 +1251,7 @@ end) local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 kept = nil local dropped = pcall(function() - for i = 1, 20 do local image = eu07.image(4096, 4096) end + for i = 1, 4 do local image = eu07.image(4096, 4096) end end) return { render = function(state) From 3c3c773ff46080b697c7b788c7a7b62503c5d8df Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:11:07 +0100 Subject: [PATCH 12/22] test(scenarios): the buckle cases run with physics.derailment new (#423) * test(scenarios): the buckle cases run with physics.derailment new eu07_td_buckle_derails waits for the "derailed on buckled track" line, which only the criteria of physics.derailment new write. It was written with new as the default; since monitor is the default (0645096e) the criteria only log "derailment monitor: ... overturned at 46 km/h on track tdo_n222" and the train runs on to Przystanek, so the case failed. The case sets the mode itself now. eu07_td_buckle_event sets it too: under monitor its "no Bad driving" check said nothing about the criteria. * docs(scenarios): the buckle cases and the derailment mode they set --- tests/scenarios/README.md | 9 +++++++++ tests/scenarios/cases/eu07_td_buckle_derails.json | 4 ++-- tests/scenarios/cases/eu07_td_buckle_event.json | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 7e9ceef7c..f65d96fb2 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -278,6 +278,15 @@ pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the bl locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s. +The `eu07_td_buckle_*` cases (fragment `td_buckle_event.scn`) run the timetable train of +`td_timetable.scn` and buckle the curve `tdo_n222`, about 950 m ahead of it, with a `trackbuckle` +event of `vars.amplitude` at 10:35. Both have `physics.derailment new` in `ini`: the default, +`monitor`, leaves the decision to the legacy draw and only logs what the criteria would do +(`derailment monitor: ... overturned at 46 km/h on track tdo_n222`), so the train runs on to +Przystanek whatever the buckle. With 600 mm over a main lobe of 8 m the locomotive overturns on +the buckle at 46 km/h, 1036 m from the start (`Bad driving: ... derailed on buckled track`); with +30 mm it keeps on the rails and stops at Przystanek after 1400 m. + The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a `putvalues` event, `Crew: `: cab 1 or -1 puts an AI driver in cab A or B of the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json index 5caaa60b6..8506736a5 100644 --- a/tests/scenarios/cases/eu07_td_buckle_derails.json +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -1,5 +1,5 @@ { - "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: with physics.derailment new (the default, monitor, only logs what the criteria would do and the train runs on) the locomotive leaves the rails on the buckle and stops short of Przystanek.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_buckle_event.scn", @@ -7,7 +7,7 @@ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", "amplitude": "600 8" }, - "ini": ["gfxrenderer null"], + "ini": ["gfxrenderer null", "physics.derailment new"], "duration": 240, "timeout": 600, "checks": [ diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json index 192fa9b5a..13e0da7bc 100644 --- a/tests/scenarios/cases/eu07_td_buckle_event.json +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -1,5 +1,5 @@ { - "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek.", + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek, with physics.derailment new: the criteria decide, as in eu07_td_buckle_derails.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_buckle_event.scn", @@ -7,7 +7,7 @@ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", "amplitude": "30" }, - "ini": ["gfxrenderer null"], + "ini": ["gfxrenderer null", "physics.derailment new"], "duration": 240, "timeout": 600, "checks": [ From 677795e595ba45f7d13b8c26ea0014f4a3518a6e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:11:51 +0100 Subject: [PATCH 13/22] test(scenarios): brakes cut out once a train formed by coupling stands (#282) (#436) An EU07 couples on the run to a cut of 16 coaches with P alone and 8 wagons with G, 541 m, and runs it on as a train: a train on G, whose coaches have their brakes cut out (Cw-1 19.9). The inspector looks at the train at 4 km/h as it couples and leaves the cut-outs to reinspect_brakes(), which makes them as the train stands just after. Taking the driver off at 38 km/h shows it: the train stops at 0.27 m/s2 over 211 m, against 0.57 m/s2 over 99 m with every brake working (the second case, with ai.brakesetting.cw1 no). stops_driverless takes optional min_deceleration and max_deceleration. --- tests/scenarios/README.md | 22 +++++- ...07_td_reinspect_brakes_after_coupling.json | 69 ++++++++++++++++++ ..._td_reinspect_brakes_legacy_inspector.json | 71 +++++++++++++++++++ tests/scenarios/cases/td_reinspect_brakes.scn | 33 +++++++++ tests/scenarios/run.py | 17 +++-- 5 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json create mode 100644 tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json create mode 100644 tests/scenarios/cases/td_reinspect_brakes.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index f65d96fb2..b85f0f8cf 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -341,6 +341,23 @@ brake of the Vectron switched on), and `event0` of the track gives the driver `O starts up, charges the brake pipe and leaves on time (the stop after 209 s and 1393 m); without the `H` the pipe stays below 1 bar and the case ends as a standstill after 300 s. +`eu07_td_reinspect_brakes_after_coupling` (fragment `td_reinspect_brakes.scn`, eu07/maszyna#350 and #282) is about the +wagon inspector of the AI (`TController::AutoRewident()`) on a train formed by coupling. An EU07 stands cold on the line +from Stacja1 (`koniec`) and a cut stands 45 m ahead of it, braked, with nobody in it: 16 coaches with P alone (BDhpumn) +and next to the locomotive 8 empty wagons with G and P (401W), 541 m of wagons. `event0` of the locomotive's track gives +the driver `Shunt -3 3`, once: couple to the cut with the coupler and the brake hose and run it on as a train +(`Obey_train`), waiting for the way, which `event2` of `tdo_n231`, in front of the cut, gives as a `SetVelocity 40 40` +(no signal of the line is in sight). Over 500 m of wagons make it a train on G (Cw-1 §19.1), where the brake of a wagon +without G is cut out (§19.9). The inspector looks at the train as the AI couples, at 4 km/h (t=69 s), too fast for it to +cut a brake out, and leaves that for the next standstill: `reinspect_brakes()` cuts the 16 coaches out as the train stands +a moment later, its brakes applied by the empty pipe of the cut. Neither the physicslog nor the black box has the brakes +of the wagons, so the case tells by how the train brakes: `event2` of `tdo_n240` takes the driver off at 38 km/h, which +leaves the brake valve in the emergency position, and braked by the locomotive and the 8 wagons alone the train stops 29 s +and 211 m later, a mean deceleration of 0.27 m/s² (`stops_driverless` with `max_deceleration` 0.40). With every brake +working it stops at 0.57 m/s², 99 m: that is `eu07_td_reinspect_brakes_legacy_inspector`, the same run with the inspector +of the earlier releases (`ai.brakesetting.cw1 no`), which cuts no brake out, and also what a build whose +`reinspect_brakes()` does nothing gives for the first case, which then fails. The test passes 150 s after the driver goes. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission @@ -433,7 +450,10 @@ the row instead, logged by builds from this branch on. (1 m), `hold` (60 s): the black box has the vehicle lose its driver at `min_speed` or faster, stand `within` seconds later and stay within `max_creep` of where it stopped for the rest of the recording, or until it gets a driver again, at least `hold` seconds. The physicslog can't - tell: the driver writes it, so it ends when the driver goes. + tell: the driver writes it, so it ends when the driver goes. Optional `min_deceleration`, + `max_deceleration` (m/s²): the mean deceleration of that stop, from the speed the driver left at + and the way to the stop (v²/2s), has to be within them, e.g. a train some of whose brakes are + cut out stops slower. - `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the vehicle reach `min_speed` with that end leading (the physicslog speed has no direction). diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json new file mode 100644 index 000000000..be4b96feb --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json @@ -0,0 +1,69 @@ +{ + "description": "eu07/maszyna#350, #282: an EU07 on td.scn couples on the run (Shunt -3 3) to a cut standing on the line, 16 coaches with P alone and 8 empty wagons with G and P, 541 m of wagons, and runs it on as a train (Obey_train): a train on G (Cw-1 19.1), so the brakes of the coaches are to be cut out (19.9). The inspector looks at the train as it couples, at 4 km/h, and leaves the cut-outs for the standstill; reinspect_brakes() makes them as the train stands just after. The driver taken off at 38 km/h leaves the brake valve in the emergency position: braked by the locomotive and the 8 wagons alone the train stops at some 0.27 m/s2, over 210 m (with every brake working, 0.57 m/s2 over 99 m).", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 90, + "hold": 60, + "min_deceleration": 0.15, + "max_deceleration": 0.4 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json new file mode 100644 index 000000000..e3a03c2da --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json @@ -0,0 +1,71 @@ +{ + "description": "The train of eu07_td_reinspect_brakes_after_coupling with the inspector of the releases before eu07/maszyna#350 (ai.brakesetting.cw1 no), which cuts no brake out: every brake of the train works, and the emergency stop after the driver is taken off at 38 km/h comes at some 0.57 m/s2, over 99 m. It shows what the deceleration check of that case tells apart.", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 60, + "hold": 60, + "min_deceleration": 0.45 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ], + "ini": [ + "ai.brakesetting.cw1 no" + ] +} diff --git a/tests/scenarios/cases/td_reinspect_brakes.scn b/tests/scenarios/cases/td_reinspect_brakes.scn new file mode 100644 index 000000000..37c76550a --- /dev/null +++ b/tests/scenarios/cases/td_reinspect_brakes.scn @@ -0,0 +1,33 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the line from Stacja1 to Stacja2 (flat, curves of 600 m): a locomotive with an AI driver stands cold +// (trainset velocity 0) on koniec, its front 35 m past point 1 of the track, facing point 2, towards Stacja2; +// a cut of wagons (vars.cut) stands, braked as well and with nobody in it, ahead of it, its front 56 m past +// point 1 of tdo_n222, some 45 m in front of the locomotive. +trainset none koniec 35.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n222 56.0 0.0 +{{cut}} +endtrainset + +// event0 of the locomotive's track (the case's track_events) runs while the locomotive stands there. it wakes +// the driver and gives it, once, the order to couple to the cut ahead and run it on as a train: Shunt -3 3, +// Connect (with the coupler and the brake hose) then Obey_train, which waits for the way to be given. the AI +// couples on the run, at some 4 km/h, and the wagon inspector of the train run looks at the new train then, +// before it stands. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -3 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the way: no signal of the line is in sight, so event2 of tdo_n231 (the case's track_events), 40 m in front of +// the cut, gives the speed a signal at proceed would, 40 km/h, which the AI reads as it scans the track ahead +event autotest_way PutValues 0 none 0 0 0 SetVelocity 40 40 endevent + +// event2 of tdo_n240 (the case's track_events), some 700 m on, as the locomotive runs over it pushing the train: +// the driver is taken off (Crew: 0 0), which leaves the brake valve in the emergency position, so the +// train stops on the brakes it has. the pass comes 150 s later, with the train standing. +event autotest_crew_off multiple 0 none autotest_driver_off autotest_pass endevent +event autotest_driver_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent +event autotest_pass UpdateValues 150 __test.result the_train_was_stopped_with_the_brakes_it_has 1 * endevent diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index fd1941577..35e923bee 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -705,9 +705,11 @@ def check_driver_changes(box, vehicle, to, after=0.0, before=None): return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)" -def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0): +def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0, + min_deceleration=None, max_deceleration=None): """The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it - stopped, to the end of the recording or until it gets a driver again.""" + stopped, to the end of the recording or until it gets a driver again. With the decelerations, the mean one of + that stop (from the speed and the way to the stop, m/s²) has to be within them: how well the train brakes.""" states, why = _vehicle_states(box, vehicle) if states is None: return False, why @@ -734,8 +736,15 @@ def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_ if fastest > stop_speed or creep > max_creep: return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver" way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time) - return True, (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " - f"and {way:.0f} m later, moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}") + stopped = (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " + f"and {way:.0f} m later") + # v² / 2s: the black box lists a vehicle once a second, so the way is closer to the truth than the time + deceleration = (abs(left.speed) / 3.6) ** 2 / (2 * way) if way > 0 else math.inf + if ((min_deceleration is not None and deceleration < min_deceleration) + or (max_deceleration is not None and deceleration > max_deceleration)): + bounds = f"{min_deceleration if min_deceleration is not None else 0:g}..{max_deceleration if max_deceleration is not None else 'any'}" + return False, f"{stopped}: a mean deceleration of {deceleration:.2f} m/s², outside {bounds}" + return True, f"{stopped} ({deceleration:.2f} m/s²), moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}" def check_moves(box, vehicle, min_speed, direction="front"): From 57a0a71f4825bf5717f7c31d6599209b5986b67c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:12:15 +0100 Subject: [PATCH 14/22] fix(ci): build and run the shader validator again (#437) * fix(ci): build and run the shader validator again - gl/glsl_common.h and gl/shader.cpp include utilities/Globals.h and utilities/Logs.h now, so the stand-in headers of the validator move to ci_shadervalidator/utilities/. - gl/ubo.h needs std::span and gl/shader.cpp uses contains(), so the script builds with -std=c++20. The stand-in stdafx.h gives , and , which the precompiled header of the simulator gives otherwise. - build.sh runs from any directory and stops on the first error. - glslang defines the GL_ARB_gpu_shader5 macro without the #extension directive, so light_common.glsl took its textureGather() path without the extension enabled and 25 material shaders failed on desktop GL with the shadows on. The validator adds the directive which the simulator gives on the drivers with the extension. - The shader goes to the temporary directory of the system instead of a fixed /tmp, a shader which can't be preprocessed fails instead of ending the run, the shaders go in name order and the failed ones are listed at the end. * fix(ci): write the validated shader to a unique temporary file The shader validator wrote every preprocessed shader to a file with a fixed name in the temporary directory (/tmp/shader on Linux) and opened it with std::ofstream. In a shared /tmp anyone can create that name in advance, as a file or a link to another file, and the validator would then write through it (Sonar rule S5443, publicly writable directories). The shader now goes to a file with a unique name which is created exclusively: mkstemp() on Linux, and on Windows, which has no mkstemp(), a random name opened with fopen_s(..., "wx"), which fails when the file exists. The file is removed after glslangValidator has checked it, and when it cannot be written completely. glslangValidator gets the stage with -S, so the file still needs no extension. * docs(ci): the standalone validator no longer checks the PCF fallback path The comment of has_gl_extension() said the validator compiles the 16-tap PCF fallback of light_common.glsl. Since the validator adds the GL_ARB_gpu_shader5 directive itself, it checks the textureGather() path. --- ci_shadervalidator/build.sh | 7 +- ci_shadervalidator/main.cpp | 99 +++++++++++++++++--- ci_shadervalidator/stdafx.h | 5 + ci_shadervalidator/{ => utilities}/Globals.h | 0 ci_shadervalidator/{ => utilities}/Logs.h | 0 gl/shader.cpp | 6 +- 6 files changed, 101 insertions(+), 16 deletions(-) rename ci_shadervalidator/{ => utilities}/Globals.h (100%) rename ci_shadervalidator/{ => utilities}/Logs.h (100%) diff --git a/ci_shadervalidator/build.sh b/ci_shadervalidator/build.sh index b0207f6ed..fe13b9c63 100755 --- a/ci_shadervalidator/build.sh +++ b/ci_shadervalidator/build.sh @@ -1,2 +1,7 @@ #!/bin/sh -g++ -std=c++17 -O2 -DSHADERVALIDATOR_STANDALONE ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../gl/shader.cpp main.cpp -I../ref/glad/include -I../ref/glm -I. -o validateshaders +# builds the shader validator next to this script. it compiles gl/shader.cpp and gl/glsl_common.cpp of the +# simulator against the stand-in headers of this directory (stdafx.h, utilities/Globals.h, utilities/Logs.h) +# and needs glslangValidator on PATH to run. run validateshaders from this directory +set -e +cd "$(dirname "$0")" +${CXX:-g++} -std=c++20 -O2 -DSHADERVALIDATOR_STANDALONE ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../gl/shader.cpp main.cpp -I../ref/glad/include -I../ref/glm -I. -o validateshaders diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 65ad54b2a..bd7db0523 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -1,20 +1,70 @@ #include "stdafx.h" #include "../gl/shader.h" #include "../gl/glsl_common.h" -#include "Globals.h" +#include "utilities/Globals.h" #include -#include +#include #include #include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif _global Global; +// writes the text to a new file with a unique name in the temporary directory of the system and returns its path, +// or an empty string when it cannot be written. the file is created exclusively, so nothing put in a shared /tmp +// under a name known in advance (a file or a link) is written through +std::string write_temp_file(std::string const &text) +{ + std::string path = (std::filesystem::temp_directory_path() / "maszyna-shader-XXXXXX").string(); + std::FILE *file = nullptr; +#ifdef _WIN32 + // no mkstemp() in the CRT; a random name, opened with "x", which fails when the file is there already + std::random_device random; + for (int attempt = 0; attempt < 100 && file == nullptr; ++attempt) { + path.replace(path.size() - 6, 6, std::to_string(100000 + random() % 900000)); + if (fopen_s(&file, path.c_str(), "wx") != 0) + file = nullptr; + } +#else + int const descriptor = mkstemp(path.data()); + if (descriptor != -1) { + file = fdopen(descriptor, "w"); + if (file == nullptr) { + close(descriptor); + std::remove(path.c_str()); + } + } +#endif + if (file == nullptr) + return {}; + + bool const written = std::fwrite(text.data(), 1, text.size(), file) == text.size(); + if (std::fclose(file) != 0 || !written) { + std::remove(path.c_str()); + return {}; + } + return path; +} + bool check_shader(std::string filename) { gl::shader shader_processor; gl::glsl_common_setup(); - std::pair source = shader_processor.process_source(filename, "../shaders/"); + std::pair source; + try { + source = shader_processor.process_source(filename, "../shaders/"); + } + catch (gl::shader_exception const &e) { + std::cout << "failed to preprocess: " << e.what() << std::endl; + return false; + } std::string stage; if (source.first == GL_VERTEX_SHADER) @@ -26,11 +76,26 @@ bool check_shader(std::string filename) else return false; - std::ofstream file("/tmp/shader"); - file << source.second; - file.close(); + // glslang defines the GL_ARB_gpu_shader5 macro without the #extension directive, so light_common.glsl + // takes its textureGather() path, which needs the extension enabled on desktop GL 3.30. has_gl_extension() + // of gl/shader.cpp has no GL context here and says no, so the directive which the simulator gives on the + // drivers with the extension is added here + std::string const gpu_shader5 = "#extension GL_ARB_gpu_shader5 : enable\n"; + if (!Global.gfx_usegles && source.second.find(gpu_shader5) == std::string::npos) { + std::size_t const version_end = source.second.find('\n'); + if (version_end != std::string::npos) + source.second.insert(version_end + 1, gpu_shader5); + } - int ret = system(("glslangValidator -S " + stage + " /tmp/shader").c_str()); + // the stage is given with -S, so the file needs no extension + std::string const path = write_temp_file(source.second); + if (path.empty()) { + std::cout << "cannot write the shader to the temporary directory" << std::endl; + return false; + } + + int ret = system(("glslangValidator -S " + stage + " \"" + path + "\"").c_str()); + std::remove(path.c_str()); return ret == 0; } @@ -90,24 +155,32 @@ bool check_shader_confs(std::string filename) int main() { - bool suc = true; + // in name order, so the runs can be compared + std::vector shaders; for (auto &f : std::filesystem::recursive_directory_iterator("../shaders/")) { if (!f.is_regular_file()) continue; - std::string relative = std::filesystem::relative(f.path(), "../shaders/").string(); if (f.path().extension() != ".frag" && f.path().extension() != ".geom" && f.path().extension() != ".vert") continue; + shaders.push_back(std::filesystem::relative(f.path(), "../shaders/").generic_string()); + } + std::sort(shaders.begin(), shaders.end()); + + std::vector failed; + for (auto const &relative : shaders) { std::cout << "== validating shader " << relative << ": " << std::flush; if (!check_shader_confs(relative)) - suc = false; + failed.push_back(relative); } - if (suc) - std::cout << "==== all checks ok" << std::endl; + if (failed.empty()) + std::cout << "==== all checks ok (" << shaders.size() << " shaders)" << std::endl; else { - std::cout << "==== checks failed" << std::endl; + std::cout << "==== checks failed for " << failed.size() << " of " << shaders.size() << " shaders:" << std::endl; + for (auto const &relative : failed) + std::cout << relative << std::endl; return 1; } diff --git a/ci_shadervalidator/stdafx.h b/ci_shadervalidator/stdafx.h index 5e0560889..093baa4d2 100644 --- a/ci_shadervalidator/stdafx.h +++ b/ci_shadervalidator/stdafx.h @@ -1,6 +1,11 @@ #pragma once +// stands in for the precompiled header of the simulator, with what gl/shader.cpp, gl/glsl_common.cpp and the +// headers they include take from it #define GLM_ENABLE_EXPERIMENTAL #define GLM_FORCE_CTOR_INIT #include +#include +#include #include +#include #include diff --git a/ci_shadervalidator/Globals.h b/ci_shadervalidator/utilities/Globals.h similarity index 100% rename from ci_shadervalidator/Globals.h rename to ci_shadervalidator/utilities/Globals.h diff --git a/ci_shadervalidator/Logs.h b/ci_shadervalidator/utilities/Logs.h similarity index 100% rename from ci_shadervalidator/Logs.h rename to ci_shadervalidator/utilities/Logs.h diff --git a/gl/shader.cpp b/gl/shader.cpp index c276cdef8..feb5d95dc 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -30,8 +30,10 @@ namespace { // SHADERVALIDATOR_STANDALONE gates out the GL queries because the offline // shader validator tool links glad.c but never calls gladLoadGL(); the // function pointers stay null and a real call would crash. Returning -// false there means the standalone validator simply compiles the original -// 16-tap PCF fallback path in light_common.glsl, which is what we want. +// false there adds no #extension directive. For desktop GL the validator +// adds GL_ARB_gpu_shader5 itself (ci_shadervalidator/main.cpp), since +// glslang defines that macro anyway, so light_common.glsl is validated on +// its textureGather() path, not on the 16-tap PCF fallback. bool has_gl_extension(char const *name) { #ifdef SHADERVALIDATOR_STANDALONE (void)name; From 7059644209d48157bdfd9748677cfbafd87e2dc0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:18 +0100 Subject: [PATCH 15/22] fix(editor): a model file named outside the code page no longer crashes the first track selection (#470) * fix(editor): a model file named outside the code page no longer crashes the first track selection The first selection of a track builds the track property list, and with it the sleeper and timber model choices. pack_models() walked the whole models/ tree and turned the name of every .t3d/.e3d into a narrow string before looking at whether it was a sleeper at all. On Windows that goes through the ANSI code page, so a single model file anywhere under models/ named with a character the code page lacks threw std::system_error "No mapping for the Unicode character exists in the target multi-byte code page" out of the editor frame and the editor stopped (GE#560). The conversions are now in a try, as in the editor's other folder scans: a file whose name can't be converted is left out (the game couldn't load it by that name anyway) and the scan goes on. Names that convert give the same list as before. The scan itself moved to world/SleeperPack.cpp in the core library as pack_models(root), which pack_models() calls once with models/, so the unit tests can run it on a folder of their own. * fix(launcher): a vehicle folder named outside the code page is skipped by the skin scan scan_textures() keeps the folder of each textures.txt as a wide path and get_vehicle() turns it into a narrow name with no try. On Windows a folder under dynamic/ named with a character the code page lacks threw the same std::system_error out of the editor's vehicle tool, the launcher and the vehicle picker. Such a folder is now left out of the scan, as the model scan does with such a file. --- CMakeLists.txt | 1 + launcher/textures_scanner.cpp | 12 +++- tests/unit/test_sleeper_models.cpp | 67 ++++++++++++++++++++++ world/SleeperModels.cpp | 55 +----------------- world/SleeperPack.cpp | 91 ++++++++++++++++++++++++++++++ world/TrackSleepers.h | 4 ++ 6 files changed, 175 insertions(+), 55 deletions(-) create mode 100644 tests/unit/test_sleeper_models.cpp create mode 100644 world/SleeperPack.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 294128b87..ddffc7402 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -550,6 +550,7 @@ set(CORE_SOURCES "McZapkie/derailment.cpp" "McZapkie/collision.cpp" "world/TrackCheck.cpp" +"world/SleeperPack.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 741f978ca..480bd5671 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -9,8 +9,18 @@ void ui::vehicles_bank::scan_textures() if (f->path().filename() != "textures.txt") continue; + auto const folder{std::filesystem::relative(f->path().parent_path(), "dynamic/", error)}; + try { + // the vehicles are kept by narrow names. on Windows a folder named with a character the code page lacks + // can't be given one and would throw at the first vehicle; the game couldn't load it by that name anyway + [[maybe_unused]] auto const name{folder.generic_string()}; + } + catch (std::system_error const &) { + continue; + } + ctx_path = folder; + std::fstream stream(f->path(), std::ios_base::binary | std::ios_base::in); - ctx_path = std::filesystem::relative(f->path().parent_path(), "dynamic/", error); std::string line; while (std::getline(stream, line)) diff --git a/tests/unit/test_sleeper_models.cpp b/tests/unit/test_sleeper_models.cpp new file mode 100644 index 000000000..05d90ab32 --- /dev/null +++ b/tests/unit/test_sleeper_models.cpp @@ -0,0 +1,67 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "world/TrackSleepers.h" + +#include +#include +#include + +// the models of sleepers and timbers the track editor lists (world/TrackSleepers.h), found by the names of the files in a +// folder. a file named with a character the code page lacks is left out, rather than throwing out of the scan (GE#560) + +namespace { + +void write_model(std::filesystem::path const &Path, std::string const &Content) { + std::filesystem::create_directories(Path.parent_path()); + std::ofstream file{Path, std::ios::binary}; + file << Content; +} + +// whether the name can be turned into the narrow names of the code page: on Windows a Chinese character can't be with any +// of the single byte pages, where the narrow names are UTF-8 it can +bool narrow_name(std::filesystem::path const &Path) { + try { + static_cast(Path.generic_string()); + return true; + } catch (std::exception const &) { + return false; + } +} + +} // namespace + +TEST_CASE("sleeper models: a file named outside of the code page is left out, the rest is listed") { + test::scratch_folder const folder{"sleeper_models"}; + auto const root{folder.root()}; + write_model(root / "pkp" / "podklad_a.t3d", "Name: podklad\n"); + write_model(root / "pkp" / "podrozjazd_b.t3d", "Name: begin\nName: main\nName: end\n"); + auto const odd{root / "pkp" / std::filesystem::path{u8"podklad_\u4e2d.t3d"}}; + write_model(odd, "Name: podklad\n"); + // nor any other model of the folder named so, looked at before its name tells it's no sleeper + write_model(root / "drzewa" / std::filesystem::path{u8"drzewo_\u4e2d.e3d"}, ""); + write_model(root / "drzewa" / "drzewo.e3d", ""); + REQUIRE(std::filesystem::exists(odd)); + + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(root)); + + auto const listed{narrow_name(odd)}; + REQUIRE(models.size() == (listed ? 3u : 2u)); + // the timbers first, then by the name + CHECK(models[0].name == "pkp/podrozjazd_b"); + CHECK(models[0].timber); + CHECK(models[1].name == "pkp/podklad_a"); + CHECK_FALSE(models[1].timber); + if (listed) { + CHECK(models[2].name.find("pkp/podklad_") == 0); + } +} + +TEST_CASE("sleeper models: a folder missing lists none") { + test::scratch_folder const folder{"sleeper_models_missing"}; + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(folder.root() / "missing")); + CHECK(models.empty()); +} diff --git a/world/SleeperModels.cpp b/world/SleeperModels.cpp index ad3c791c8..ada63d3a6 100644 --- a/world/SleeperModels.cpp +++ b/world/SleeperModels.cpp @@ -23,8 +23,6 @@ http://mozilla.org/MPL/2.0/. #include #include -#include -#include #include namespace track_sleepers { @@ -237,44 +235,6 @@ double plain_length( TTrack const &Track ) { return 2.0 * ( 0.5 * std::abs( Track.fTrackWidth ) + rail_reach + beam_overhang ); } -namespace { - -// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error -void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { - - namespace fs = std::filesystem; - if( false == Entry.is_regular_file( Error ) ) { - return; - } - auto const extension { ToLower( Entry.path().extension().string() ) }; - if( extension != ".t3d" && extension != ".e3d" ) { - return; - } - auto name { ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ) }; - if( Error || name.empty() ) { - return; - } - if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos - && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { - return; - } - // a timber model has the parts it's put together from, told by their names in the file - std::ifstream file { Entry.path(), std::ios::binary }; - std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; - auto const has = [ &extension, &content ]( std::string const &Part ) { - return ( - extension == ".t3d" ? - content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos - || content.find( "Name: " + Part + "\r" ) != std::string::npos : - content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; - auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; - if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { - Models.emplace_back( std::move( name ), timber ); - } -} - -} // namespace - std::vector const &pack_models() { static std::vector models; @@ -283,20 +243,7 @@ std::vector const &pack_models() { return models; } scanned = true; - namespace fs = std::filesystem; - std::error_code error; - auto const root { fs::path { paths::models } }; - fs::recursive_directory_iterator entry { root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; - fs::recursive_directory_iterator const end; - while( entry != end ) { - if( error ) { - break; - } - add_pack_model( *entry, root, error, models ); - entry.increment( error ); - } - std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { - return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + models = pack_models( std::filesystem::path { paths::models } ); return models; } diff --git a/world/SleeperPack.cpp b/world/SleeperPack.cpp new file mode 100644 index 000000000..b04c573bb --- /dev/null +++ b/world/SleeperPack.cpp @@ -0,0 +1,91 @@ +/* +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 "world/TrackSleepers.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include + +// the models of sleepers and timbers found among the files of a folder, by their names; apart from the models drawn, so the +// unit tests can look through a folder of their own + +namespace track_sleepers { + +namespace { + +// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error +void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { + + namespace fs = std::filesystem; + if( false == Entry.is_regular_file( Error ) ) { + return; + } + // a name with a character the code page lacks throws as it's turned into the narrow names the models are loaded by, which + // couldn't open the file anyway: the file is left out, not the rest of the folder with it + std::string extension; + std::string name; + try { + extension = ToLower( Entry.path().extension().string() ); + if( extension != ".t3d" && extension != ".e3d" ) { + return; + } + name = ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ); + } + catch( std::exception const & ) { + return; + } + if( Error || name.empty() ) { + return; + } + if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos + && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { + return; + } + // a timber model has the parts it's put together from, told by their names in the file + std::ifstream file { Entry.path(), std::ios::binary }; + std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; + auto const has = [ &extension, &content ]( std::string const &Part ) { + return ( + extension == ".t3d" ? + content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos + || content.find( "Name: " + Part + "\r" ) != std::string::npos : + content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; + auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; + if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { + Models.emplace_back( std::move( name ), timber ); + } +} + +} // namespace + +std::vector pack_models( std::filesystem::path const &Root ) { + + namespace fs = std::filesystem; + std::vector models; + std::error_code error; + fs::recursive_directory_iterator entry { Root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; + fs::recursive_directory_iterator const end; + while( entry != end ) { + if( error ) { + break; + } + add_pack_model( *entry, Root, error, models ); + entry.increment( error ); + } + std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { + return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + return models; +} + +} // namespace track_sleepers diff --git a/world/TrackSleepers.h b/world/TrackSleepers.h index a22bcb94a..9acd9dc25 100644 --- a/world/TrackSleepers.h +++ b/world/TrackSleepers.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -123,6 +124,9 @@ struct pack_model { // the models of sleepers and timbers in the scenery data, found once in models/ by the names of their files telling sleepers // or timbers: podklad, podrozjazd, sleeper, timber. the timber ones first, then by the name std::vector const &pack_models(); +// the models of sleepers and timbers among the files under the folder given, named relative to it, in the same order; a file +// named with a character the code page lacks is left out +std::vector pack_models( std::filesystem::path const &Root ); // the beams of the track placed anew, as instances of the parts of the model void lay( TTrack &Track ); // the beams of the tracks around the track to be placed again, as they depend on where it runs From a3f4bd4f0d952f7912bbe3c5044194e2f350d4dc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:37 +0100 Subject: [PATCH 16/22] fix(ai): a train standing past a signal when its speed table is traced hasn't passed it (#473) * fix(ai): a train standing past a signal when its speed table is traced hasn't passed it Since #409 a point of the speed table found behind the head counts as passed only when the head had it ahead once, but a point found up to 5 m behind the head still counted as seen ahead (SeenAheadTolerance), whether the train moved or stood. A train set at a stand 0.5-4.5 m past a signal at stop therefore found the signal behind its head at its first look ahead, the next update marked it elapsed, and the test mode ended with "signal passed at danger" at 13.6 s with the train at 0 km/h (EU07 on td.scn at stacja1_j; set 6 m or 20 m past, no report). The tolerance is kept for a moving train, which may be just passing a point found at its head. A standing train passes nothing: a point found behind its head counts as seen ahead only once an update finds it ahead. The rule moves out of TSpeedPos into vehicle/signalpassing.{h,cpp}, so it is unit tested; the blackbox record of passed signals follows it as before. Measured with the head set 0.5-6 m past and 0.5-2 m short of the signal on tor1k: the distance the scan finds is the head's own distance from the memory cell (to the micrometre there), so a train standing 0.5 m short still gets the signal ahead and passes it if it goes on. Tests: tests/unit/test_signal_passing.cpp (6 cases), and the scenario cases test_mode_standing_1m_past_signal and test_mode_standing_4m_past_signal (fragment td_past_red_signal.scn), which ended as signals passed at danger before and run into their timeout now. * test(scenarios): the shunting AI stops before a signal at stop on td.scn Two cases for the shunting fix of #409, left out of it: an EU07 with no timetable (its AI shunts) starting at 30 km/h about 150 m before the exit signal stacja1_j at stop, alone (eu07_td_shunt_red_signal) and pushing three coaches (eu07_td_shunt_push_red_signal), has to stop before the signal and stay there. They come from #340, whose braking was sharper; run on the code of #409 they stop after 145 m and 141 m, with the signal 151 m from the start, so the checks of #340 (no more than 150 m, below 40 km/h) hold as they were. * fix(sonar): count the metres of the signal passing test in an integer SonarCloud rule cpp:S2193 (a for loop counter of floating type) flagged the loop that moves the head a metre at a time in tests/unit/test_signal_passing.cpp and made the new reliability rating of the pull request fail the quality gate. The counter is now an int; it took whole values only, so every case runs the same number of steps as before. * fix(ai): the gap of a standing train a few decimetres short of a signal noted at seen_ahead_when_found --- CMakeLists.txt | 1 + tests/scenarios/README.md | 14 +- .../cases/eu07_td_shunt_push_red_signal.json | 24 ++++ .../cases/eu07_td_shunt_red_signal.json | 19 +++ tests/scenarios/cases/td_past_red_signal.scn | 7 + tests/scenarios/cases/td_shunt_red_signal.scn | 7 + .../test_mode_standing_1m_past_signal.json | 16 +++ .../test_mode_standing_4m_past_signal.json | 16 +++ tests/unit/test_signal_passing.cpp | 128 ++++++++++++++++++ vehicle/Driver.cpp | 28 ++-- vehicle/Driver.h | 3 +- vehicle/signalpassing.cpp | 30 ++++ vehicle/signalpassing.h | 38 ++++++ 13 files changed, 312 insertions(+), 19 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_shunt_push_red_signal.json create mode 100644 tests/scenarios/cases/eu07_td_shunt_red_signal.json create mode 100644 tests/scenarios/cases/td_past_red_signal.scn create mode 100644 tests/scenarios/cases/td_shunt_red_signal.scn create mode 100644 tests/scenarios/cases/test_mode_standing_1m_past_signal.json create mode 100644 tests/scenarios/cases/test_mode_standing_4m_past_signal.json create mode 100644 tests/unit/test_signal_passing.cpp create mode 100644 vehicle/signalpassing.cpp create mode 100644 vehicle/signalpassing.h diff --git a/CMakeLists.txt b/CMakeLists.txt index ddffc7402..200adcf30 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -571,6 +571,7 @@ set(CORE_SOURCES "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" +"vehicle/signalpassing.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index b85f0f8cf..321b65479 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,7 +135,7 @@ Python 3.10+, no extra packages. Options: `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. The 22 cases +- `-j N` runs N cases at once. Each case prints its results when it is done. The 42 cases that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, 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 @@ -236,6 +236,11 @@ starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels 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. +`td_shunt_red_signal.scn` is the same with no timetable, so the AI shunts (Shunt) towards the signal at +stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alone and +`eu07_td_shunt_push_red_signal` pushing three coaches, both from 30 km/h, have to stop before the signal, +151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed +by #409). They stop after 145 m and 141 m. `eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about 35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): @@ -259,6 +264,13 @@ standstill of 100 s ends the test although the traffic runs on (counting every v 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. +`test_mode_standing_1m_past_signal` and `test_mode_standing_4m_past_signal` (fragment `td_past_red_signal.scn`) set +the td/rozklad train at a stand with its head 1 m and 4 m past the exit signal at stop (the memory cell of the +signal is 51 m into `tor1k`). The driver finds the signal behind the head at its first look ahead, 13.6 s in, and a +standing train passes nothing, so both run into their timeout. When a signal found up to 5 m behind the head +still counted as one the head had ahead, standing or not, both ended as signals passed at danger at 13.6 s (a +train set 6 m or 20 m past didn't). Starting at 0 km/h the driver doesn't wake up within the case, so they start at +0.1 km/h, as `td_red_signal.scn` does. The `en57_2000_automatic_coupler_*` cases (issue #86) share `td_automatic_coupler_hit.scn`: an EN57-2000 unit without a driver runs at `vars.velocity` km/h into a standing one, from diff --git a/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json new file mode 100644 index 000000000..243d37641 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json @@ -0,0 +1,24 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt), pushing three coaches with no route set, the first coach starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "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": 600, + "checks": [ + { "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_shunt_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_red_signal.json new file mode 100644 index 000000000..bc23046cd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_red_signal.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt) with no route set, starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "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/td_past_red_signal.scn b/tests/scenarios/cases/td_past_red_signal.scn new file mode 100644 index 000000000..e5e68da5f --- /dev/null +++ b/tests/scenarios/cases/td_past_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad) set at a stand past the exit signal stacja1_j, which stays at stop +// (no route): the head {{offset}} m into tor1k, whose memory cell of the signal is 51 m into the track. the train +// starts at 0.1 km/h, as in td_red_signal.scn: set at 0 its AI driver doesn't wake up within the case +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_shunt_red_signal.scn b/tests/scenarios/cases/td_shunt_red_signal.scn new file mode 100644 index 000000000..649427247 --- /dev/null +++ b/tests/scenarios/cases/td_shunt_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal_moving.scn (no route, the exit signal stacja1_j about 150 m ahead of the start of +// tdo_n1734 stays at stop), but the train has no timetable, so its AI driver shunts (Shunt), and it +// starts {{offset}} m into tdo_n1734, already moving at {{velocity}} km/h. +trainset none tdo_n1734 {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/test_mode_standing_1m_past_signal.json b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json new file mode 100644 index 000000000..4157dc52d --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 1 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "52.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/test_mode_standing_4m_past_signal.json b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json new file mode 100644 index 000000000..b0b668873 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 4 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "55.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/unit/test_signal_passing.cpp b/tests/unit/test_signal_passing.cpp new file mode 100644 index 000000000..16d3cd9eb --- /dev/null +++ b/tests/unit/test_signal_passing.cpp @@ -0,0 +1,128 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/signalpassing.h" + +// when a signal in the AI's speed table counts as passed by the train (TController::CheckSignalPassed): the test +// mode reports a signal at stop passed that way as "passed at danger", the blackbox records every passed signal. a +// train set or standing past a signal at the start of a scenario didn't pass it; within 5 m of the signal the test +// mode used to report it all the same. + +namespace { + +// a point of the speed table the way TSpeedPos keeps it: found by the scan of the route, then updated as the head +// moves on (TController::TableCheck: UpdateDistance, Update, CheckSignalPassed) +struct table_point { + double distance; // ahead of the head [m], negative behind it + bool seen_ahead; + bool elapsed{false}; + int passes{0}; // reports of the point passed + + table_point(double const Distance, bool const Standing) + : distance(Distance), seen_ahead(signal_passing::seen_ahead_when_found(Distance, Standing)) { + move(0.0); // the first update comes with the next check of the table, the train hasn't moved yet + } + + // the head moves Metres on, and the table updates the point + void move(double const Metres) { + distance -= Metres; + auto const elapsedbefore{elapsed}; + elapsed = elapsed || distance < 0.0; + seen_ahead = signal_passing::seen_ahead_on_update(distance, seen_ahead); + if (signal_passing::passed_now(elapsedbefore, elapsed, seen_ahead)) { + ++passes; + } + } + + // the head moves Metres on in steps of a metre + void run(double const Metres) { + for (int moved{0}; moved < Metres; ++moved) { + move(1.0); + } + } +}; + +auto constexpr standing{true}; +auto constexpr moving{false}; + +} // namespace + +TEST_CASE("signal passing: a train standing past a signal when its table is traced hasn't passed it") { + auto behind{0.0}; + // 1-4.5 m: reported as passed at danger before; 20 m: the train standing across the signal of #409 + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("1 m") { behind = 1.0; } + SUBCASE("2 m") { behind = 2.0; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("4 m") { behind = 4.0; } + SUBCASE("4.9 m") { behind = 4.9; } + SUBCASE("20 m") { behind = 20.0; } + CAPTURE(behind); + + table_point signal{-behind, standing}; + CHECK_FALSE(signal.seen_ahead); + // standing there a while, then pulling away from it + for (auto check{0}; check < 10; ++check) { + signal.move(0.0); + } + signal.run(200.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train standing short of a signal passes it when it moves on") { + auto ahead{0.0}; + SUBCASE("at the signal") { ahead = 0.0; } + SUBCASE("0.5 m") { ahead = 0.5; } + SUBCASE("10 m") { ahead = 10.0; } + SUBCASE("150 m") { ahead = 150.0; } + CAPTURE(ahead); + + table_point signal{ahead, standing}; + CHECK(signal.seen_ahead); + signal.move(0.0); + CHECK(signal.passes == 0); + signal.run(ahead + 50.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a moving train passing a signal its table finds just behind the head passes it") { + // the table traced anew in motion, the head right at the signal: the distance is found in steps of a metre, + // so a signal just ahead may come out a little behind + auto behind{0.0}; + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("at the tolerance") { behind = signal_passing::moving_tolerance; } + CAPTURE(behind); + + table_point signal{-behind, moving}; + CHECK(signal.seen_ahead); + CHECK(signal.passes == 1); + signal.run(100.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a signal found further behind a moving train than the tolerance wasn't passed by it") { + table_point signal{-(signal_passing::moving_tolerance + 0.5), moving}; + CHECK_FALSE(signal.seen_ahead); + signal.run(100.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train that overruns a signal and stops past it passes it once") { + // the overrun counts while the train moves; a table traced again with the train standing 3 m past the signal + // (a change of direction and back, a new order) doesn't count it again + table_point approach{150.0, moving}; + approach.run(153.0); + CHECK(approach.passes == 1); + + table_point traced_again{-3.0, standing}; + traced_again.run(50.0); + CHECK(traced_again.passes == 0); +} + +TEST_CASE("signal passing: the report of a pass needs the point to become elapsed in this very update") { + CHECK(signal_passing::passed_now(false, true, true)); + CHECK_FALSE(signal_passing::passed_now(true, true, true)); // elapsed before + CHECK_FALSE(signal_passing::passed_now(false, false, true)); // still ahead + CHECK_FALSE(signal_passing::passed_now(false, true, false)); // the head never had it ahead +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 99c6a951e..a25ed392c 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" #include "vehicle/handover.h" +#include "vehicle/signalpassing.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" #include "world/stationnames.h" @@ -330,9 +331,7 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } - else { - bSeenAhead = true; - } + bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); if (iFlags & spTrack) { // road/track if (trTrack) { @@ -418,18 +417,14 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } -// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] -constexpr double SeenAheadTolerance { 5.0 }; - -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) +bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order, bool const Standing) { // zapamiętanie zdarzenia fDist = dist; - // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the - // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head - // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than - // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't - // be told from one stopped just short of it, which really passes the signal if it goes on - bSeenAhead = ( dist >= -SeenAheadTolerance ); + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving + // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a + // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its + // head counts only once an update finds it ahead + bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -646,7 +641,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), OrderCurrentGet() ) ) { */ - if (newspeedpoint.Set(pEvent, GetDistanceToEvent(pTrack, pEvent, fLastDir, fCurrentDistance), fLength, OrderCurrentGet())) + if (newspeedpoint.Set(pEvent, GetDistanceToEvent(pTrack, pEvent, fLastDir, fCurrentDistance), fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) { fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować @@ -922,9 +917,8 @@ std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsigna void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const { - if( Passedbefore - || false == TestFlag( Point.iFlags, spElapsed ) - || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it + // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it + if( false == signal_passing::passed_now( Passedbefore, TestFlag( Point.iFlags, spElapsed ), Point.bSeenAhead ) || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0aaf70707..87dccd030 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -184,7 +184,8 @@ class TSpeedPos void UpdateDistance( double dist ) { fDist -= dist; } - bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders); + // Standing: the train stands, so an event found behind its head wasn't passed by it + bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders, bool Standing = false); void Set(TTrack *t, double d, int f); std::string TableText() const; std::string GetName() const; diff --git a/vehicle/signalpassing.cpp b/vehicle/signalpassing.cpp new file mode 100644 index 000000000..58d691760 --- /dev/null +++ b/vehicle/signalpassing.cpp @@ -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/. +*/ + +#include "stdafx.h" +#include "vehicle/signalpassing.h" + +namespace signal_passing { + +bool seen_ahead_when_found( double const Distance, bool const Standing ) { + + return Distance >= ( Standing ? 0.0 : -moving_tolerance ); +} + +bool seen_ahead_on_update( double const Distance, bool const Seenahead ) { + + return Seenahead || Distance >= 0.0; +} + +bool passed_now( bool const Elapsedbefore, bool const Elapsed, bool const Seenahead ) { + + return Elapsed && !Elapsedbefore && Seenahead; +} + +} // namespace signal_passing diff --git a/vehicle/signalpassing.h b/vehicle/signalpassing.h new file mode 100644 index 000000000..33f2e5265 --- /dev/null +++ b/vehicle/signalpassing.h @@ -0,0 +1,38 @@ +/* +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 + +// when a point of the AI's speed table (a signal above all) counts as passed by the train: the test mode's +// "signal passed at danger" and the blackbox record of passed signals (TController::CheckSignalPassed) +namespace signal_passing { + +// how far behind the head a point found by the scan of a moving train may lie and still count as one the head +// had ahead [m]. GetDistanceToEvent() finds the distance in steps of a metre from the position of the memory +// cell, so a signal just ahead of the head may come out a little behind it +inline constexpr double moving_tolerance { 5.0 }; + +// whether a point the scan finds Distance [m] ahead of the head (negative: behind it) counts as one the head had +// ahead. a moving train may be just passing it, so a point up to moving_tolerance behind counts. a standing train +// isn't passing anything: a point found behind its head was passed before (a train set or stopped past a signal), +// and counts only once an update finds it ahead. +// known gap: the distance can be off by about half a metre (GetDistanceToEvent() takes the nearest of samples a +// metre apart), so a train standing a few decimetres short of a signal may find it just behind the head, and if it +// then runs past it at stop, that isn't reported. a tolerance for a standing train wouldn't close it: the first +// update marks a point behind the head elapsed (TSpeedPos::Update()), so such a train would be reported as passing +// the signal at once, while it stands short of it. the AI stops 8-15 m short of a signal +bool seen_ahead_when_found( double Distance, bool Standing ); + +// whether the head had the point ahead, after an update finds it Distance [m] ahead of the head +bool seen_ahead_on_update( double Distance, bool Seenahead ); + +// whether an update of a point reports it as passed: it became elapsed in this update, and the head had it ahead +bool passed_now( bool Elapsedbefore, bool Elapsed, bool Seenahead ); + +} // namespace signal_passing From 419bec12853e3b9930bd067b1b942acbd0fccfe4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:46 +0100 Subject: [PATCH 17/22] test(camera): pin the order of the rotations of TCamera::SetMatrix (#414) (#474) The roll of the camera is multiplied in first, so it turns the view about the line of sight. 623c4f82 once moved it last, which nodded the view up and down when looking out of a side window with the cab swaying; #414 put it back. The new tests check the axes of the view matrix for several pitch, yaw and roll values: the line of sight follows the pitch and the yaw whatever the roll, the roll turns the up and right axes about the line of sight, and in the cab the view out of a side window stays level. With the roll moved back last, all three test cases fail. The test binary now compiles vehicle/Camera.cpp itself, with stubs for the command queue and the clock. The smoke colour of a cold diesel (#413) stays untested: it lives in rendering/particles.cpp, which needs the world environment and a whole vehicle to link. --- tests/unit/CMakeLists.txt | 2 + tests/unit/COVERAGE.md | 2 + tests/unit/test_camera.cpp | 156 +++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+) create mode 100644 tests/unit/test_camera.cpp diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index d06c83445..180285912 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + # the camera, for the order of its rotations (test_camera.cpp) + "${CMAKE_SOURCE_DIR}/vehicle/Camera.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 9b677fbed..4f7f4d657 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -124,6 +124,8 @@ Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. - `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. +- `vehicle/Camera.cpp` isn't in the library either. The test binary compiles it for the order of the camera's rotations (`test_camera.cpp`, #414), with stubs for the command queue and the clock that `TCamera::Update()` reaches for. +- The colour of the smoke of a cold diesel (#413) isn't tested: the fix is in `smoke_source::update()` (`rendering/particles.cpp`), which needs the world environment (sky, sun, precipitation, sounds) and a whole `TDynamicObject` to link. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). ### The parser, the helpers and the PLC diff --git a/tests/unit/test_camera.cpp b/tests/unit/test_camera.cpp new file mode 100644 index 000000000..684fadb56 --- /dev/null +++ b/tests/unit/test_camera.cpp @@ -0,0 +1,156 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include +#include +#include + +#include "input/command.h" +#include "utilities/Timer.h" +#include "vehicle/Camera.h" + +// the view matrix of the camera (TCamera::SetMatrix): the pitch (Angle.x) and the yaw (Angle.y) give the line of sight, +// the roll (Angle.z) turns the view about that line, wherever the camera looks. The roll comes from the sway of the cab +// (drivermode.cpp) or the angles of a camera entry of the scenery. Multiplied in last, it once acted about the world's z +// axis instead, and nodded the view up and down when looking out of a side window (623c4f82, put back in #414). +// vehicle/Camera.cpp isn't in the core library; the test binary compiles it itself (tests/unit/CMakeLists.txt) + +// the parts of the engine TCamera::Update() reaches for, which no test here runs: the command queue and the clock +// (simulation::Commands itself is in test_script_screen_host.cpp) +bool command_queue::pop(command_data &, uint32_t const) { // NOSONAR signature from input/command.h + return false; +} + +double Timer::GetDeltaRenderTime() { // NOSONAR signature from utilities/Timer.h + return 0.0; +} + +namespace { + +// the axes of the view in the world, from the view matrix +struct view_axes { + glm::dvec3 eye; + glm::dvec3 forward; // the line of sight + glm::dvec3 up; + glm::dvec3 right; +}; + +view_axes axes(TCamera const &Camera) { + glm::dmat4 matrix{1.0}; + REQUIRE(Camera.SetMatrix(matrix)); + auto const toworld{glm::inverse(matrix)}; + return { + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, 0.0, 1.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, -1.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 1.0, 0.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{1.0, 0.0, 0.0, 0.0}}}; +} + +void check_equal(glm::dvec3 const &Actual, glm::dvec3 const &Expected) { + CAPTURE(Actual.x); + CAPTURE(Actual.y); + CAPTURE(Actual.z); + CHECK(Actual.x == doctest::Approx(Expected.x).epsilon(1e-9)); + CHECK(Actual.y == doctest::Approx(Expected.y).epsilon(1e-9)); + CHECK(Actual.z == doctest::Approx(Expected.z).epsilon(1e-9)); +} + +// the free camera, at Position, turned by Angle (pitch, yaw, roll) +TCamera free_camera(glm::dvec3 const &Position, glm::vec3 const &Angle) { + TCamera camera; + camera.Init(Position, glm::dvec3{Angle}, nullptr); + return camera; +} + +struct turn { + float pitch; + float yaw; +}; + +// the camera looking ahead (-z), out of the left and the right side window, back, up and down at an angle +std::vector const turns{ + {0.f, 0.f}, + {0.f, static_cast(std::numbers::pi / 2)}, + {0.3f, static_cast(-std::numbers::pi / 2)}, + {-0.4f, static_cast(std::numbers::pi)}, + {0.2f, 0.7f}, + {-0.6f, -2.1f}, +}; + +std::vector const rolls{0.1f, -0.2f, 0.5f}; + +} // namespace + +TEST_CASE("camera: the pitch and the yaw give the line of sight, the roll leaves it as it is (#414)") { + glm::dvec3 const position{120.0, 4.5, -300.0}; + for (auto const &turn : turns) { + auto const pitch{static_cast(turn.pitch)}; + auto const yaw{static_cast(turn.yaw)}; + // the yaw from -z towards -x, the pitch up from the ground, as TCamera::RaLook() works them out + glm::dvec3 const sight{-std::sin(yaw) * std::cos(pitch), std::sin(pitch), -std::cos(yaw) * std::cos(pitch)}; + for (auto const roll : {0.f, rolls[0], rolls[1], rolls[2]}) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const view{axes(free_camera(position, {turn.pitch, turn.yaw, roll}))}; + check_equal(view.eye, position); + check_equal(view.forward, sight); + } + } +} + +TEST_CASE("camera: the roll turns the view about the line of sight, wherever the camera looks (#414)") { + for (auto const &turn : turns) { + auto const level{axes(free_camera({}, {turn.pitch, turn.yaw, 0.f}))}; + for (auto const roll : rolls) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const rolled{axes(free_camera({}, {turn.pitch, turn.yaw, roll}))}; + auto const angle{static_cast(roll)}; + // the up of the view leans towards the left by the roll, and stays square to the line of sight + check_equal(rolled.up, std::cos(angle) * level.up - std::sin(angle) * level.right); + check_equal(rolled.right, std::cos(angle) * level.right + std::sin(angle) * level.up); + CHECK(glm::dot(rolled.up, rolled.forward) == doctest::Approx(0.0).epsilon(1e-9)); + } + } +} + +// the camera in the cab: the eye in the cab, looking at a point ahead of the vehicle (TCamera::LookAt), the head turned +// by the yaw and the pitch, the sway of the cab given as the roll. The camera needs no more of the vehicle than that it +// has one, so the vehicle is a zeroed block of its size, never used as an object (as the neighbours in vehicle.cpp) +static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); + +TEST_CASE("camera: in the cab, the sway leaves the view out of a side window level (#414)") { + std::vector vehicle(sizeof(TDynamicObject)); // zeroed + + glm::dvec3 const eye{10.0, 2.0, -5.0}; + // the vehicle heading north-east on level track + auto const ahead{glm::normalize(glm::dvec3{1.0, 0.0, -1.0})}; + glm::dvec3 const left{ahead.z, 0.0, -ahead.x}; // the vehicle's left, flat + + for (auto const head : {-1, 1}) { // turned to the right, to the left + for (auto const roll : {0.1f, -0.15f}) { + CAPTURE(head); + CAPTURE(roll); + + TCamera camera; + camera.Init(eye, {}, reinterpret_cast(vehicle.data())); // NOSONAR see above + camera.LookAt = eye + ahead; + camera.vUp = {0.f, 1.f, 0.f}; + camera.Angle = {0.f, static_cast(head * std::numbers::pi / 2), roll}; + + auto const view{axes(camera)}; + check_equal(view.eye, eye); + // out of the window to the left or the right, still level, whatever the sway (the yaw is a float, a hair + // off a right angle) + auto const yaw{static_cast(camera.Angle.y)}; + check_equal(view.forward, std::sin(yaw) * left + std::cos(yaw) * ahead); + CHECK(glm::dot(view.forward, static_cast(head) * left) == doctest::Approx(1.0).epsilon(1e-6)); + // the sway tilts the view about that line by its angle + CHECK(glm::dot(view.up, view.forward) == doctest::Approx(0.0).epsilon(1e-9)); + CHECK(view.up.y == doctest::Approx(std::cos(static_cast(roll))).epsilon(1e-9)); + } + } +} From d7b4238bb84b8980fd4b4bd4b640746df36bc9e8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:14:41 +0100 Subject: [PATCH 18/22] test(scenarios): the L053 poranek cases now fail on the station's SM42 (#477) * test(scenarios): the L053 poranek cases now fail on the station's SM42 #409 fixed what both l053_poranek_tme222158_debica cases were marked xfail for: the EP07 on Tm4 stops at the checkpoint, and the ET21 no longer stands off the wire at Debica Towarowa. Run on staging f15ea405, neither passes yet: TME222158 gets to Debica and reports there, but the station's SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off, so the station never gives TME222158 step 1 and both runs end as a standstill (4347 s and 4576 s of simulation time). The xfail marks stay, with that reason. * test(scenarios): the README table names the staging run of the L053 poranek rows --- tests/scenarios/README.md | 7 ++++--- tests/scenarios/cases/l053_poranek_tme222158_debica.json | 2 +- .../cases/l053_poranek_tme222158_debica_et21.json | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 321b65479..2638272c7 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -399,15 +399,16 @@ track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): first order is `Connect` releases the hand brake a cold locomotive starts with (`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. -The cases and what they showed on master of 2026-11-11: +The cases and what they showed on master of 2026-11-11 (the two L053 poranek rows also on +staging f15ea405 of 2026-11-23): | case | report | result | | --- | --- | --- | | `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | | `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | | `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | -| `l053_poranek_tme222158_debica` | #421 | `xfail`: the train is never let into Debica, the station jams 4 minutes after the start: the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint the station waits for it at | -| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: with an ET21, as in the report, the locomotive stops for good at Debica Towarowa: running round the wagons it stands on the headshunt 20 m past the end of the overhead wire, and its driver never gets out of `Prepare_engine` | +| `l053_poranek_tme222158_debica` | #421 | `xfail`: on master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h. Since #409 (staging f15ea405, 2026-11-23) the EP07 stops at the checkpoint and TME222158 gets to Debica, but the station's SM42-1096 jams it: ordered to uncouple at step 10 of `deb_sm42_stat` it pushes its cut past `debica_k_sem_info` at danger and never gets the coupler off, so the station never sends TME222158 on | +| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: on master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 (staging f15ea405) the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica, then fails on the SM42 as `l053_poranek_tme222158_debica` does | | `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | In the L053 sceneries the test mode logs a signal passed at danger for several shunting diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json index 6fbc141e7..cba4a9830 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -10,7 +10,7 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421 is not reached: with every train driven by AI Debica jams 4 minutes after the start, the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint before it (tor1834:event0), so RPE23113 never reports there and TME222158 is never let into the station", + "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica: since #409 EP07-338'16 stops at the checkpoint before Tm4 (tor1834:event0) and TME222158 is let in and reports at Debica (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4347 s", "physicslog": false, "ini": [ "file.binary.terrain no" diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json index 4f169fea7..62785a518 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -16,7 +16,7 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421: the ET21 stands for good at Debica Towarowa with the shunting signal at Ms2. Running round the wagons it stops on the headshunt 20 m past the end of the overhead wire (the wire ends at z 4804 over tor2466, the locomotive stands at z 4786), loses power, and its driver never gets out of Prepare_engine; the ET22 the scenery has there now gets through", + "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica, as in l053_poranek_tme222158_debica: since #409 the ET21 no longer stands off the wire at Debica Towarowa, it gets through steps 1-5 of dt_tme222158_stat, takes the wagons to Debica and reports there (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4576 s", "physicslog": false, "ini": [ "file.binary.terrain no" From 02c4c8169493dd5f0aabc96fc3cff47898c2daee Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:14:50 +0100 Subject: [PATCH 19/22] refactor: the line breaker state as an enum class, fcfuH without the text round trip (L16) (#478) * refactor(cab): the cab's state of the line breaker is an enum class TTrain::m_linebreakerstate kept 0, 1 and 2 for open, closed and closing (the closing control held long enough). It is linebreaker::state now, which linebreaker::pressed() takes too; every comparison and assignment names the state. Nothing writes the state out: it isn't in the Python dictionary of the cab, the black box, the physics log or the network. No change in behaviour (eu07/maszyna#148). * refactor(physics): fcfuH takes fcfu without writing it out and reading it back A definition of an induction motor drive without fcfuH gave the dynamic brake fcfu through text: std::to_string() of the value as the default of extract_value(). The loader assigns it now. For any figure of up to six decimals the value is the same to the bit (the test compares both ways over more than 70000 figures, and through the loader); the game's definitions have one or two. Only a figure of more than six decimals, which the text rounded to six, or one past the largest value, which read back as 0 from "inf", gives another; the test pins both (eu07/maszyna#99). --- McZapkie/Mover.cpp | 6 +- tests/unit/test_fcfuh_default.cpp | 153 ++++++++++++++++++++++++++++++ tests/unit/test_linebreaker.cpp | 37 ++++---- vehicle/Train.cpp | 42 ++++---- vehicle/Train.h | 3 +- vehicle/linebreaker.cpp | 6 +- vehicle/linebreaker.h | 17 +++- 7 files changed, 215 insertions(+), 49 deletions(-) create mode 100644 tests/unit/test_fcfuh_default.cpp diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b1735d0c5..5143b359a 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -13759,7 +13759,11 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) extract_value(eimc[eimc_f_DU], "DU", Input, ""); extract_value(eimc[eimc_f_I0], "I0", Input, ""); extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); + if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) + { + // without its own figure the dynamic brake takes the one of the traction + eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; + } extract_value(eimc[eimc_p_F0], "F0", Input, ""); extract_value(eimc[eimc_p_a1], "a1", Input, ""); extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp new file mode 100644 index 000000000..437164060 --- /dev/null +++ b/tests/unit/test_fcfuh_default.cpp @@ -0,0 +1,153 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include +#include +#include + +using test::definition; +using test::vehicle; + +// the figure of the voltage by the frequency of an induction motor drive in the dynamic brake (fcfuH) takes the +// one of the traction (fcfu) when the definition has none. the loader took it by writing fcfu out with +// std::to_string() and reading the text back as the default of fcfuH (eu07/maszyna#99); it assigns it now + +namespace { + +// a figure read from a line the way TMoverParameters::LoadFIZ_EngineInductionMotor() reads fcfu +double read_fcfu(std::string const &Text) { + double fcfu{0.0}; + extract_value(fcfu, "fcfu", "fcfu=" + Text, ""); + return fcfu; +} + +// fcfuH missing, the way the loader took it before: the figure written out with six decimals in the C locale +// (the game never sets another) and read back +double fcfuh_before(double const Fcfu) { + double fcfuh{-1.0}; + extract_value(fcfuh, "fcfuH", "", std::to_string(Fcfu)); + return fcfuh; +} + +// the bits of the value, which tell -0.0 from 0.0 too +std::uint64_t bits(double const Value) { + std::uint64_t result; + std::memcpy(&result, &Value, sizeof(result)); + return result; +} + +// the value with all its digits, for the message +std::string exact(double const Value) { + char text[64]; + std::snprintf(text, sizeof(text), "%.17g", Value); + return text; +} + +// a generator of its own (splitmix64), for the same numbers on every platform +struct numbers { + std::uint64_t state{0x2545f4914f6cdd1dull}; + std::uint64_t next() { + auto value{state += 0x9e3779b97f4a7c15ull}; + value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ull; + value = (value ^ (value >> 27)) * 0x94d049bb133111ebull; + return value ^ (value >> 31); + } +}; + +// the decimal text of Integer / 10^Decimals, as a definition could hold it +std::string decimal(std::uint64_t const Integer, int const Decimals, bool const Negative) { + auto digits{std::to_string(Integer)}; + if (Decimals > 0) { + if (digits.size() <= static_cast(Decimals)) { + digits.insert(0, Decimals + 1 - digits.size(), '0'); + } + digits.insert(digits.size() - Decimals, "."); + } + return (Negative ? "-" : "") + digits; +} + +} // namespace + +TEST_CASE("fcfuH: the figure of the traction is the same, assigned or written out and read back, for every figure of up to six decimals") { + // any decimal figure of up to six decimals: the value read from it lies within half a millionth of it, so + // std::to_string() writes the figure itself and the text reads back to the very same value. checked over the + // figures the game's definitions use (33.5 to 81.5) and the ones around them, and over many others, of up + // to six decimals and up to 18 digits, of either sign + auto compared{0}; + auto const check{[&](std::string const &Text) { + auto const fcfu{read_fcfu(Text)}; + auto const before{fcfuh_before(fcfu)}; + if (bits(before) != bits(fcfu)) { + FAIL_CHECK("fcfu=" << Text << " was " << exact(before) << " as fcfuH, now " << exact(fcfu)); + } + ++compared; + }}; + // every figure of up to two decimals, from -10 to 200 + for (auto hundredths{-1000}; hundredths <= 20000; ++hundredths) { + check(decimal(static_cast(std::abs(hundredths)), 2, hundredths < 0)); + } + // every figure of up to six decimals around the ones of the game's definitions + for (auto const figure : {33.5, 40.1, 43.7, 45.18, 46.8, 47.6, 48.9, 49.0, 81.5}) { + auto const millionths{static_cast(figure * 1e6 + 0.5)}; + for (auto offset{-2000}; offset <= 2000; ++offset) { + check(decimal(static_cast(millionths + offset), 6, false)); + } + } + // figures of 0 to 6 decimals and 1 to 18 digits + numbers random; + for (auto decimals{0}; decimals <= 6; ++decimals) { + for (auto digits{1}; digits <= 18; ++digits) { + std::uint64_t limit{1}; + for (auto digit{0}; digit < digits; ++digit) { + limit *= 10; + } + for (auto sample{0}; sample < 400; ++sample) { + check(decimal(random.next() % limit, decimals, (sample & 1) != 0)); + } + } + } + // the way of writing it doesn't matter, only the value + for (auto const text : {"4.76e1", "47.60", "+47.6", "0047.6", "476e-1", "0", "-0", "1e15", "-1e-6", "1e300"}) { + check(text); + } + // nor does a figure the stream can't read, which reads as 0 + for (auto const text : {"abc", "-", "x47.6"}) { + check(text); + } + CHECK(compared > 70000); +} + +TEST_CASE("fcfuH: where the two ways part, figures no definition has") { + // no definition of the game has such a figure (they have one or two decimals, from 33.5 to 81.5). more than + // six decimals: std::to_string() rounded the value to six, the figure is taken as it's written now + CHECK(fcfuh_before(read_fcfu("0.1234567")) == read_fcfu("0.123457")); + CHECK(fcfuh_before(read_fcfu("1e-7")) == 0.0); + CHECK(read_fcfu("1e-7") == 1e-7); + // a figure past the largest value reads as infinite (with MSVC; the largest value with GCC): written out it + // was "inf", which the stream doesn't read, so the dynamic brake got 0 where it gets the traction's figure now + auto const huge{read_fcfu("1e999")}; + CHECK(huge > 1e300); + if (std::isinf(huge)) { + CHECK(fcfuh_before(huge) == 0.0); + } +} + +TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when the definition has none") { + for (auto const fcfu : {"43.7", "45.18", "49", "0.000001", "1e2"}) { + CAPTURE(fcfu); + // the EU47's definition has fcfu only + vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; + CHECK(eu47->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(eu47->eimc[eimc_f_cfu])); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); + // its own figure is kept + vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; + CHECK(own->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(own->eimc[eimc_f_cfuH] == read_fcfu("40.1")); + } +} diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 126e3307c..9b36b817f 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -9,6 +9,7 @@ using test::consist; using test::definition; +using linebreaker::state; namespace { @@ -16,7 +17,7 @@ namespace { // 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 + state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; void press() { @@ -26,8 +27,8 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == 1 && mover.MainSwitch(false)) { - breaker = 0; + if (breaker == state::closed && mover.MainSwitch(false)) { + breaker = state::open; } break; default: @@ -36,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == 0 && mover.Mains) { - breaker = 1; + if (breaker == state::open && mover.Mains) { + breaker = state::closed; } - if (breaker == 1 && false == mover.Mains) { - breaker = 0; + if (breaker == state::closed && false == mover.Mains) { + breaker = state::open; } - if (on && breaker == 0 && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? 1 : 0; + if (on && breaker == state::open && mover.MainSwitchCheck()) { + breaker = mover.MainSwitch(true) ? state::closed : state::open; } } }; @@ -53,15 +54,15 @@ struct lever { 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); + CHECK(linebreaker::pressed(state::open, latching, false) == close); + CHECK(linebreaker::pressed(state::closed, latching, true) == open); + CHECK(linebreaker::pressed(state::closed, latching, false) == open); // freshly closed, the cab finishes closing it first - CHECK(linebreaker::pressed(2, latching, true) == none); + CHECK(linebreaker::pressed(state::closing, 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); + CHECK(linebreaker::pressed(state::open, true, true) == open); + CHECK(linebreaker::pressed(state::open, false, true) == close); } TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { @@ -72,7 +73,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r REQUIRE(test::start_up(driver, line)); REQUIRE(ep05.Mains); REQUIRE(ep05.ConverterFlag); - lever ws{ep05, 1, true}; + lever ws{ep05, state::closed, 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 @@ -80,7 +81,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.MainSwitch(false, range_t::local); ws.update(); REQUIRE_FALSE(ep05.Mains); - REQUIRE(ws.breaker == 0); + REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close test::drive(driver, line, 5.0); @@ -106,7 +107,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); ws.update(); CHECK(ep05.Mains); - CHECK(ws.breaker == 1); + CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 8bf948096..3f2cbebae 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -3748,7 +3748,7 @@ void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Comm { // only impulse switches react to release events // NOTE: we presume dedicated state switch is of impulse type - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { // ...after opening circuit, or holding for too short time to close it OnCommand_linebreakeropen(Train, Command); @@ -3801,14 +3801,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman // play sound immediately when the switch is hit, not after release Train->fMainRelayTimer = 0.0f; - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { return; } // already in the desired state if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) { - Train->m_linebreakerstate = 0; + Train->m_linebreakerstate = linebreaker::state::open; 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 @@ -3883,7 +3883,7 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); } - if (Train->m_linebreakerstate == 1) + if (Train->m_linebreakerstate == linebreaker::state::closed) { return; } // already in the desired state @@ -3891,10 +3891,10 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched // NOTE: this behaviour should depend on MainOnButton presence and type_delayed // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) + if (Train->m_linebreakerstate == linebreaker::state::closing && 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, Train->mvControlled->MainSwitchRange()) ? 1 : 0; + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; @@ -8762,16 +8762,16 @@ bool TTrain::Update(double const Deltatime) { // train state update // line breaker: - if (m_linebreakerstate == 0 && true == mvControlled->Mains) + if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) { // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = 1; + m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == 1 && false == (mvControlled->Mains || mvControlled->dizel_startup)) + if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { @@ -8781,10 +8781,10 @@ bool TTrain::Update(double const Deltatime) // put the lever back on to match, like the line breaker state above ggMainOffButton.UpdateValue(0.0); } - else if (m_linebreakerstate == 2) + else if (m_linebreakerstate == linebreaker::state::closing) { // the hold coil was cut off while the closing button was held, the line breaker won't close on its release - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } } @@ -8808,18 +8808,18 @@ bool TTrain::Update(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == 0 && fMainRelayTimer > mvControlled->InitialCtrlDelay) + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) { // wlaczanie WSa z opoznieniem // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = 2; + m_linebreakerstate = linebreaker::state::closing; } // for diesels and/or vehicles with toggle switch setup we complete the engine start here // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) + if (m_linebreakerstate == linebreaker::state::closing && (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, mvControlled->MainSwitchRange()) ? 1 : 0; + m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // the switches of the other vehicles in multiple update_remote_linebreakers(Deltatime); @@ -9393,10 +9393,10 @@ bool TTrain::Update(double const Deltatime) btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == 2 || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == 2 || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); @@ -11808,7 +11808,7 @@ void TTrain::set_cab_controls(int const Cab) // line breaker if (ggMainButton.SubModel != nullptr) { // 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); + ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); } // line breakers of the other vehicles in multiple for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) diff --git a/vehicle/Train.h b/vehicle/Train.h index e6cc0f3ba..c079c3f18 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Button.h" #include "vehicle/Gauge.h" #include "vehicle/enginestart.h" +#include "vehicle/linebreaker.h" #include "audio/sound.h" #include "scripting/PyInt.h" #include "input/command.h" @@ -553,7 +554,7 @@ class TTrain { TMoverParameters *mvThird { nullptr }; // trzeci człon (SN61) TMoverParameters *mvPantographUnit { nullptr }; // nearest pantograph equipped unit // helper variable, to prevent immediate switch between closing and opening line breaker circuit - int m_linebreakerstate { 0 }; // 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it) + linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; control_mapper m_controlmapper; diff --git a/vehicle/linebreaker.cpp b/vehicle/linebreaker.cpp index 97eae0325..cc9b2f008 100644 --- a/vehicle/linebreaker.cpp +++ b/vehicle/linebreaker.cpp @@ -12,11 +12,11 @@ http://mozilla.org/MPL/2.0/. namespace linebreaker { -toggle pressed(int const Breakerstate, bool const Latchinglever, bool const Leveron) { - if (Breakerstate == 1) { +toggle pressed(state const Breakerstate, bool const Latchinglever, bool const Leveron) { + if (Breakerstate == state::closed) { return toggle::open; } - if (Breakerstate != 0) { + if (Breakerstate != state::open) { return toggle::none; } // the line breaker is open; a lever left on goes off first diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h index 370e992cc..e87312dd1 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,6 +12,13 @@ http://mozilla.org/MPL/2.0/. // the line breaker (main switch, WS) controls of the cab namespace linebreaker { +// the state the cab keeps of the line breaker, besides the vehicle's own (TMoverParameters::Mains) +enum class state : int { + open, + closed, + closing // the closing control was held long enough; the line breaker closes when it's released, or right away +}; + 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 @@ -19,10 +26,10 @@ enum class toggle : int { }; // 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); +// breaker. 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(state Breakerstate, bool Latchinglever, bool Leveron); } // namespace linebreaker From d3e6736f788918e0cfc0f4124aa6a2bf0c0df11d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:02 +0100 Subject: [PATCH 20/22] fix(ai): the braking margin ends once the independent brake is on (#479) * fix(ai): the braking margin ends once the independent brake is on The braking curve outside the final approach keeps the room the brake takes to fill only while the brake is still to be applied. It took the train brake handle past running as the only sign that the brake was on. A vehicle that runs alone, a light locomotive or a railcar such as the SN61, brakes with its independent brake and leaves the handle in running, so the margin never ended for it: on every look it planned to stop short by the distance the brake takes to fill, slowed down too early, released, braked again, and crawled the last tens of metres to a W4 or a signal at stop. This followed #264 and #297. The independent brake now counts as well (braking_curve::brake_acting, LocalBrakePosA above 0). On td.scn the light EU07 reaches the W4 of Przystanek 6.6 s sooner and covers the last 100 m in 20.3 s instead of 26.3 s; on a 20 per mille downgrade it reaches a signal at stop 11.7 s sooner (last 100 m in 20.6 s instead of 31.7 s), with 3 applications of the independent brake in the last 300 m instead of 5. A train braking with the train brake runs as before (its physicslog is the same byte for byte). * test(scenarios): light locomotive, railcar and train stopping down a 20 per mille gradient The *_td_downgrade_w4_signal cases run on a line the fragment adds beside td.scn: 300 m level, then 3000 m down a gradient of 20 per mille under a wire fed by a substation of its own. The train stops at the W4 of Dol 1500 m down the gradient and then before a signal at stop 1100 m further down. They run with a light EU07 and an SN61 alone, which brake with the independent brake, and with an EU07 and three coaches, which brakes with the train brake. eu07_coaches_td_timetable is that train on the td/rozklad timetable to Przystanek. They show the approach to a stop: before the previous commit the light EU07 needed 31.7 s for the last 100 m to the signal, now 20.6 s; the train with coaches runs the same in both. * fix(ai): the braking margin counts the independent brake only on a vehicle that has one * test(scenarios): the light EU07 and the SN61 stop at the signal down the gradient in time --- tests/scenarios/README.md | 18 +- .../eu07_coaches_td_downgrade_w4_signal.json | 42 ++ .../cases/eu07_coaches_td_timetable.json | 40 ++ .../cases/eu07_td_downgrade_w4_signal.json | 47 ++ .../cases/sn61_td_downgrade_w4_signal.json | 47 ++ tests/scenarios/cases/td_downgrade.txt | 20 + .../cases/td_downgrade_w4_signal.scn | 518 ++++++++++++++++++ tests/scenarios/run.py | 21 +- tests/unit/test_braking_curve.cpp | 35 ++ vehicle/Driver.cpp | 10 +- vehicle/brakingcurve.cpp | 4 + vehicle/brakingcurve.h | 8 +- 12 files changed, 803 insertions(+), 7 deletions(-) create mode 100644 tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/eu07_coaches_td_timetable.json create mode 100644 tests/scenarios/cases/eu07_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/sn61_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/td_downgrade.txt create mode 100644 tests/scenarios/cases/td_downgrade_w4_signal.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 2638272c7..bf5467018 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -254,6 +254,16 @@ the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the route begins at the last vehicle and keeps a W4 behind the head. +`eu07_coaches_td_timetable` is the timetable case with the EU07 and three coaches, a train that brakes with the train +brake, beside the light EU07 and the SN61 alone, which brake with the independent brake. The `*_td_downgrade_w4_signal` +cases (fragment `td_downgrade_w4_signal.scn`, timetable `td_downgrade.txt`) run on a line the fragment adds beside the +tracks of td.scn, at x = -3000: 300 m level, then 3000 m down a gradient of 20 per mille, under an overhead wire fed +by a substation of its own (`gr_pwr`; the wire on the section `pwr01` of td.scn gave the EU07 no voltage). The train +starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before +`gr_sem`, a signal at stop 1100 m further down (a memory cell with `SetVelocity 0 0` and the event that reads it, no +model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with +three coaches. + 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 @@ -428,9 +438,11 @@ the row instead, logged by builds from this branch on. - `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`). +- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`, `max_time`, + `nth`: 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`), with `max_time` + it has to begin by then (seconds of the physicslog). `nth` (default 1) takes a later stop: each + stop after the first counts once the train has reached `moving_speed` again. - `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 diff --git a/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json new file mode 100644 index 000000000..1faae73ff --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json @@ -0,0 +1,42 @@ +{ + "description": "An EU07 with three coaches on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. A train braking with the train brake, the control of the light EU07 and SN61 cases.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_timetable.json b/tests/scenarios/cases/eu07_coaches_td_timetable.json new file mode 100644 index 000000000..c8621c3b0 --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_timetable.json @@ -0,0 +1,40 @@ +{ + "description": "EU07 with three coaches on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek with the train brake.", + "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 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 360, + "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_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json new file mode 100644 index 000000000..e26f6180d --- /dev/null +++ b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "A light EU07 on a line of its own beside td.scn, down a gradient of 20 per mille on a timetable: stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before the signal gr_sem at stop 1100 m further down. The EU07 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 355, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json new file mode 100644 index 000000000..033313dc0 --- /dev/null +++ b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "An SN61 railcar alone on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. The SN61 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 366, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/td_downgrade.txt b/tests/scenarios/cases/td_downgrade.txt new file mode 100644 index 000000000..ddc50d031 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST26 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Dol 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP 1 10.38 | ] +[ | 80 |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 7 ] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade_w4_signal.scn b/tests/scenarios/cases/td_downgrade_w4_signal.scn new file mode 100644 index 000000000..ffa43ecc3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_w4_signal.scn @@ -0,0 +1,518 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 300 m level, then 3000 m down a gradient of 20 per mille, +// under an overhead wire. +// the train starts on the level, with the W4 of Gora about 40 m ahead, and runs on the timetable {{timetable}}: +// Gora 10:35 -> Dol, a W4 1500 m down the gradient (stop, leaves at 10:38) -> the signal gr_sem, 1100 m further +// down, which stays at stop. the line goes on 400 m past the signal +node -1 0 gr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 gr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 gr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 gr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 gr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 gr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 gr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 gr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 gr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 gr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 gr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 gr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 gr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 gr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 gr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 gr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 gr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 gr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +event2 dol#1_stopinfo +endtrack +node -1 0 gr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +endtrack +node -1 0 gr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +endtrack +node -1 0 gr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +endtrack +node -1 0 gr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +endtrack +node -1 0 gr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 gr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 gr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 gr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 gr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 gr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 gr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +event2 gr_sem_info +endtrack +node -1 0 gr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 gr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 gr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 gr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 gr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction + +// the W4 of the two stations of the timetable; the middle of the consist 2 m before it, leaves on time +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -60.0 180 0 0 2 202 end +include ip/pkp/w4n.inc dol#1 -2997.3 30.00 1500.0 180 0 0 2 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 gr_sem_mem memcell -2997.3 8.00 2600.0 SetVelocity 0.0 0.0 none endmemcell +event gr_sem_info getvalues 5.0 gr_sem_mem endevent + +trainset {{timetable}} gr_02 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 35e923bee..2dcec6f0d 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -482,25 +482,42 @@ def check_brakes(rows, min_pressure, moving_speed=20): 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): +def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None, max_time=None, nth=1): + """The nth stop of `hold` seconds after moving off at `moving_speed` (each stop after the first counts once the + train is moving at `moving_speed` again).""" 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 + held = 0 + moving = True for i in range(start, len(rows)): r = rows[i] + if not moving: + moving = r[COL_VELOCITY] >= moving_speed + continue if r[COL_VELOCITY] <= stop_speed: if stopped_at is None: stopped_at = i if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold: + held += 1 + if held < nth: + stopped_at = None + moving = False + continue where = dist[stopped_at] - detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m" + when = rows[stopped_at][COL_TIME] + detail = f"came to a stop at t={when:.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" + if max_time is not None and when > max_time: + return False, f"{detail}, wanted by t={max_time}s" return True, detail else: stopped_at = None + if held: + return False, f"stopped {held} times for {hold}s after moving off, wanted stop {nth}" return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off" diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp index 7102d06e0..6bcf92fc7 100644 --- a/tests/unit/test_braking_curve.cpp +++ b/tests/unit/test_braking_curve.cpp @@ -154,6 +154,41 @@ TEST_CASE("braking curve: a train with a worked out brake table plans along the } } +TEST_CASE("braking curve: the train brake handle or the independent brake counts as braking") { + CHECK_FALSE(braking_curve::brake_acting(0.0, 0.0)); + // the handle in its release or filling positions is below running + CHECK_FALSE(braking_curve::brake_acting(-1.0, 0.0)); + CHECK(braking_curve::brake_acting(1.0, 0.0)); + CHECK(braking_curve::brake_acting(0.5, 0.0)); + // a light locomotive or a railcar alone brakes with the independent brake, the handle stays in running + CHECK(braking_curve::brake_acting(0.0, 0.25)); + CHECK(braking_curve::brake_acting(-1.0, 1.0)); + CHECK(braking_curve::brake_acting(2.0, 0.5)); +} + +TEST_CASE("braking curve: a vehicle braking with its independent brake uses the whole distance, as with the train brake") { + // before, only the train brake handle counted: a light locomotive that had put its independent brake on still + // planned, on every look, to stop short by the distance the brake takes to fill, so it slowed down too early + // and crawled the last tens of metres to the stop + flat_table const light; + auto const table{light.table()}; + auto approach{stop_at(60.0, 300.0)}; + approach.offset = 20.0; + approach.fill_horizon = 8.0; + approach.brake_applied = braking_curve::brake_acting(0.0, 0.3); + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(60.0, 0.0, 280.0 + 0.1 / 25.92, 0.0, table))); + auto trainbrake{approach}; + trainbrake.brake_applied = braking_curve::brake_acting(1.0, 0.0); + CHECK(demand == doctest::Approx(braking_curve::demand(trainbrake, &table))); + auto released{approach}; + released.brake_applied = braking_curve::brake_acting(0.0, 0.0); + // with no brake on, the room to fill is kept, and more is asked for + CHECK(braking_curve::demand(released, &table) < demand); +} + TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { // a table that grips harder as the train slows, on a gradient; the demands were worked out with the // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index a25ed392c..5630cdea1 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -8256,8 +8256,16 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { // 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 fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its + // independent brake and leaves the train brake handle in running, so that brake counts as well braking_curve::approach const approach { - Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, + braking_curve::brake_acting( + BrakeCtrlPosition, + // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too + ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? + mvOccupied->LocalBrakePosA : + 0.0 ), brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp index d39ee2868..1cd1397aa 100644 --- a/vehicle/brakingcurve.cpp +++ b/vehicle/brakingcurve.cpp @@ -25,6 +25,10 @@ bool brake_table::known() const { return a0[size] > 0.0; } +bool brake_acting(double const Trainbrakeposition, double const Localbrakeposition) { + return (Trainbrakeposition > 0.0) || (Localbrakeposition > 0.0); +} + double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h index 6ed40d9bb..3b49597e5 100644 --- a/vehicle/brakingcurve.h +++ b/vehicle/brakingcurve.h @@ -40,11 +40,17 @@ struct approach { double offset; // the braking point that far short of it [m] double gravity; // tangential acceleration of the gradient [m/s2], negative uphill double acceleration; // present acceleration of the train [m/s2] - bool brake_applied; // the train brake handle is past running + bool brake_applied; // the brake the train slows down with is applied (brake_acting) double speedup_horizon; // how long the present acceleration lasts while speeding up [s] double fill_horizon; // how long the brake takes to fill once applied [s] }; +// whether the train is braking already, for approach::brake_applied: the train brake handle is past running +// (Trainbrakeposition above 0), or the independent brake is applied (Localbrakeposition above 0). a vehicle that +// runs alone, a light locomotive or a railcar, brakes with the independent brake and leaves the train brake +// handle in running +bool brake_acting(double Trainbrakeposition, double Localbrakeposition); + // acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake // (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has // responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at From 3ccd4fe73ff4a9cdd2f5fe12c1b6854e9d9fd03a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:27 +0100 Subject: [PATCH 21/22] fix(ai): read the motor parameters of ESMVelocity() within the table (#486) * fix(ai): read the motor parameters of ESMVelocity() within the table TController::ESMVelocity() indexed MotorParam with the field shunting step of the next master controller position. For a position with a step of its own that index is RList[].ScndAct, the sixth column of the RList rows of the .fiz, which readRList() takes as it is. A step of 11 or more read past the 11 entries of MotorParam. The pole flux is now read through motor_param(), which keeps the index inside the table, as MomentumF() in the same loop and Momentum() already do. Nothing changes for a .fiz with valid steps. The unit tests show the loader keeping an out-of-range ScndAct and motor_param() clamping it; ESMVelocity() itself is in Driver.cpp, which the unit tests don't build. * test(scenarios): a Traxx, with a brake handle with a time chamber, starting up None of the cases had a driver's brake handle with a time chamber (MHZ_K5P, MHZ_6P, M394, Knorr, St113, FVel6, FVE408), for which the AI getting the vehicle ready has a rule of its own for releasing the train brake (5775493b2). Three cases run a Traxx (E186, MHZ_6P) on td.scn: the timetable run from a trainset ready to depart, the same from a cold start, and the locomotive standing ready to depart with nobody in it until a driver is put in. In each the driver puts the handle to running and leaves. * test: read the EP09 definition into a json with '=', not braces GCC takes nlohmann::ordered_json in braces for an initializer list and makes an array holding the parsed object, so at("RList") threw on the Linux build (type_error 304); MSVC kept the object. --- tests/scenarios/README.md | 10 ++++ tests/scenarios/cases/traxx_td_crew_add.json | 31 ++++++++++ tests/scenarios/cases/traxx_td_timetable.json | 17 ++++++ .../cases/traxx_td_timetable_cold.json | 20 +++++++ tests/unit/test_motor_param_bounds.cpp | 57 +++++++++++++++++++ vehicle/Driver.cpp | 6 +- 6 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 tests/scenarios/cases/traxx_td_crew_add.json create mode 100644 tests/scenarios/cases/traxx_td_timetable.json create mode 100644 tests/scenarios/cases/traxx_td_timetable_cold.json create mode 100644 tests/unit/test_motor_param_bounds.cpp diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index bf5467018..5ddc77dca 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -242,6 +242,16 @@ stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alon 151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed by #409). They stop after 145 m and 141 m. +The `traxx_*` cases run a Traxx (E186, `p160dc`), whose driver's brake handle (MHZ_6P) has a time +chamber, like the MHZ_K5P, M394, Knorr, St113, FVel6 and FVE408 handles, which no other case has: the +AI getting such a locomotive ready has a rule of its own for releasing the train brake (5775493b2, +#444). `traxx_td_timetable` is the timetable run from a trainset ready to depart, +`traxx_td_timetable_cold` the same from a cold start (`td_cold_timetable.scn`, the handle in its +holding position, the brake pipe low), and `traxx_td_crew_add` the locomotive standing ready to depart +with nobody in it, the handle in its holding position and the brake pipe charged, until a driver is +put in (`td_crew.scn`, as `eu07_td_crew_add`). In all three the driver puts the handle to running +within a second of starting and leaves. + `eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about 35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation diff --git a/tests/scenarios/cases/traxx_td_crew_add.json b/tests/scenarios/cases/traxx_td_crew_add.json new file mode 100644 index 000000000..9d6200a1b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "As eu07_td_crew_add, with a Traxx (E186, p160dc) standing ready to depart (trainset velocity 0.1) with nobody in it: its brake handle, one with a time chamber (MHZ_6P), in the holding position and the brake pipe and the control reservoir at running pressure. The AI driver put in cab A 20 s after the start gets the locomotive ready, puts the handle to running and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_traxx_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable.json b/tests/scenarios/cases/traxx_td_timetable.json new file mode 100644 index 000000000..51d84860b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "Traxx (E186, p160dc) on td.scn, AI driver on the td/rozklad timetable: a driver's brake handle with a time chamber (MHZ_6P), for which the AI getting the locomotive ready has a rule of its own for releasing the train brake (5775493b2, #444). 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/e186_v2 146_226-6 p160dc 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/traxx_td_timetable_cold.json b/tests/scenarios/cases/traxx_td_timetable_cold.json new file mode 100644 index 000000000..bfdb833a2 --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable_cold.json @@ -0,0 +1,20 @@ +{ + "description": "As traxx_td_timetable, from a cold start: the trainset stands with velocity 0, so the locomotive starts braked, its brake handle (MHZ_6P, with a time chamber) in the holding position and the brake pipe below running pressure. The driver gets the order to run as a train, starts the locomotive, puts the handle to running, charges the brake pipe and leaves on time.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "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/unit/test_motor_param_bounds.cpp b/tests/unit/test_motor_param_bounds.cpp new file mode 100644 index 000000000..5d44c7331 --- /dev/null +++ b/tests/unit/test_motor_param_bounds.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include + +#include + +using test::definition; +using test::vehicle; + +// the field shunting step a position of the master controller selects (RList, its sixth column ScndAct) indexes the +// motor parameter table, MotorParam, which has MotorParametersArraySize + 1 entries. The loader takes ScndAct from the +// .fiz as it is, so the readers of the table (TMoverParameters::Momentum(), MomentumF(), TController::ESMVelocity()) +// go through motor_param(), which keeps the index inside the table + +namespace { + +// the RList rows of the EP09 with the ScndAct of the first position replaced +nlohmann::ordered_json ep09_rlist_with_scndact(std::string const &Scndact) { + std::ifstream file{std::string{EU07_UNIT_TESTS_DATA} + "/fiz/ep09_v2/104e.json"}; + REQUIRE(file.good()); + // '=' rather than braces: GCC takes a json in braces for an initializer list, an array holding it + auto const ep09 = nlohmann::ordered_json::parse(file); + auto rows = ep09.at("RList").at("rows"); + REQUIRE(rows.size() > 1); + rows[1][5] = Scndact; + return rows; +} + +} // namespace + +TEST_CASE("motor parameters: the ScndAct of an RList row is read from the .fiz as it is") { + vehicle ep09{definition::fiz("ep09_v2/104e")}; + // the first position of the EP09 runs on field shunting step 2 + CHECK(ep09->RList[1].ScndAct == 2); + CHECK(&ep09->motor_param(ep09->RList[1].ScndAct) == &ep09->MotorParam[2]); + + // a .fiz giving a step beyond the table: nothing checks it on loading + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + CHECK(broken->RList[1].ScndAct == 20); + CHECK(broken->RList[1].ScndAct > MotorParametersArraySize); +} + +TEST_CASE("motor parameters: motor_param() keeps a step from the .fiz inside the table") { + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + auto const &table{broken->MotorParam}; + // past the end: the last entry, rather than memory beyond the table + CHECK(&broken->motor_param(broken->RList[1].ScndAct) == &table[MotorParametersArraySize]); + CHECK(&broken->motor_param(MotorParametersArraySize + 1) == &table[MotorParametersArraySize]); + // below the start: the first entry + CHECK(&broken->motor_param(-1) == &table[0]); + // inside the table: the entry itself + for (int step = 0; step <= MotorParametersArraySize; ++step) { + CHECK(&broken->motor_param(step) == &table[step]); + } +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 5630cdea1..086ff43ad 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2726,8 +2726,10 @@ double TController::ESMVelocity(bool Main) } IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - double pole = mvControlling->MotorParam[SCPN].fi * - std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0); + // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does + auto const &motorparam{mvControlling->motor_param(SCPN)}; + double pole = motorparam.fi * + std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); double Us = abs(mvControlling->EngineVoltage) - IF*R; double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; From fa13d4b4a25084e515a93f77f35b45c4c7344460 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:40 +0100 Subject: [PATCH 22/22] fix(editor): Esc in the road window goes back to the select tool when nothing is being drawn (#487) Esc in the road window only called road_cancel(), which gives up the road being drawn but never changes the tool, so with the build or place tool chosen every Esc left that tool in use and the next click started another road. Now the first Esc still gives up the road being drawn (or led out of a road or a junction, or the Alt+drag of the heights) and keeps the tool; with nothing going on Esc switches to the select tool, the way the first and the next Esc work in the track field of work. The decision is editor_road::tool_after_escape(), covered by unit tests. Fixes #348 --- application/editormode.cpp | 5 ++++ editor/editorRoad.hpp | 7 ++++++ tests/unit/test_road_escape.cpp | 44 +++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 tests/unit/test_road_escape.cpp diff --git a/application/editormode.cpp b/application/editormode.cpp index a40c6e081..cfc0287c6 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -7454,7 +7454,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } if (is_press(Action)) { + // in the road window the first Esc gives up the road being drawn, the next one goes back to the selection + auto const &road{m_roadtool}; + auto const next{editor_road::tool_after_escape(road.tool, road.chain || road.branchroad != nullptr || road.branchjunction != nullptr, road.lifting)}; road_cancel(); + if (road.window && ui()->mode() != nodebank_panel::TRACK) + road_choose_tool(next); } // the first Esc drops what is going on in the track mode, the next one goes back to the selection if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) diff --git a/editor/editorRoad.hpp b/editor/editorRoad.hpp index c1b23433f..51498b143 100644 --- a/editor/editorRoad.hpp +++ b/editor/editorRoad.hpp @@ -173,6 +173,13 @@ class editor_road // Radius: of the axis of that road; Layout: what the road is like. the lanes it has along its axis are the ones the roundabout gets. // Island: what the middle is covered with, "none" to leave the ground showing static std::vector roundabout(glm::dvec3 const &Centre, double const Radius, road_node::state const &Layout, std::string const &Island); + // the tool of the road window (0 select, 1 build, 2 place) Esc leaves. while a road is being drawn, or led out of the side of + // a road or a junction, or the selected points are dragged up or down, the tool in use stays and Esc gives that up; with + // nothing going on Esc goes back to the selection + static constexpr int tool_after_escape(int const Tool, bool const Drawing, bool const Lifting) + { + return (Drawing || Lifting) ? Tool : 0; + } private: // takes down what depends on the listed pieces and junctions, lets the caller change them, then builds it all again diff --git a/tests/unit/test_road_escape.cpp b/tests/unit/test_road_escape.cpp new file mode 100644 index 000000000..31fbc1a21 --- /dev/null +++ b/tests/unit/test_road_escape.cpp @@ -0,0 +1,44 @@ +// Esc in the road window (GH#348): the first one gives up what is going on, the next one goes back to the selection + +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRoad.hpp" + +namespace { + +constexpr int select_tool{0}; +constexpr int build_tool{1}; +constexpr int place_tool{2}; + +} // namespace + +TEST_CASE("Esc with the build tool and no road being drawn goes back to the selection") { + CHECK(editor_road::tool_after_escape(build_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while a road is being drawn or led out of a road or a junction keeps the build tool") { + CHECK(editor_road::tool_after_escape(build_tool, true, false) == build_tool); +} + +TEST_CASE("Esc with the place tool goes back to the selection, the tool has nothing being drawn") { + CHECK(editor_road::tool_after_escape(place_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while the selected points are dragged up or down keeps the tool, the drag is given up") { + CHECK(editor_road::tool_after_escape(select_tool, false, true) == select_tool); + CHECK(editor_road::tool_after_escape(build_tool, false, true) == build_tool); +} + +TEST_CASE("Esc with the selection tool stays with it") { + CHECK(editor_road::tool_after_escape(select_tool, false, false) == select_tool); +} + +TEST_CASE("two Esc presses from the build tool in the middle of a road: the road given up, then the selection") { + auto tool{build_tool}; + bool drawing{true}; + tool = editor_road::tool_after_escape(tool, drawing, false); + drawing = false; // what the first Esc gives up + CHECK(tool == build_tool); + tool = editor_road::tool_after_escape(tool, drawing, false); + CHECK(tool == select_tool); +}