* fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges Prepared from cold, the AI filled the brake pipe at once with the locomotive brake off: the distributors released while the auxiliary reservoirs were still empty, so the train had no air to brake with, and on a gradient it rolled as it released. The train counted as ready as soon as it was released. A train placed cold with its pipe below the lock of the FV4a driver's brake valve (2.75 bar) wasn't unlocked until the order to go, and went on what its reservoirs got meanwhile (TMS77185 in linia_107_objazdy: 40 minutes at 1.2-1.9 bar, the last wagon at 4.3 bar at the start). - Standing, PrepareEngine() applies the locomotive brake first, then fills the pipe. Where the locomotive brake alone doesn't hold the train (1.1 x the grade force), the train brake goes to the first service position instead, so the reservoirs charge with the train held. Multiple units with the electro-pneumatic brake are released as before. - Standing to charge, the AI unlocks the pipe as it does to go (the releaser, or the unlock button). A handle which has to be moved to unlock is left where the light application holds the train. - A train is ready only once the pipe and the auxiliary reservoir of every vehicle with a working brake are within 0.5 bar of the working pressure (4.5 of 5.0: the last wagon of a long train stays at about 4.6-4.7 from what leaks along the pipe), with the pipe fed at the head of the train. Brakes cut out don't count. - The locomotive brake comes off only once the train is charged, also against DecBrakeEIM(), which for a vehicle without the integrated handle releases it too; an uphill start begins only then. - A human driver gets the same wait as a hint: "Wait for the train brakes to charge" (driver_hint::waitbrakecharge), and the hint to release the brakes waits with it once the train brake is off (brake_charge::release_waits()). The train brake may still come off: released, it fills the pipe. - A charge that rises by less than 0.02 bar in 60 s lets the train go all the same, with a line in the log. The time counts only while there is air to charge with (the engine prepared, the main reservoir above what the pipe charges to, the pipe fed at the head): a train with its compressor not running yet or a locked pipe is waited out. Once let go, a train stays so until it is to stand again: otherwise the pipe refilling behind the release held it at a crawl (et22-1075 with 36 wagons, baltyk_interregio). - The check applies to the pneumatic brake only, to the first start of a train that hasn't run (above 1 km/h) since it was placed, and to a start with the pipe below 2.5 bar (near empty, after an emergency application). A start after an ordinary stop, a service stop (3.0-3.5 bar), a change of direction or a shunting move isn't held: waiting there only delayed the train, and the scenery set the routes of the others later. - The release of the train brake in PrepareEngine() had a stray semicolon after its condition; the condition applies again in motion. - Unit tests for the charge check (brake_charge::charged(), locomotive_brake_holds(), release_waits()). Run on all 174 shipped sceneries (20 minutes each, against master): no train stuck that moved on master, 466 timetable departures compared, 459 within 15 s, mean -1.2 s. Waits for the charge: median 4 s, 90% 39 s, longest 106 s (a heavy freight train charged from 2.2 bar). * test(ai): the brake charge test counts its looks in whole numbers, not in a floating-point time SonarCloud took the loop of the test of a train with nothing to charge with yet for a bug (cpp:S2193, a counter of type double). The same 120 looks, 5 s apart. * fix(ai): the light application that holds a charging train stays on, and an empty pipe is no charge Runs of a cold train on a gradient (P33000 at Lupkow in linia_107_objazdy, 13-16 per mille, with an SM42 and 32 wagons, 1556 t) showed three faults of the charged-brakes start: - The locomotive brake was taken to hold the train with the force of its brake blocks alone, 1031 kN for an ST43: several times what its wheels pass on to the rails. It is limited to a quarter of the locomotive's weight (brake_charge::adhesion), so a light locomotive with a heavy train gets the light application of the train brake. - That application was taken off again as soon as the order to go came, by the rule that puts the handle back to running with the main reservoir below 5 bar, and by DecBrake(). The train then stood on the locomotive brake that doesn't hold it, and moved as its wagons let go (to 0.3 km/h). It stays on until the train is charged (brake_charge::holds_application()). - With the train brake applied the train counted as charged to what the head of the pipe has, which is nothing with the pipe empty: charged at 0.02 bar the moment the brake was applied. The pipe at the head counts no lower than a full service application leaves (brake_charge::reference()). The SM42 with the 32 wagons now stands still while it charges and starts without rolling back, 2 min 30 s after it was prepared (4 min 40 s before, with a start that rolled back at 0.3 km/h). An ST43 with 33 wagons and a 754 with 8 coaches there are as before, their locomotive brake holds them. In eight of the sceneries run before (l053_poranek, calkowo_v2_cementa, calkowo_v2_ctl-wegiela, calkowo_v2_osoba_jar_poranek, calkowo_retro_zima, linia61_towarowy2, l053-sluzba-brutto-posp, baltyk_interregio) the 60 timetable departures compared are the same, within 15 s, mean 0.0 s. Unit tests for the two new decisions. * fix(ai): the locomotive brake counted of the occupied vehicle alone locomotive_brake_force() added the brake of every powered vehicle of the train. The locomotive brake handle acts on the occupied vehicle only (LocalBrakePosA is set on mvOccupied and passed to no other vehicle), so a second locomotive, in multiple control or hauled dead, made the brake count as holding a train it doesn't hold, and the train brake was released on a gradient with the leading locomotive alone holding. The estimate of one vehicle is brake_charge::locomotive_brake_force(), with a test. brakecharge.h named TController::control_brake_charge(), which doesn't exist: the logic is in determine_consist_state().
Unit tests
C++ tests of the simulation logic: set up the conditions, run the code, check the outcome. They run
as part of every build of the game, in CI and locally alike, and from the IDE. They need no game
data and no window: the test vehicles are JSON definitions in data/, loaded from memory by the
game's own vehicle loader.
The code under test is eu07_core, the library of the simulation parts the game links as well
(physics, vehicle definition loader, ...): built once, with the game's settings, and tested as the
game uses it. The python library gets linked along with the game's settings, but the tests don't
use it and run without it.
COVERAGE.md says how much of the simulation core the tests reach, what's left and why, and what they found.
Running
- With the build: building the game (
WITH_TESTS, on by default) runs them at the end, once the game is linked, and printsUnit tests: 11/11 passed (80 checks). A failing test prints the full report and fails the build; the game binary gets removed, so the next build links it again and reruns them. They also run when only the tests, a definition indata/orrun_tests.cmakechanged (Ninja and Makefile generators).-DWITH_TESTS=OFFbuilds the game without them. - From the IDE: run or debug the
eu07_unit_teststarget. CLion recognises doctest and lists the test cases, so a single one can be run or debugged from the gutter. - By hand:
ctest --test-dir <build dir> --build-config Release, or the binary itself, which takes doctest options, e.g.eu07_unit_tests -tc="brakes*".EU07_UNIT_TESTS_LOG=1shows the engine log, quiet otherwise.
Writing a test
Add a test_<topic>.cpp here, it's picked up on its own.
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
TEST_CASE("brakes: service braking stops a heavier wagon too") {
// conditions: the wagon from data/wagon.json, heavier, running at 40 km/h
test::vehicle wagon{test::definition::load("wagon").set("Param", "M", 60000), 40.0 /* km/h */};
// action: full service application, as a coupled locomotive would make it
wagon.hold_brake_pipe(3.5); // bar
wagon.run(40.0 /* s */, test::track{0.15 /* friction */, 0.0 /* gradient */});
// outcome
CHECK(std::abs(wagon.speed()) < 0.1);
}
definition::load("<name>")readsdata/<name>.json, with the sections and keys of the game's vehicle definitions;set()andremove()change it for the test. Table sections give their rows as"rows": [[...], ...], keys starting with_are comments. A section the loader doesn't know is an error (the table of them is infiz.cpp); a misspelt key isn't caught, so check in the test that the value the test is about made it to the vehicle. Keep the definitions physically sensible: some parts need keys others don't (the ESt brake valves needBrake.Size), and a test on a half-defined vehicle tests the definition rather than the simulation.definition::fiz("<dir>/<name>")is one of the game's own vehicles,data/fiz/<dir>/<name>.json, in the same form, converted from the game's.fizwith the files it includes (the list and how to add one:data/fiz/README.md). The conversion keeps what the game's loader reads of the file and checks it reads the same of the converted one (fiz.h), so the vehicle is the game's.- The random numbers of the simulation are reseeded before every test case, so a test gives the
same result alone or among the others. Loading a vehicle draws some too (the scatter of its brake
pipe pressure), so a test making vehicles in a loop calls
test::reseed_random()before each. - Logic which lives in classes too big to set up in a test (the AI driver, the cab) goes into free
functions on the vehicle state the class calls, and the test calls them the same way: see
vehicle/handover.h, whichTController::TakeControl()uses, andtest_handover.cpp. vehiclecreates the vehicle the wayTDynamicObject::Init()does and steps it the way the simulation loop does, on a straight track of the given friction, gradient, catenary voltage and physics iterations a frame. With a cab (vehicle{definition, 0.0, "name", 1}) it has a driver.consist(consist.h) couples vehicles into a train and steps them together, coupler forces, air, control and power passing between them. The physics reaches a neighbour through itsTDynamicObject, for itsMoverParametersonly; the tests have a stand-in of it with just that.drive.hhas the driver's part, made of the AI's steps:start_up()(battery, pumps, pantographs, line breaker, converter, compressor),drive()(running, acknowledging the vigilance),release_brakes(),drive_cycle()(a whole run from start-up to a stop).scenario(scenario.h) puts a train, its driver and a golden trace for each vehicle together, for a test of a feature:act()marks an event in the traces,wait()runs the train.pair(vehicle.h) puts two vehicles on that track facing each other with the given ends and runs them together, as the simulation runs the vehicles of a scene: the coupler and buffer forces, collisions and automatic coupling come from the physics (test_couplers.cpp).- A test which reads files makes them in a
test::scratch_folder(scratch.h): a folder of its own in the build folder of the tests, removed with the object. The files are written byte for byte, so the line ends are the ones the test gives (test_parser.cpp,test_ladder_logic.cpp). - Check behaviour (speeds, pressures, states the player sees) rather than internal flags, and make
the test check its own preconditions (
REQUIREthat the braking skidded, before checking what a skid leads to).
Golden traces
A golden trace pins down how the simulation behaves now, for changes which mustn't alter it, like
restructuring a function: the values of some channels of a vehicle over a run, compared with the
ones recorded from the code before, in data/golden/<name>.csv. A difference fails the test, naming
the channel, the time and both rows.
The samples and their key figures aren't kept in the repository (tens of megabytes, and they only mean something against the code before the change): record them before the change, and compare after it.
git switch master
EU07_UNIT_TESTS_UPDATE_GOLDEN=1 eu07_unit_tests # records data/golden/**/*.csv, ignored by git
git switch my-refactor
EU07_UNIT_TESTS_GOLDEN_EXACT=1 eu07_unit_tests # compares every sample, bit for bit
The recorded files stay through switching branches. Without them, a trace checks the invariants and
its test's own CHECKs, which is what the CI does: every test states the behaviour it's about in
CHECKs, a scenario of a feature what the feature does (the doors open, the train stops), a run of
every real vehicle what holds for each of them (it brakes harder by every step, it runs off and stops).
test::trace trace{"eu07/notch up", test::channels::motion() + test::channels::traction()};
eu07.record(trace); // samples every 10th step
eu07->MainSwitch(true);
trace.mark("main switch"); // shows in the event column of the row
eu07.run(30.0);
trace.check();
EU07_UNIT_TESTS_UPDATE_GOLDEN=1records the samples and the key figures, for a new test or a change which alters the behaviour on purpose; the diff of the key figures shows what it altered, review it like code.- Without
EU07_UNIT_TESTS_GOLDEN_EXACT=1, samples recorded are compared within a relative 1e-9, as GCC and glibc's maths functions can differ from MSVC's in the last bits, and a trace without them passes. With it they're compared exactly, and a trace without them or its key figures fails, so a run of the refactoring check can't pass by having nothing to compare. - Keep the runs short (tens of seconds): the simulation feeds back on itself, and a last bit grows.
- A trace with no assertion about what the behaviour should be is a characterisation, bugs included;
put the behaviour the test is about into
CHECKs besides.
Key figures
Next to its samples, every trace records the figures a person reads (figures.h), for each part of
the run between two events, in data/golden/<name>.figures: the duration, the speeds, the distance,
the time to stop, the brake pipe's lowest pressure and the time to get back to 4.9 bar, the peaks of
the brake cylinders, the motor current and the tractive force.
[brake]
duration = 60.00 s
speed at the start = 118.5 km/h
distance = 944.3 m
stopped after = 45.97 s
brake cylinders peak = 3.997 bar
They're compared within 0.5% or the last decimal written, loose enough for any compiler, and the differences are told by part and figure:
key figures of "traction/4e_v1/4e" differ:
[brake] distance: 944.3 m now, 980.0 m recorded
EU07_UNIT_TESTS_UPDATE_GOLDEN=1 records them with the samples. After a change which alters the
behaviour, their comparison says in a few lines what the thousands of changed samples mean. A trace
sampled by hand, at times of its own (the commands and switches tests), records none.
Invariants
Every trace also checks, on every step of its vehicle and not only on the recorded ones, the rules
which hold for any vehicle whatever a test does (invariants.h): no NaN, the brake cylinders under
the vehicle's highest pressure, the pipes under the highest governor setting, no motor current with
the line breaker open, no tractive force without power, the distance counted as the speed runs, no
acceleration over 5 g, and a few more. They compare nothing with a recorded file, so they hold on
any compiler, and they still check a behaviour recorded anew on purpose makes sense. A broken rule
fails the test, naming the time, the last event and the values:
invariant "no motor current with the line breaker open" broken in traction/et42 fuse/0 at 63.200 s,
after "dynamic brake": Mains=0 Im=-412.5 Itot=-412.5
Where a test makes a vehicle break a rule (a collision), or a game vehicle breaks one as it is, the
list of excuses in invariants.cpp names the trace, the rule and the reason; the second kind goes
into the findings of COVERAGE.md too.
Code to test, and when the tests fail to link
A source joins the tested code by moving from SOURCES to CORE_SOURCES in the main
CMakeLists.txt; the game links it from the library from then on. The library reaches for a little
of the rest of the engine, which engine_stubs.cpp stands in for in the tests (logs, settings,
scenery layers). If a change makes it use something new, either move the real source into the
library too, when it stands on its own, or add a stub to engine_stubs.cpp.