18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-19 09:56:01 +01:00

Merge branch 'master' into feat/renderers-cleanup

This commit is contained in:
2026-11-10 17:09:09 +01:00
140 changed files with 13065 additions and 622 deletions

View File

@@ -35,6 +35,15 @@ add_executable(${UNIT_TESTS_NAME}
# the core library brings the game's build settings along
target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core)
# the script screen host, tested with the real runtimes (test_script_screen_host.cpp)
target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp")
if (WITH_LUA)
target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c")
endif()
if (WITH_WASM)
target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp")
target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_wamr)
endif()
target_include_directories(${UNIT_TESTS_NAME} PRIVATE "${DEPS_DIR}/doctest")
# the names the tests CAPTURE are often C strings, shown as text rather than pointers
target_compile_definitions(${UNIT_TESTS_NAME} PRIVATE EU07_UNIT_TESTS_DATA="${CMAKE_CURRENT_SOURCE_DIR}/data" DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING)
@@ -44,6 +53,10 @@ endif()
set_target_properties(${UNIT_TESTS_NAME} PROPERTIES FOLDER "tests")
add_test(NAME ${UNIT_TESTS_NAME} COMMAND ${UNIT_TESTS_NAME})
if (WIN32)
# the libraries of the game (lua51.dll) are next to the game, see run_tests.cmake
set_tests_properties(${UNIT_TESTS_NAME} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:eu07>")
endif()
# for running the tests at the end of building the game, see the main CMakeLists.txt
set(UNIT_TEST_DATA ${UNIT_TEST_DATA} PARENT_SCOPE)

View File

@@ -2,6 +2,14 @@
# prints a one line summary when they pass, the full report when they don't. a failure fails the build and
# removes the game binary, so the next build links it again and reruns the tests
# the tests load the libraries the game loads (lua51.dll for the Lua screens): on Windows they're looked for next to
# the game binary as well, where they are for running the game, since nothing puts them next to the tests
if(CMAKE_HOST_WIN32)
get_filename_component(game_folder "${GAME}" DIRECTORY)
file(TO_NATIVE_PATH "${game_folder}" game_folder)
set(ENV{PATH} "${game_folder};$ENV{PATH}")
endif()
execute_process(
COMMAND "${TESTS}" --no-intro --no-version
RESULT_VARIABLE result

View File

@@ -0,0 +1,31 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
using test::definition;
using test::vehicle;
// the hints for the AI driver from the AI section of the .fiz
TEST_CASE("ai hints: without the AI section the pantographs follow the built-in logic") {
vehicle wagon{definition::load("wagon")};
CHECK(wagon->AIHintPantstate == 0);
CHECK(wagon->AIHintShuntPantstate == 0);
CHECK(wagon->AIHintPantUpIfIdle);
}
TEST_CASE("ai hints: the suggested pantograph setup for shunting is read apart from the one for train mode") {
// eu07/maszyna#461: so the ET41 doesn't shunt with all of its four pantographs up
vehicle shunting{definition::load("wagon").set("AI", "Pantstate", 1).set("AI", "ShuntPantstate", 2)};
CHECK(shunting->AIHintPantstate == 1);
CHECK(shunting->AIHintShuntPantstate == 2);
}
TEST_CASE("ai hints: a .fiz with the setup for train mode only has none for shunting") {
vehicle train{definition::load("wagon").set("AI", "Pantstate", 3)};
CHECK(train->AIHintPantstate == 3);
CHECK(train->AIHintShuntPantstate == 0);
}

View File

@@ -4,6 +4,7 @@
#include "golden.h"
#include "real_vehicles.h"
#include "drive.h"
#include "consist.h"
#include "McZapkie/hamulce.h"
@@ -35,6 +36,7 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double
// every position of the driver's handle, recorded in the trace
void every_position(vehicle &Vehicle, test::trace &Trace) {
Vehicle.hold_main_reservoir(std::max(Vehicle->MaxCompressor, 8.0));
REQUIRE(Vehicle->Handle != nullptr);
auto &handle{*Vehicle->Handle};
Vehicle.record(Trace);
@@ -57,6 +59,13 @@ void every_position(vehicle &Vehicle, test::trace &Trace) {
hold(Vehicle, Trace, "running", handle.GetPos(bh_RP), 60.0);
}
// the handle put to the given position and the vehicle driven from its cab for Seconds, marked in the trace
void driven_at(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double Position, double Seconds) {
Trace.mark(Event);
Vehicle->BrakeLevelSet(Position);
test::drive(test::driving(Vehicle), {}, Seconds);
}
} // namespace
TEST_CASE("brake handles: every position of the driver's handle of every real vehicle") {
@@ -96,6 +105,7 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") {
real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0));
test::trace trace{"local brake/" + path, handle_channels(), 100};
real.record(trace);
REQUIRE(real->Handle != nullptr);
real->BrakeLevelSet(real->Handle->GetPos(bh_RP));
trace.mark("charge");
real.run(60.0);
@@ -126,25 +136,21 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ
real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0));
test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100};
real.record(trace);
REQUIRE(real->Handle != nullptr);
auto &handle{*real->Handle};
auto const at{[&trace, &real](std::string const &Event, double Position, double Seconds) {
trace.mark(Event);
real->BrakeLevelSet(Position);
test::drive(test::driving(real), {}, Seconds);
}};
at("running", handle.GetPos(bh_RP), 60.0);
driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0);
auto const running{real->PipePress};
handle.SetUniversalFlag(TUniversalBrake::ub_Overload);
at("overload button", handle.GetPos(bh_RP), 30.0);
driven_at(real, trace, "overload button", handle.GetPos(bh_RP), 30.0);
handle.SetUniversalFlag(0);
auto const overloaded{real->PipePress};
at("overload decaying", handle.GetPos(bh_RP), 240.0);
driven_at(real, trace, "overload decaying", handle.GetPos(bh_RP), 240.0);
auto const decayed{real->PipePress};
handle.SetUniversalFlag(TUniversalBrake::ub_HighPressure);
at("high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0);
driven_at(real, trace, "high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0);
auto const filled{real->PipePress};
handle.SetUniversalFlag(0);
at("running", handle.GetPos(bh_RP), 120.0);
driven_at(real, trace, "running", handle.GetPos(bh_RP), 120.0);
CHECK(running == doctest::Approx(5.0).epsilon(0.01));
CHECK(overloaded > running + 0.3);
CHECK(decayed < overloaded);
@@ -152,3 +158,110 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ
trace.check();
}
}
// eu07/maszyna#134: the Knorr St113 of the EN57-001 releases the EP brake in the running position (bh_RP, Num 6)
// and applies it one position on (Num 8), short of the lap position (Num 5); the positions are those the keys
// select, and the EP brake works only with the control of the cab powered: the battery, the reverser out of
// neutral and the EP fuse on (Ctrl+Z), as the Oerlikon handle's
namespace {
// the front car of the EN57-001 driven from its cab, with the motor car behind it, which has the battery of the two;
// air in the reservoirs, the battery on
void ready_knorr_ep(test::consist &Unit) {
Unit.add(definition::fiz("en57_v1/6bai"), 1);
Unit.add(definition::fiz("en57_v1/5bgb"));
auto &cab{Unit[0]};
REQUIRE(cab->BrakeHandle == TBrakeHandle::St113);
REQUIRE(cab->Handle != nullptr);
cab->BatterySwitch(true);
cab->CabActivisation();
cab.hold_brake_pipe(5.0);
cab->BrakeLevelSet(cab->Handle->GetPos(bh_RP));
Unit.run(60.0);
}
// the EP brake button pressed in the given handle position, held for Seconds; the cylinder pressure of the cab car
double ep_brake(test::consist &Unit, double Position, double Seconds) {
auto &cab{Unit[0]};
cab->BrakeLevelSet(Position);
Unit.run(0.1);
cab->SwitchEPBrake(1);
Unit.run(Seconds);
return cab->BrakePress;
}
// the EP force the St113 handle of the cab car gives in the given position
double ep_at(test::consist &Unit, double Position) {
auto &cab{Unit[0]};
cab->BrakeLevelSet(Position);
Unit.run(0.1);
return cab->Handle->GetEP();
}
} // namespace
TEST_CASE("brake handles: the positions of the Knorr St113 EP brake") {
test::consist unit;
ready_knorr_ep(unit);
auto &cab{unit[0]};
REQUIRE(cab->Handle != nullptr);
auto &handle{*cab->Handle};
// the keys: Num 6 running, Num 8 the first position on, Num 5 the middle of the handle
CHECK(handle.GetPos(bh_RP) == doctest::Approx(0.0));
CHECK(ep_at(unit, 0.0) == doctest::Approx(-1.0)); // EP release
CHECK(ep_at(unit, 1.0) == doctest::Approx(1.0)); // EP brake
CHECK(ep_at(unit, cab->BrakeCtrlPosNo / 2) == doctest::Approx(0.0)); // lap, Num 5
CHECK(ep_at(unit, handle.GetPos(bh_FB)) == doctest::Approx(0.0));
CHECK(ep_at(unit, handle.GetPos(bh_EPR)) == doctest::Approx(-1.0));
CHECK(ep_at(unit, handle.GetPos(bh_EPB)) == doctest::Approx(1.0));
}
TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab powered") {
for (std::string const cut : {"reverser in neutral", "EP fuse off", "battery off"}) {
CAPTURE(cut);
test::consist unit;
ready_knorr_ep(unit);
auto &cab{unit[0]};
cab->DirectionForward();
unit.run(1.0);
REQUIRE(cab->EPBrakeControlPowered());
if (cut == "reverser in neutral") {
cab->DirectionBackward();
}
else if (cut == "EP fuse off") {
cab->EpFuseSwitch(false);
}
else {
cab->BatterySwitch(false);
}
unit.run(1.0);
REQUIRE_FALSE(cab->EPBrakeControlPowered());
// the button in the EP brake position does nothing
CHECK(ep_brake(unit, 1.0, 5.0) < 0.1);
CHECK(cab->EpForce == doctest::Approx(0.0));
cab->SwitchEPBrake(0);
}
test::consist unit;
ready_knorr_ep(unit);
auto &cab{unit[0]};
cab->DirectionForward();
unit.run(1.0);
// powered, the EP brake applies
auto const applied{ep_brake(unit, 1.0, 2.0)};
CHECK(applied > 0.5);
// the reverser put to neutral with the button still held: the EP brake drops out and holds what it applied
cab->DirectionBackward();
unit.run(0.1);
CHECK(cab->EpForce == doctest::Approx(0.0));
auto const held{cab->BrakePress};
unit.run(5.0);
CHECK(cab->BrakePress < held + 0.05);
CHECK(cab->BrakePress > 0.2);
// and doesn't release either, until the control is powered again
CHECK(ep_brake(unit, 0.0, 5.0) > 0.2);
cab->SwitchEPBrake(0);
cab->DirectionForward();
unit.run(0.1);
CHECK(ep_brake(unit, 0.0, 10.0) < 0.1);
}

View File

@@ -1,6 +1,7 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
#include "consist.h"
using test::definition;
using test::vehicle;
@@ -91,3 +92,48 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") {
wagon.run(40.0 /* s */, test::track{0.15 /* friction */, 0.0 /* gradient */});
CHECK(std::abs(wagon.speed()) < 0.1);
}
// eu07/maszyna#87: the ESt4d of the EN57's EP2 valve charged its auxiliary reservoir from the main reservoir pipe
// alone, so a dead unit hauled by a locomotive coupled with the hook and the brake hose ("3") never charged it,
// its control reservoir stopped half way, and it didn't brake. Like every ESt, it charges from the brake pipe too
TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the brake pipe and brakes") {
test::consist train;
auto &locomotive{train.add(definition::fiz("sm42_v1/6d1"))};
train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::coupler | coupling::brakehose);
train.add(definition::fiz("en57_v1/6ba_840"));
train.add(definition::fiz("en57_v1/5bgaiii_led_spot"));
// a unit standing dead: no air anywhere, nothing in its main reservoir pipe
for (std::size_t i = 1; i < train.size(); ++i) {
auto &car{train[i].mover()};
REQUIRE(car.BrakeValve == TBrakeValve::EP2);
car.Hamulec->ForceEmptiness();
car.Pipe->CreatePress(0.0);
car.Pipe->Act();
car.Pipe2->CreatePress(0.0);
car.Pipe2->Act();
car.CompressedVolume = 0.0;
}
locomotive.hold_brake_pipe(5.0);
train.run(900.0);
for (std::size_t i = 1; i < train.size(); ++i) {
CAPTURE(i);
auto &car{train[i].mover()};
REQUIRE(car.ScndPipePress < 0.1); // no main reservoir pipe
CHECK(car.Hamulec->GetBRP() > 4.8);
CHECK(car.Hamulec->GetCRP() > 4.8);
CHECK(car.BrakePress < 0.1);
}
// a full service application brakes the unit, and it releases again
locomotive.hold_brake_pipe(3.5);
train.run(20.0);
for (std::size_t i = 1; i < train.size(); ++i) {
CAPTURE(i);
CHECK(train[i]->BrakePress > 2.0);
}
locomotive.hold_brake_pipe(5.0);
train.run(60.0);
for (std::size_t i = 1; i < train.size(); ++i) {
CAPTURE(i);
CHECK(train[i]->BrakePress < 0.1);
}
}

View File

@@ -227,3 +227,204 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended"
CHECK(security.radiostop_available());
scenario.check();
}
namespace {
// the SM42, its shunt mode switching its vigilance device (CA) off or not (AwareOffInShuntMode), set in the
// test whatever the converted definition says
definition sm42_vigilance(bool const Off) {
return definition::fiz("sm42_v1/6d1").set("Security", "AwareOffInShuntMode", Off ? "Yes" : "No");
}
// runs the train for Seconds with nobody acknowledging the vigilance; returns whether the vigilance alarm came
bool unattended(scenario &Scenario, int const Seconds) {
bool blinked{false};
for (int i = 0; i < Seconds; ++i) {
Scenario.train().run(1.0, Scenario.line());
blinked |= Scenario.cab().SecuritySystem.is_vigilance_blinking();
}
return blinked;
}
} // namespace
TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, where its definition says so") {
// eu07/maszyna#457: with AwareOffInShuntMode=Yes the shunt mode of the SM42 switches its vigilance device (CA)
// off, it alerts again once the shunt mode is off
scenario scenario{"cab/sm42 vigilance in shunt mode", motion() + brakes(), test::track{}};
scenario.train().add(sm42_vigilance(true), 1);
REQUIRE(scenario.start_up());
auto &sm42{scenario.cab()};
auto const &security{sm42.SecuritySystem};
REQUIRE(sm42.CurrentSwitch(true));
REQUIRE(sm42.ShuntMode);
scenario.get_going();
sm42.AnPos = 0.3;
sm42.IncMainCtrl(1);
scenario.act("unattended in shunt mode");
bool blinked{false};
for (int i = 0; i < 120; ++i) {
scenario.train().run(1.0, scenario.line());
blinked |= security.is_blinking();
}
CHECK(sm42.Vel > 1.0);
CHECK_FALSE(blinked);
CHECK(sm42.PipePress > 3.5);
scenario.act("shunt mode off");
scenario.notch_back(0);
REQUIRE(sm42.CurrentSwitch(false));
sm42.IncMainCtrl(1);
scenario.act("unattended");
CHECK(unattended(scenario, 120));
scenario.check();
}
TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by default") {
// without AwareOffInShuntMode the shunt mode leaves the vigilance device alone: unattended, it alerts and brakes
scenario scenario{"cab/sm42 vigilance kept in shunt mode", motion() + brakes(), test::track{}};
scenario.train().add(sm42_vigilance(false), 1);
REQUIRE(scenario.start_up());
auto &sm42{scenario.cab()};
REQUIRE(sm42.CurrentSwitch(true));
REQUIRE(sm42.ShuntMode);
scenario.get_going();
sm42.AnPos = 0.3;
sm42.IncMainCtrl(1);
scenario.act("unattended in shunt mode");
CHECK(unattended(scenario, 120));
CHECK(sm42.ShuntMode);
CHECK(sm42.PipePress < 1.0);
scenario.check();
}
TEST_CASE("cab: the SM42's vigilance alarm on, not cleared by switching into the shunt mode") {
// the shunt mode switches the vigilance device off for the time to come: an alarm already on goes on to the
// emergency braking, until the driver acknowledges it (#275 review)
scenario scenario{"cab/sm42 vigilance alarm into shunt mode", motion() + brakes(), test::track{}};
scenario.train().add(sm42_vigilance(true), 1);
REQUIRE(scenario.start_up());
auto &sm42{scenario.cab()};
auto const &security{sm42.SecuritySystem};
scenario.get_going();
sm42.IncMainCtrl(1);
scenario.act("unattended");
// the alerter counts only on the move, which takes a while on the first notch
for (int i = 0; i < 300 && false == security.is_vigilance_blinking(); ++i) {
scenario.train().run(1.0, scenario.line());
}
REQUIRE(security.is_vigilance_blinking());
REQUIRE_FALSE(security.is_braking());
scenario.act("shunt mode on");
for (int i = 0; i < 20 && false == sm42.IsMainCtrlNoPowerPos(); ++i) {
sm42.DecMainCtrl(1);
}
REQUIRE(sm42.CurrentSwitch(true));
REQUIRE(sm42.ShuntMode);
scenario.train().run(15.0, scenario.line());
CHECK(security.is_vigilance_blinking());
CHECK(security.is_beeping());
CHECK(security.is_braking());
CHECK(sm42.PipePress < 1.0);
scenario.act("acknowledged");
sm42.SecuritySystemReset();
scenario.train().run(1.0, scenario.line());
CHECK_FALSE(security.is_blinking());
CHECK_FALSE(security.is_braking());
scenario.check();
}
namespace {
TSecuritySystem sm42_security(bool const OffInShuntMode) {
TSecuritySystem security;
security.load(std::string{"Security: AwareSystem=Active AwareMinSpeed=0.0 AwareDelay=60 SoundSignalDelay=2.5 MaxHoldTime=1.0 "
"EmergencyBrakeDelay=2.5 AwareOffInShuntMode="} +
(OffInShuntMode ? "Yes" : "No"),
90.0);
security.set_enabled(true);
security.update(0.1, 20.0, true, 1);
return security;
}
void run(TSecuritySystem &Security, double const Seconds) {
for (int i = 0; i < std::lround(Seconds / 0.1); ++i) {
Security.update(0.1, 20.0, true, 1);
}
}
} // namespace
TEST_CASE("cab: the alerter in the shunt mode, with and without AwareOffInShuntMode") {
for (auto const off : {false, true}) {
CAPTURE(off);
auto security{sm42_security(off)};
security.set_shunt_mode(true);
run(security, 120.0);
// without the key the shunt mode changes nothing: the alerter alerts and brakes
CHECK(security.is_vigilance_blinking() != off);
CHECK(security.is_braking() != off);
}
}
TEST_CASE("cab: the alerter's alarm on, not cleared by the shunt mode") {
auto security{sm42_security(true)};
run(security, 61.0);
REQUIRE(security.is_vigilance_blinking());
REQUIRE_FALSE(security.is_braking());
security.set_shunt_mode(true);
run(security, 10.0);
CHECK(security.is_vigilance_blinking());
CHECK(security.is_beeping());
CHECK(security.is_braking());
security.acknowledge_press();
security.acknowledge_release();
run(security, 0.1);
CHECK_FALSE(security.is_blinking());
CHECK_FALSE(security.is_braking());
// then nothing more on the move in the shunt mode
run(security, 300.0);
CHECK_FALSE(security.is_blinking());
// and back in the line mode the alerter counts again
security.set_shunt_mode(false);
run(security, 61.0);
CHECK(security.is_vigilance_blinking());
}
TEST_CASE("cab: the vigilance button held too long, its alarm not cleared by the shunt mode") {
// the alarm of the button held too long stays on in the shunt mode too, until the button is let go
TSecuritySystem security;
security.load("Security: AwareSystem=Active AwareMinSpeed=0.0 AwareDelay=60 SoundSignalDelay=2.5 MaxHoldTime=1.0 "
"EmergencyBrakeDelay=2.5 AwareOffInShuntMode=Yes",
90.0);
security.set_enabled(true);
security.update(0.1, 20.0, true, 1);
security.acknowledge_press();
for (int i = 0; i < 20; ++i) {
security.update(0.1, 20.0, true, 1);
}
REQUIRE(security.is_vigilance_blinking());
security.set_shunt_mode(true);
for (int i = 0; i < 60; ++i) {
security.update(0.1, 20.0, true, 1);
}
CHECK(security.is_vigilance_blinking());
CHECK(security.is_braking());
security.acknowledge_release();
security.update(0.1, 20.0, true, 1);
CHECK_FALSE(security.is_blinking());
CHECK_FALSE(security.is_braking());
// held again in the shunt mode, no new alarm
security.acknowledge_press();
for (int i = 0; i < 100; ++i) {
security.update(0.1, 20.0, true, 1);
}
CHECK_FALSE(security.is_blinking());
security.acknowledge_release();
// out of the shunt mode, held too long again
security.set_shunt_mode(false);
security.acknowledge_press();
for (int i = 0; i < 20; ++i) {
security.update(0.1, 20.0, true, 1);
}
CHECK(security.is_vigilance_blinking());
}

View File

@@ -37,3 +37,145 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh
CHECK(unit->ConverterOverloadRelayStart == start_t::automatic);
}
}
namespace {
// the first position of the master controller after Position without the starting resistors in the circuit
int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) {
for (auto position{Position + 1}; position <= Vehicle.MainCtrlPosNo; ++position) {
if (Vehicle.RList[position].R < 0.01) {
return position;
}
}
return 0;
}
// the vehicle with its cab occupied, the master controller set to Position and the shunt controller off
void controllers_at(vehicle &Vehicle, int Position) {
Vehicle->CabActive = 1;
Vehicle->MainCtrlPos = Position;
Vehicle->ScndCtrlPos = 0;
}
} // namespace
TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and on the resistive positions (eu07/maszyna#402)") {
for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) {
CAPTURE(path);
vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1};
REQUIRE(locked->ScndCtrlResistiveLock);
REQUIRE(locked->ScndCtrlPosNo > 0);
auto const resistancefree{resistance_free_position(locked.mover())};
REQUIRE(resistancefree > 1);
if (resistancefree <= 1) {
continue; // not reached, the REQUIRE above ends the test; tells the static analysis the index below is in range
}
REQUIRE(locked->RList[resistancefree - 1].R >= 0.01);
SUBCASE("zero") {
controllers_at(locked, 0);
CHECK(locked->IsScndCtrlLockedByMainCtrl());
CHECK_FALSE(locked->IncScndCtrl(1));
CHECK_FALSE(locked->IncScndCtrl(2));
CHECK(locked->ScndCtrlPos == 0);
}
SUBCASE("resistive positions") {
for (auto position{1}; position < resistancefree; ++position) {
CAPTURE(position);
controllers_at(locked, position);
CHECK_FALSE(locked->IncScndCtrl(1));
CHECK(locked->ScndCtrlPos == 0);
}
}
SUBCASE("every resistance-free position") {
for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.mover(), position)) {
CAPTURE(position);
controllers_at(locked, position);
CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl());
CHECK(locked->IncScndCtrl(1));
CHECK(locked->ScndCtrlPos == 1);
}
}
SUBCASE("the shunt goes down on a resistance-free position") {
controllers_at(locked, resistancefree);
REQUIRE(locked->IncScndCtrl(1));
REQUIRE(locked->IncScndCtrl(1));
CHECK(locked->DecScndCtrl(1));
CHECK(locked->ScndCtrlPos == 1);
CHECK(locked->DecScndCtrl(2));
CHECK(locked->ScndCtrlPos == 0);
}
SUBCASE("the shunt doesn't go down on a resistive position either") {
// a state the lock doesn't let arise (see below), set by hand to check the controller alone
controllers_at(locked, resistancefree - 1);
locked->ScndCtrlPos = 1;
CHECK(locked->IsScndCtrlLockedByMainCtrl());
CHECK_FALSE(locked->DecScndCtrl(1));
CHECK_FALSE(locked->DecScndCtrl(2));
CHECK(locked->ScndCtrlPos == 1);
}
SUBCASE("the master controller taken back from a shunt step drops the shunt") {
controllers_at(locked, resistancefree);
REQUIRE(locked->IncScndCtrl(1));
if (locked->TrainType == dt_ET22) {
// the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before
CHECK_FALSE(locked->DecMainCtrl(1));
CHECK(locked->MainCtrlPos == resistancefree);
CHECK(locked->DecScndCtrl(1));
}
CHECK(locked->DecMainCtrl(1));
CHECK(locked->MainCtrlPos == resistancefree - 1);
CHECK(locked->ScndCtrlPos == 0);
// and the master controller goes on down to zero, nothing left locked
while (locked->MainCtrlPos > 0 && locked->DecMainCtrl(1)) {
}
CHECK(locked->MainCtrlPos == 0);
}
SUBCASE("the master controller set directly (AI, consist) drops the shunt in the next update") {
controllers_at(locked, resistancefree);
REQUIRE(locked->IncScndCtrl(1));
locked->MainCtrlPos = resistancefree - 1;
locked.step();
CHECK(locked->ScndCtrlPos == 0);
CHECK(locked->MainCtrlPos == resistancefree - 1);
}
SUBCASE("the master controller moved up from a shunt step onto a resistive position drops the shunt") {
// the last series position, followed by the resistive parallel ones
auto lastseries{0};
for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.mover(), position)) {
if (locked->RList[position + 1].R >= 0.01) {
lastseries = position;
break;
}
}
REQUIRE(lastseries > 0);
controllers_at(locked, lastseries);
locked->DirActive = 1;
REQUIRE(locked->IncScndCtrl(1));
if (locked->TrainType == dt_ET22) {
CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before
CHECK(locked->ScndCtrlPos == 1);
}
else {
CHECK(locked->IncMainCtrl(1));
CHECK(locked->MainCtrlPos == lastseries + 1);
CHECK(locked->ScndCtrlPos == 0);
}
}
}
}
TEST_CASE("cntrl: without ScndCtrlResistiveLock the field shunting engages on any position, as before") {
for (auto const *path : {"et22_v3/201e-rn", "ep09_v2/104e"}) {
CAPTURE(path);
vehicle unlocked{definition::fiz(path), 0.0, "test", 1};
CHECK_FALSE(unlocked->ScndCtrlResistiveLock);
for (auto const position : {0, 1}) {
CAPTURE(position);
controllers_at(unlocked, position);
CHECK_FALSE(unlocked->IsScndCtrlLockedByMainCtrl());
CHECK(unlocked->IncScndCtrl(1));
CHECK(unlocked->ScndCtrlPos == 1);
}
}
}

View File

@@ -113,3 +113,93 @@ TEST_CASE("compressor: without a pressure switch the air over the cut-out pressu
REQUIRE(vehicle->CompressorFlag); // nothing stops it
CHECK(vehicle->CompressedVolume < 8.5 * 0.81); // a fifth of the air let out
}
TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") {
auto vehicle{compressor_vehicle(30.0)};
vehicle->Mains = true; // engine started
run_compressor(vehicle, 20.0);
REQUIRE_FALSE(vehicle->CompressorFlag);
vehicle->Mains = false; // engine stopped, 10 s short of the delay
run_compressor(vehicle, 1.0);
vehicle->Mains = true;
run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one
CHECK_FALSE(vehicle->CompressorFlag);
run_compressor(vehicle, 15.1);
CHECK(vehicle->CompressorFlag);
}
TEST_CASE("compressor: the start delay holds back a compressor switched on by hand too") {
auto vehicle{compressor_vehicle(30.0)};
vehicle->CompressorStart = start_t::manual;
vehicle->CompressorAllow = true; // switch in the cabinet on before the engine start
vehicle->Mains = true;
run_compressor(vehicle, 29.9);
CHECK_FALSE(vehicle->CompressorFlag);
run_compressor(vehicle, 0.2);
CHECK(vehicle->CompressorFlag);
}
TEST_CASE("compressor: the start delay is read from the brake section") {
auto const delay{[](std::string const &Section) {
return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->CompressorStartDelay;
}};
CHECK(delay("Brake") == doctest::Approx(30.0));
CHECK(delay("Cntrl") == doctest::Approx(0.0)); // the key isn't taken from the control section
}
namespace {
// 401Da: the compressor runs from the 110 V of the auxiliary generator driven by the engine, here the converter
// started with the main circuit, which gets up to voltage the converter start delay after the engine start
definition generator_vehicle(double const ConverterDelay, double const CompressorDelay) {
return definition::load("cab_vehicle")
.set("Param", "PWR", 370)
.set("Light", "Light", "Generator")
.set("Light", "LMaxVoltage", 110)
.set("Brake", "Vv", 0.6)
.set("Brake", "MinCP", 6.5)
.set("Brake", "MaxCP", 8.0)
.set("Brake", "CompressorSpeed", 0.003)
.set("Brake", "CompressorPower", "Converter")
.set("Brake", "CompressorStartDelay", CompressorDelay)
.set("Cntrl", "CompressorStart", "Automatic")
.set("Cntrl", "ConverterStart", "Automatic")
.set("Cntrl", "ConverterStartDelay", ConverterDelay);
}
} // namespace
TEST_CASE("compressor: fed from the converter it waits for the converter start delay") {
vehicle loco{generator_vehicle(30.0, 0.0)};
REQUIRE(loco->CompressorPower == 2);
REQUIRE(loco->ConverterStartDelay == doctest::Approx(30.0));
loco.run(1.0); // engine off
CHECK_FALSE(loco->Power110vIsAvailable);
loco->Mains = true; // engine started
loco.run(25.0);
CHECK_FALSE(loco->Power110vIsAvailable);
CHECK_FALSE(loco->CompressorFlag);
loco.run(10.0);
CHECK(loco->Power110vIsAvailable);
CHECK(loco->CompressorFlag);
}
TEST_CASE("compressor: fed from the converter the start delay counts from the converter voltage") {
vehicle loco{generator_vehicle(20.0, 10.0)};
REQUIRE(loco->CompressorStartDelay == doctest::Approx(10.0));
loco.run(1.0); // engine off
loco->Mains = true; // engine started
loco.run(25.0);
REQUIRE(loco->Power110vIsAvailable); // the converter is up
CHECK_FALSE(loco->CompressorFlag); // but the compressor waits for its own delay as well
loco.run(10.0);
CHECK(loco->CompressorFlag);
}

View File

@@ -525,3 +525,130 @@ TEST_CASE("couplers: a collision of coupled vehicles keeps the momentum of the p
CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) > 13.5);
CHECK(0.5 * (front_wagon.speed() + rear_wagon.speed()) < 15.05 + 1e-6);
}
// eu07/maszyna#520: an electric and a diesel locomotive got their control coupled (multiple-unit control) when the
// scenario or the Starter asked for it, or when the couplers let it through, as a Vectron and an SM42 did
namespace {
// the given setting of the control coupling check for the test, restored after it
class control_coupling_check_setting {
public:
explicit control_coupling_check_setting(bool Enabled) { Global.control_coupling_engine_check = Enabled; }
~control_coupling_check_setting() { Global.control_coupling_engine_check = m_previous; }
control_coupling_check_setting(control_coupling_check_setting const &) = delete;
control_coupling_check_setting &operator=(control_coupling_check_setting const &) = delete;
private:
bool m_previous{Global.control_coupling_engine_check};
};
constexpr int scenario_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control};
// couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the
// first one only), returns the coupling the pair got
int scenario_couple(vehicle &First, vehicle &Second, int Coupling = scenario_coupling) {
REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), Coupling, true, false));
CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag);
return First->Couplers[end::rear].CouplingFlag;
}
} // namespace
TEST_CASE("couplers: an electric and a diesel locomotive don't share their control") {
control_coupling_check_setting const check{true};
// the E6ACT names no control system (ControlType), as the Vectron doesn't; the SM42 names its own, the SM03 none
auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}};
REQUIRE(electric->EngineType == TEngineType::ElectricInductionMotor);
SUBCASE("a diesel-electric one with its own control system") {
auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
REQUIRE(diesel->EngineType == TEngineType::DieselElectric);
CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front));
CHECK(scenario_couple(electric, diesel) == (scenario_coupling & ~coupling::control));
}
SUBCASE("a diesel-mechanical one without a control system named, either") {
auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}};
REQUIRE(diesel->EngineType == TEngineType::DieselEngine);
CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear));
CHECK(scenario_couple(diesel, electric) == (scenario_coupling & ~coupling::control));
}
SUBCASE("unless both name the same control system") {
auto diesel{vehicle{definition::fiz("sm03_v1/sm03").set("BuffCoupl", "ControlType", "shared"), 0.0, "diesel"}};
auto shared{vehicle{definition::fiz("e6act_v2/e6acta").set("BuffCoupl", "ControlType", "shared"), 0.0, "electric"}};
CHECK(scenario_couple(shared, diesel) == scenario_coupling);
}
SUBCASE("unless the vehicles make one unit, coupled for good") {
auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}};
auto const forgood{scenario_coupling | coupling::permanent};
CHECK(scenario_couple(electric, diesel, forgood) == forgood);
}
SUBCASE("unless the check is turned off") {
control_coupling_check_setting const off{false};
auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
CHECK(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front));
CHECK(scenario_couple(electric, diesel) == scenario_coupling);
}
}
TEST_CASE("couplers: locomotives of the same traction and the cars keep their control coupling") {
control_coupling_check_setting const check{true};
SUBCASE("two locomotives or motor cars of the same traction") {
// two electric ones, an electric one of each motor type, two diesel ones, a diesel-mechanical and a
// diesel-electric one, an electric multiple unit's control trailer and its motor car
std::initializer_list<std::pair<char const *, char const *>> const pairs{
{"ep09_v2/104e", "et22_v3/201e-w"},
{"e6act_v2/e6acta", "eu04_v1/eu04-01"},
{"sm03_v1/sm03", "wmb10_v1/wmb10"},
{"sm03_v1/sm03", "st44_v2/m62-1151"},
{"en57_v1/5bgb", "en57_v1/6bai"}};
for (auto const &paths : pairs) {
CAPTURE(paths.first);
CAPTURE(paths.second);
auto first{vehicle{definition::fiz(paths.first), 0.0, "first"}};
auto second{vehicle{definition::fiz(paths.second), 0.0, "second"}};
CHECK(scenario_couple(first, second) == scenario_coupling);
}
}
SUBCASE("a diesel locomotive and a car") {
auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
auto car{vehicle{definition::load("wagon"), 0.0, "car"}};
CHECK(scenario_couple(diesel, car) == scenario_coupling);
}
}
TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive couple without the control connection") {
crash_damage_setting const crashdamage{true};
control_coupling_check_setting const check{true};
auto const flag{coupling::coupler | coupling::brakehose | coupling::control};
auto automatic = [flag](std::string const &Path) {
return definition::fiz(Path).set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", flag);
};
auto moving{vehicle{automatic("e6act_v2/e6acta"), 5.0, "moving"}};
SUBCASE("a diesel one") {
auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}};
test::pair pair{moving, end::front, standing, end::rear, 1.0};
REQUIRE(couple_during(pair, 3.0));
CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose));
}
SUBCASE("an electric one") {
auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}};
test::pair pair{moving, end::front, standing, end::rear, 1.0};
REQUIRE(couple_during(pair, 3.0));
CHECK(pair.coupling() == flag);
}
}
TEST_CASE("couplers: the AI and the player get the coupling the vehicles can take") {
control_coupling_check_setting const check{true};
auto electric{vehicle{definition::fiz("e6act_v2/e6acta"), 0.0, "electric"}};
auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}};
auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}};
CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == (scenario_coupling & ~coupling::control));
CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling);
// nothing to take away without the control connection asked for
CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, coupling::coupler) == coupling::coupler);
}

View File

@@ -177,3 +177,32 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button
CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive);
scenario.check();
}
TEST_CASE("diesel: the SM42's shunt mode, switched on and off with one move of the switch") {
// eu07/maszyna#497: the shunt mode of the diesel-electrics (ShuntMode=1) shares its switch with the motor
// overload relay threshold of the electric locomotives (CurrentSwitch()). the SM42 has no such relay, so
// the switch sets the shunt mode at the first move, at the controller's zero position only
scenario scenario{"diesel/sm42 shunt mode", motion() + traction(), test::track{}};
scenario.add("sm42_v1/6d1", 1);
REQUIRE(scenario.start_up());
auto &sm42{scenario.cab()};
REQUIRE(sm42.ShuntModeAllow);
CHECK_FALSE(sm42.ShuntMode);
scenario.act("shunt mode on");
CHECK(sm42.CurrentSwitch(true));
CHECK(sm42.ShuntMode);
scenario.get_going();
scenario.act("shunting power");
sm42.AnPos = 0.5;
CHECK(sm42.IncMainCtrl(1));
scenario.wait(60.0);
CHECK(sm42.Vel > 1.0);
// not with the controller out of its zero position
CHECK_FALSE(sm42.CurrentSwitch(false));
CHECK(sm42.ShuntMode);
scenario.notch_back(0);
scenario.act("shunt mode off");
CHECK(sm42.CurrentSwitch(false));
CHECK_FALSE(sm42.ShuntMode);
scenario.check();
}

112
tests/unit/test_dimmer.cpp Normal file
View File

@@ -0,0 +1,112 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
using test::definition;
using test::vehicle;
// the headlight dimmer's position indexes the DimmerList of the .fiz. a short or an empty list, or a DefaultPos
// past its end, put the dimmer outside the list, where the lights and the cab read past the end of it
namespace {
// rows: high beam, dimmed, off
nlohmann::ordered_json const plain{"no", "no", "no"};
nlohmann::ordered_json const dimmed{"no", "yes", "no"};
nlohmann::ordered_json const off{"no", "no", "yes"};
definition dimmer_list(nlohmann::ordered_json const &Rows, int const Defaultposition, bool const Cycle = false) {
return definition::load("cab_vehicle")
.set("DimmerList", "rows", Rows)
.set("DimmerList", "Size", static_cast<int>(Rows.size()))
.set("DimmerList", "DefaultPos", Defaultposition)
.set("DimmerList", "Cycle", Cycle ? "yes" : "no");
}
} // namespace
TEST_CASE("dimmer: a position outside the list reads as a plain one, neither off nor dimmed") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({off, dimmed}), 0)};
REQUIRE(cab->dimPositions.size() == 2);
for (auto const position : {-1, 2, 100}) {
CAPTURE(position);
cab->modernDimmerPosition = position;
auto const entry{cab->currentDimPosition()};
CHECK_FALSE(entry.isOff);
CHECK_FALSE(entry.isDimmed);
CHECK_FALSE(entry.isHighBeam);
}
cab->modernDimmerPosition = 0;
CHECK(cab->currentDimPosition().isOff);
cab->modernDimmerPosition = 1;
CHECK(cab->currentDimPosition().isDimmed);
}
TEST_CASE("dimmer: positions are clamped to the list") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)};
CHECK(cab->clampDimmerPosition(-3) == 0);
CHECK(cab->clampDimmerPosition(1) == 1);
CHECK(cab->clampDimmerPosition(3) == 2);
CHECK(cab->clampDimmerPosition(100) == 2);
}
TEST_CASE("dimmer: a DefaultPos past the end of the list starts the dimmer at its last position") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7)};
CHECK(cab->modernDimmerDefaultPosition == 1);
// the cab puts the modern dimmer to its default position when it's entered (TTrain::set_cab_controls())
cab->modernDimmerPosition = cab->modernDimmerDefaultPosition;
CHECK(cab->currentDimPosition().isDimmed);
}
TEST_CASE("dimmer: without the modern dimmer a DefaultPos past the end of the list puts the dimmer at its last position") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7).set("Switches", "ModernDimmer", "No")};
REQUIRE_FALSE(cab->enableModernDimmer);
CHECK(cab->modernDimmerPosition == 1);
CHECK(cab->currentDimPosition().isDimmed);
}
TEST_CASE("dimmer: an empty list leaves the dimmer at 0, reading as a plain position, and it doesn't move") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array(), 3, true)};
REQUIRE(cab->dimPositions.empty());
CHECK(cab->modernDimmerDefaultPosition == 0);
CHECK(cab->modernDimmerPosition == 0);
CHECK(cab->clampDimmerPosition(1) == 0);
CHECK_FALSE(cab->currentDimPosition().isOff);
CHECK_FALSE(cab->stepDimmerPosition(1));
CHECK_FALSE(cab->stepDimmerPosition(-1));
CHECK(cab->modernDimmerPosition == 0);
}
TEST_CASE("dimmer: stepping stays within the list") {
SUBCASE("without cycling it stops at the ends") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)};
CHECK_FALSE(cab->stepDimmerPosition(-1));
CHECK(cab->modernDimmerPosition == 0);
CHECK(cab->stepDimmerPosition(1));
CHECK(cab->stepDimmerPosition(1));
CHECK(cab->modernDimmerPosition == 2);
CHECK_FALSE(cab->stepDimmerPosition(1));
CHECK(cab->modernDimmerPosition == 2);
}
SUBCASE("with cycling it goes around to the other end") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0, true)};
CHECK(cab->stepDimmerPosition(-1));
CHECK(cab->modernDimmerPosition == 2);
CHECK(cab->stepDimmerPosition(1));
CHECK(cab->modernDimmerPosition == 0);
}
SUBCASE("a position past the end steps from the last one") {
vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)};
cab->modernDimmerPosition = 9;
CHECK(cab->stepDimmerPosition(-1));
CHECK(cab->modernDimmerPosition == 1);
cab->modernDimmerPosition = 9;
CHECK(cab->stepDimmerPosition(1)); // can't go further, but comes back into the list
CHECK(cab->modernDimmerPosition == 2);
}
}

View File

@@ -0,0 +1,158 @@
#include "stdafx.h"
#include "doctest.h"
#include "scenario.h"
#include "vehicle.h"
// the door closure signalling (SOD, the i-door_blocked lamp of a cab): the state of each vehicle's doors and of the
// whole train, the most severe of its vehicles, as the driver gathers it for the lamp (eu07/maszyna#288)
using test::scenario;
using test::definition;
using test::vehicle;
using namespace test::channels;
namespace {
// the state of the whole train, the way TController::determine_consist_state() gathers it
door_closure_t consist_closure(scenario &Scenario) {
auto closure{door_closure_t::none};
for (std::size_t i = 0; i < Scenario.train().size(); ++i) {
closure = std::max(closure, Scenario.vehicle(i).door_closure());
}
return closure;
}
} // namespace
TEST_CASE("door closure: the lamp is lit for locked doors, blinks for released ones and is dark for open ones") {
for (auto const lit : {true, false}) {
CAPTURE(lit);
CHECK(door_closure_lamp(door_closure_t::locked, lit));
CHECK(door_closure_lamp(door_closure_t::released, lit) == lit);
CHECK_FALSE(door_closure_lamp(door_closure_t::open, lit));
CHECK_FALSE(door_closure_lamp(door_closure_t::none, lit));
}
// a consist takes the most severe state of its vehicles
CHECK(std::max(door_closure_t::none, door_closure_t::locked) == door_closure_t::locked);
CHECK(std::max(door_closure_t::locked, door_closure_t::released) == door_closure_t::released);
CHECK(std::max(door_closure_t::released, door_closure_t::open) == door_closure_t::open);
}
TEST_CASE("door closure: a unit with permits, locked, released by the permit and open, in any of its cars") {
scenario scenario{"door closure/elf", motion() + doors()};
scenario.add("elf_v1/21we-a", 1).add("elf_v1/21we-b").add("elf_v1/21we-c");
scenario.start_up();
auto &cab{scenario.cab()};
auto &last{scenario.vehicle(scenario.train().size() - 1)};
// closed with no permit: no door can be opened
CHECK(cab.door_closure() == door_closure_t::locked);
CHECK(last.door_closure() == door_closure_t::locked);
CHECK(consist_closure(scenario) == door_closure_t::locked);
scenario.act("permit left");
cab.PermitDoors(side::left, true);
scenario.wait(2.0);
CHECK(last.door_closure() == door_closure_t::released);
CHECK(consist_closure(scenario) == door_closure_t::released);
scenario.act("the last car opens its own door");
last.OperateDoors(side::left, true, range_t::local);
scenario.wait(5.0);
// the cab's own doors stay closed, the train is open all the same
CHECK(cab.door_closure() == door_closure_t::released);
CHECK(last.door_closure() == door_closure_t::open);
CHECK(consist_closure(scenario) == door_closure_t::open);
scenario.act("close, the steps stay out under the permit");
last.OperateDoors(side::left, false, range_t::local);
cab.OperateDoors(side::left, false);
scenario.wait(10.0);
CHECK(last.Doors.instances[side::left].position <= 0.f);
// a step out isn't a closed door
CHECK(consist_closure(scenario) == door_closure_t::open);
scenario.act("revoke the permit");
cab.PermitDoors(side::left, false);
scenario.wait(10.0);
CHECK(consist_closure(scenario) == door_closure_t::locked);
}
TEST_CASE("door closure: the doors of a unit without permits are released at a standstill") {
scenario scenario{"door closure/en57", motion() + doors()};
scenario.add("en57_v1/5bgaiii_led_spot", 1).add("en57_v1/6ba_840").add("en57_v1/5bgb");
scenario.start_up();
auto &cab{scenario.cab()};
auto &middle{scenario.vehicle(1)};
REQUIRE_FALSE(cab.Doors.permit_needed);
REQUIRE(middle.Doors.permit_needed);
// the door lock engages only once the train runs (DoorLockSpeed), till then the end cars' doors can be opened
CHECK(cab.door_closure() == door_closure_t::released);
CHECK(middle.door_closure() == door_closure_t::locked);
CHECK(consist_closure(scenario) == door_closure_t::released);
scenario.act("open right");
cab.OperateDoors(side::right, true);
scenario.wait(10.0);
CHECK(consist_closure(scenario) == door_closure_t::open);
scenario.act("close right");
cab.OperateDoors(side::right, false);
scenario.wait(10.0);
CHECK(consist_closure(scenario) == door_closure_t::released);
}
TEST_CASE("door closure: a locomotive has no doors to signal, its coach does") {
scenario scenario{"door closure/eu07 with a coach", motion() + doors()};
scenario.add("4e_v1/4e", 1).add("bdhpumn_v3/bdhpumn");
scenario.start_up();
CHECK(scenario.cab().door_closure() == door_closure_t::none);
scenario.act("open right");
scenario.cab().PermitDoors(side::right, true);
scenario.cab().OperateDoors(side::right, true);
scenario.wait(10.0);
CHECK(scenario.vehicle(1).door_closure() == door_closure_t::open);
CHECK(consist_closure(scenario) == door_closure_t::open);
}
TEST_CASE("door closure: the signalling is switched on by DoorClosureSignal in the Doors section, off without it") {
SUBCASE("without the key") {
vehicle wagon{definition::load("wagon")};
CHECK_FALSE(wagon->Doors.closure_signal);
}
SUBCASE("with the key") {
vehicle wagon{definition::load("wagon").set("Doors", "DoorClosureSignal", "Yes")};
CHECK(wagon->Doors.closure_signal);
}
}
TEST_CASE("door closure: without DoorClosureSignal the lamp shows the lock of the vehicle's own doors, as before") {
vehicle wagon{definition::load("wagon")};
REQUIRE_FALSE(wagon->Doors.closure_signal);
for (auto const locked : {true, false}) {
wagon->Doors.is_locked = locked;
for (auto const consist : {door_closure_t::none, door_closure_t::locked, door_closure_t::released, door_closure_t::open}) {
for (auto const lit : {true, false}) {
CAPTURE(locked);
CAPTURE(static_cast<int>(consist));
CAPTURE(lit);
// no blinking at a standstill with the doors closed, whatever the consist does
CHECK(wagon->door_closure_lamp_lit(consist, lit) == locked);
}
}
}
}
TEST_CASE("door closure: with DoorClosureSignal the lamp shows the consist in three states") {
vehicle wagon{definition::load("wagon").set("Doors", "DoorClosureSignal", "Yes")};
REQUIRE(wagon->Doors.closure_signal);
for (auto const locked : {true, false}) {
// the vehicle's own lock doesn't matter, the consist does
wagon->Doors.is_locked = locked;
for (auto const lit : {true, false}) {
CAPTURE(locked);
CAPTURE(lit);
CHECK(wagon->door_closure_lamp_lit(door_closure_t::locked, lit));
CHECK(wagon->door_closure_lamp_lit(door_closure_t::released, lit) == lit);
CHECK_FALSE(wagon->door_closure_lamp_lit(door_closure_t::open, lit));
CHECK_FALSE(wagon->door_closure_lamp_lit(door_closure_t::none, lit));
}
}
}

View File

@@ -0,0 +1,54 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle/doorwings.h"
// the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low
// poly interior get the same pose, worked out once from the door position of the mover
TEST_CASE("door wings: only the door animations move wings") {
CHECK(door_wings::is_wing(0x010)); // TAnim::TypeSet for the doors
CHECK_FALSE(door_wings::is_wing(0x000)); // axles
CHECK_FALSE(door_wings::is_wing(0x055)); // pantographs, five submodels
CHECK_FALSE(door_wings::is_wing(0x070)); // doorsteps
CHECK_FALSE(door_wings::is_wing(0x080)); // mirrors
CHECK(door_wings::is_wing(0x210)); // the parameter count in the upper bits doesn't matter
}
TEST_CASE("door wings: odd wings are on the left, even ones on the right") {
CHECK_FALSE(door_wings::on_right_side(1));
CHECK(door_wings::on_right_side(2));
CHECK_FALSE(door_wings::on_right_side(3));
CHECK(door_wings::on_right_side(4));
}
TEST_CASE("door wings: a sliding wing shifts along the vehicle by the door position") {
CHECK(door_wings::slide(0.f) == glm::vec3(0.f, 0.f, 0.f));
CHECK(door_wings::slide(0.65f) == glm::vec3(0.f, 0.f, 0.65f));
}
TEST_CASE("door wings: a plug wing goes out first, then slides") {
auto const rangeout{0.1f};
// closed
CHECK(door_wings::plug(0.f, rangeout) == glm::vec3(0.f, 0.f, 0.f));
// still going out, and not sliding yet
auto const out{door_wings::plug(0.02f, rangeout)};
CHECK(out.x == doctest::Approx(0.04f));
CHECK(out.z == 0.f);
// out as far as it goes, sliding by what the position has beyond half of the way out
auto const open{door_wings::plug(0.7f, rangeout)};
CHECK(open.x == rangeout);
CHECK(open.y == 0.f);
CHECK(open.z == doctest::Approx(0.65f));
}
TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as far the other way") {
auto const angles{door_wings::fold(40.f)};
CHECK(angles.smaller == 40.f);
CHECK(angles.larger == -80.f);
CHECK(angles.step == 40.f);
auto const closed{door_wings::fold(0.f)};
CHECK(closed.smaller == 0.f);
CHECK(closed.larger == 0.f);
CHECK(closed.step == 0.f);
}

View File

@@ -0,0 +1,256 @@
#include "stdafx.h"
#include "doctest.h"
#include "consist.h"
#include "drive.h"
#include "McZapkie/hamulce.h"
#include <initializer_list>
#include <string>
// the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below
// them which EIMCtrlMainEmergency adds (eu07/maszyna#413)
using test::definition;
using test::vehicle;
namespace {
// the data of an Elf: without the emergency brake position as now, with it in the files updated for it
// (EIMCtrlMainEmergency, MCPN=5, DirChangeMaxPos=4), or with the key alone added to the old files, which the
// loader fixes up
enum class data { plain, emergency, emergency_old_layout };
// three-car Elfs coupled into one train, of the given data each, ready to run, standing with their brakes
// released and the driver in the front cab of the head car of the first one, which also drives (the
// controller's eimic is worked out there)
struct elf {
explicit elf(bool Emergency) : elf({Emergency ? data::emergency : data::plain}) {}
explicit elf(std::initializer_list<data> Units) {
for (auto const units : Units) {
for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) {
auto cardefinition{definition::fiz(car)};
if (units != data::plain) {
cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes");
}
if (units == data::emergency) {
cardefinition.set("Cntrl", "MCPN", 5);
if (std::string{car} != "elf_v1/21we-b") {
// the cars with a cab have it, at neutral: 3 before, one up with the key
cardefinition.set("Cntrl", "DirChangeMaxPos", 4);
}
}
unit.add(cardefinition, unit.size() == 0 ? 1 : 0);
}
}
ready = test::start_up(test::driving(unit), line);
// the start-up of the tests leaves the controller at its position 0 (close_line_breaker() in drive.cpp),
// the emergency brake one with EIMCtrlMainEmergency; the driver sets it to neutral, as the AI does. a unit
// moves its controller only with a direction set
for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) {
cab().DirectionForward();
}
while (cab().MainCtrlPos < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) {
// up to neutral
}
test::release_brakes(cab());
recharge();
charged = cab().PipePress > 4.5;
}
// the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn,
// LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running
void recharge() {
cab().BrakeLevelSet(cab().Handle->GetPos(bh_RP));
cab().UniversalBrakeButton(0, 1);
wait(30.0);
cab().UniversalBrakeButton(0, 0);
wait(30.0);
}
TMoverParameters &cab() { return unit[0].mover(); }
TMoverParameters &car(std::size_t Index) { return unit[Index].mover(); }
// the driver moves the controller notch by notch, which the cab sends on to the coupled vehicles
void set_controller(int Position) {
while (cab().MainCtrlPos < Position && cab().IncMainCtrl(1)) {
}
while (cab().MainCtrlPos > Position && cab().DecMainCtrl(1)) {
}
}
void wait(double Seconds) { test::drive(test::driving(unit), line, Seconds); }
test::consist unit;
test::track line{0.15, 0.0, test::catenary_3kv};
bool ready{false};
bool charged{false};
};
} // namespace
TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as they were") {
elf unit{false};
REQUIRE(unit.ready);
REQUIRE(unit.charged);
auto &mover{unit.cab()};
CHECK_FALSE(mover.EIMCtrlMainEmergency);
CHECK(mover.EIMCtrlEmergencyPositions() == 0);
CHECK(mover.MainCtrlPosNo == 4);
CHECK(mover.MainCtrlNoPowerPos() == 3);
CHECK(mover.MainCtrlPos == 3);
// the lowest position brakes fully, without emptying the pipe
mover.MainCtrlPos = 0;
CHECK_FALSE(mover.IsMainCtrlEmergencyPos());
unit.wait(10.0);
CHECK(mover.eimic == doctest::Approx(-1.0));
CHECK(mover.PipePress > 4.5);
}
TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") {
elf unit{true};
REQUIRE(unit.ready);
REQUIRE(unit.charged);
auto &mover{unit.cab()};
CHECK(mover.EIMCtrlMainEmergency);
CHECK(mover.EIMCtrlEmergencyPositions() == 1);
CHECK(mover.MainCtrlPosNo == 5);
CHECK(mover.MainCtrlNoPowerPos() == 4);
CHECK(mover.MainCtrlPos == 4);
CHECK_FALSE(mover.IsMainCtrlEmergencyPos());
SUBCASE("the neutral position neither drives nor brakes") {
unit.wait(5.0);
CHECK(mover.eimic == doctest::Approx(0.0));
}
SUBCASE("the full braking position, formerly 0, brakes fully without emptying the pipe") {
mover.MainCtrlPos = 1;
unit.wait(10.0);
CHECK(mover.eimic == doctest::Approx(-1.0));
CHECK(mover.PipePress > 4.5);
}
SUBCASE("the braking position, formerly 1, ramps the braking up") {
mover.MainCtrlPos = 2;
unit.wait(1.0);
CHECK(mover.eimic < 0.0);
CHECK(mover.eimic > -1.0);
CHECK(mover.PipePress > 4.5);
}
SUBCASE("the emergency brake position brakes fully at once and empties the pipe") {
mover.MainCtrlPos = 0;
CHECK(mover.IsMainCtrlEmergencyPos());
// a single step of the physics
unit.unit.step(unit.line);
CHECK(mover.eimic == doctest::Approx(-1.0));
unit.wait(10.0);
CHECK(mover.PipePress < 0.5);
CHECK(mover.BrakePress > 1.0);
// out of it the pipe charges again
mover.MainCtrlPos = mover.MainCtrlNoPowerPos();
CHECK_FALSE(mover.IsMainCtrlEmergencyPos());
unit.recharge();
CHECK(mover.PipePress > 4.5);
}
}
TEST_CASE("elf controller: EIMCtrlMainEmergency with the old MCPN gets its positions all the same") {
vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes")};
CHECK(car->MainCtrlPosNo == 5);
CHECK(car->MainCtrlNoPowerPos() == 4);
// DirChangeMaxPos=3 of the file, the old neutral, moves up with the positions
CHECK(car->MainCtrlMaxDirChangePos == 4);
}
TEST_CASE("elf controller: EIMCtrlMainEmergency leaves DirChangeMaxPos of the files updated for it alone") {
vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5).set("Cntrl", "DirChangeMaxPos", 4)};
CHECK(car->MainCtrlPosNo == 5);
CHECK(car->MainCtrlMaxDirChangePos == 4);
}
TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlMainEmergency") {
// the key added to the old files, DirChangeMaxPos=3 in them
elf unit{{data::emergency_old_layout}};
REQUIRE(unit.ready);
auto &mover{unit.cab()};
REQUIRE(mover.MainCtrlPos == mover.MainCtrlNoPowerPos());
REQUIRE(mover.DirActive == 1);
CHECK(mover.DirectionBackward());
CHECK(mover.DirActive == 0);
CHECK(mover.DirectionForward());
CHECK(mover.DirActive == 1);
// not in the power position
unit.set_controller(mover.MainCtrlNoPowerPos() + 1);
REQUIRE(mover.MainCtrlPos == 5);
CHECK_FALSE(mover.DirectionBackward());
CHECK(mover.DirActive == 1);
}
TEST_CASE("elf controller: the emergency brake position vents the pipe only from the vehicle driven from") {
elf unit{true};
REQUIRE(unit.ready);
REQUIRE(unit.charged);
// the rear car, with its own cab, has its controller in the emergency brake position, the driven one not
auto &rear{unit.car(2)};
rear.MainCtrlPos = 0;
CHECK(rear.IsMainCtrlEmergencyPos());
CHECK_FALSE(rear.IsCabMaster());
unit.wait(10.0);
CHECK(unit.cab().PipePress > 4.5);
CHECK(rear.PipePress > 4.5);
}
TEST_CASE("elf controller: an Elf with the emergency brake position leading one without it") {
elf unit{{data::emergency, data::plain}};
REQUIRE(unit.ready);
REQUIRE(unit.charged);
auto &lead{unit.cab()};
auto &other{unit.car(3)};
REQUIRE_FALSE(other.EIMCtrlMainEmergency);
// neutral of the lead is neutral of the other
CHECK(lead.MainCtrlPos == 4);
CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos());
SUBCASE("power") {
unit.set_controller(5);
CHECK(other.MainCtrlPos == 4);
}
SUBCASE("full braking") {
unit.set_controller(1);
CHECK(other.MainCtrlPos == 0);
unit.wait(10.0);
CHECK(lead.PipePress > 4.5);
}
SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") {
unit.set_controller(0);
REQUIRE(lead.IsMainCtrlEmergencyPos());
CHECK(other.MainCtrlPos == 0);
unit.wait(10.0);
CHECK(lead.PipePress < 0.5);
CHECK(other.PipePress < 0.5);
}
}
TEST_CASE("elf controller: an Elf without the emergency brake position leading one with it") {
elf unit{{data::plain, data::emergency}};
REQUIRE(unit.ready);
REQUIRE(unit.charged);
auto &lead{unit.cab()};
auto &other{unit.car(3)};
REQUIRE(other.EIMCtrlMainEmergency);
CHECK(lead.MainCtrlPos == 3);
CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos());
SUBCASE("power") {
unit.set_controller(4);
CHECK(other.MainCtrlPos == 5);
}
SUBCASE("the full braking of the lead is the full braking of the other, not its emergency brake") {
unit.set_controller(0);
CHECK(other.MainCtrlPos == 1);
CHECK_FALSE(other.IsMainCtrlEmergencyPos());
unit.wait(10.0);
CHECK(lead.PipePress > 4.5);
CHECK(other.PipePress > 4.5);
}
}
TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alone") {
// the Impuls (EIMCtrlType 0) has its emergency brake in the brake range of its controller (EIMCtrlEmergency)
vehicle impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "EIMCtrlMainEmergency", "Yes"), 60.0, "impuls", 1};
CHECK(impuls->EIMCtrlEmergencyPositions() == 0);
CHECK(impuls->MainCtrlPosNo == 10);
impuls->MainCtrlPos = 0;
CHECK_FALSE(impuls->IsMainCtrlEmergencyPos());
}

View File

@@ -0,0 +1,298 @@
#include "stdafx.h"
#include "doctest.h"
#include "consist.h"
#include "vehicle/enginestart.h"
// starting the engines of the vehicles in multiple from the cab (eu07/maszyna#80): the cab's own switch (main_*) works
// all of them unless Engine:JointEngineStart=No keeps it to its own vehicle, and the switches mainb_* and mainc_* start
// the second and the third vehicle alone. the cab (TTrain) passes the vehicle's MainSwitchRange() to its MainSwitch(),
// finds the vehicles with engine(), and runs remote_switch for the switches of the others
using test::consist;
using test::definition;
namespace {
// the SN61 railcar, whose cab has a set of switches for each of up to three railcars in multiple
definition sn61(bool const Joint = true) {
auto railcar{definition::fiz("sn61_v2/sn61")};
if (false == Joint) {
railcar.set("Engine", "JointEngineStart", "No");
}
return railcar;
}
// the battery, the cab and the pumps of every railcar of the train switched on from the first one's cab, the oil
// pressure built up, and the controller at the first position giving the engines fuel, which a mechanical diesel
// starts at: everything but the engines ready to start
void prepare(consist &Train) {
auto &cab{Train[0].mover()};
cab.BatterySwitch(true);
cab.CabActivisation();
cab.OilPumpSwitch(true);
cab.FuelPumpSwitch(true);
while (cab.RList[cab.MainCtrlPos].R == 0.0 && cab.IncMainCtrl(1)) {
// up to the first position with fuel
}
Train.run(20.0);
}
bool running(TMoverParameters const &Vehicle) {
return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.dizel_nmin;
}
// the time step of the train in the loops below
auto const dt{0.01};
// the count of the steps of dt making up Seconds
int steps(double const Seconds) {
return static_cast<int>(std::lround(Seconds / dt));
}
// the switch of Engine held closed for Seconds, then let go, in steps of the train
void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters *Engine, double const Seconds, bool const Closesonrelease = false) {
for (auto step = 0; step < steps(Seconds); ++step) {
Switch.update(Engine, true, false, dt, Closesonrelease);
Train.step({}, dt);
}
Switch.update(Engine, false, false, dt, Closesonrelease);
}
} // namespace
TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No keeps the cab's switch to its vehicle") {
consist train;
auto const &joint{train.add(sn61(), 1).mover()};
auto const &separate{train.add(sn61(false)).mover()};
CHECK(joint.JointEngineStart);
CHECK_FALSE(separate.JointEngineStart);
CHECK(joint.MainSwitchRange() == range_t::consist);
CHECK(separate.MainSwitchRange() == range_t::local);
}
TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own one, those behind the cab first") {
consist train;
auto &first{train.add(sn61(), 1).mover()};
auto &second{train.add(sn61()).mover()};
auto &third{train.add(sn61()).mover()};
CHECK(engine_start::engine(first, first, 1) == &first);
CHECK(engine_start::engine(first, first, 2) == &second);
CHECK(engine_start::engine(first, first, 3) == &third);
CHECK(engine_start::engine(first, first, 4) == nullptr);
CHECK(engine_start::engine(first, first, 0) == nullptr);
// from the rear cab of the first railcar the others are in front of the cab, in the same order
first.CabOccupied = -1;
CHECK(engine_start::engine(first, first, 2) == &second);
CHECK(engine_start::engine(first, first, 3) == &third);
// from the middle one, the one behind its cab comes first
second.CabOccupied = 1;
CHECK(engine_start::engine(second, second, 2) == &third);
CHECK(engine_start::engine(second, second, 3) == &first);
second.CabOccupied = -1;
CHECK(engine_start::engine(second, second, 2) == &first);
CHECK(engine_start::engine(second, second, 3) == &third);
}
TEST_CASE("engine start: only the vehicles with an engine and under control through the cable count") {
consist train;
auto &first{train.add(sn61(), 1).mover()};
// a vehicle without an engine between the railcars is passed over
auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).mover()};
auto &second{train.add(sn61()).mover()};
REQUIRE(trailer.Power < 0.01);
CHECK(engine_start::engine(first, first, 2) == &second);
// the vehicle with the cab doesn't drive itself: its engine is in the vehicle it controls, which isn't counted twice
trailer.CabOccupied = 1;
CHECK(engine_start::engine(trailer, first, 1) == &first);
CHECK(engine_start::engine(trailer, first, 2) == &second);
CHECK(engine_start::engine(trailer, first, 3) == nullptr);
// coupled without the control cable, the other railcar isn't under the cab's control
consist apart;
auto &alone{apart.add(sn61(), 1).mover()};
apart.add(sn61(), 0, coupling::coupler | coupling::brakehose);
CHECK(engine_start::engine(alone, alone, 2) == nullptr);
}
TEST_CASE("engine start: by default the cab's switch starts and stops the engines of all the vehicles in multiple") {
consist train;
auto &first{train.add(sn61(), 1).mover()};
auto const &second{train.add(sn61()).mover()};
prepare(train);
REQUIRE_FALSE(first.Mains);
REQUIRE_FALSE(second.Mains);
first.MainSwitch(true, first.MainSwitchRange());
train.run(15.0);
CHECK(running(first));
CHECK(running(second));
first.MainSwitch(false, first.MainSwitchRange());
train.run(5.0);
CHECK_FALSE(first.Mains);
CHECK_FALSE(second.Mains);
}
TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") {
consist train;
auto &first{train.add(sn61(false), 1).mover()};
auto &second{train.add(sn61(false)).mover()};
auto &third{train.add(sn61(false)).mover()};
prepare(train);
// the cab's own switch starts its own engine only
first.MainSwitch(true, first.MainSwitchRange());
train.run(15.0);
REQUIRE(running(first));
CHECK_FALSE(second.Mains);
CHECK_FALSE(third.Mains);
// the second one's switch, mainb_*, starts the second engine
engine_start::remote_switch switchb;
engine_start::remote_switch switchc;
auto *engineb{engine_start::engine(first, first, 2)};
auto *enginec{engine_start::engine(first, first, 3)};
REQUIRE(engineb == &second);
REQUIRE(enginec == &third);
hold(train, switchb, engineb, 2.0); // past the SN61's delay of 1.5 s
train.run(15.0);
CHECK(running(second));
CHECK_FALSE(third.Mains);
// and the third one's, mainc_*, the third
hold(train, switchc, enginec, 2.0);
train.run(15.0);
CHECK(running(third));
// the switches open their own vehicles' circuits only
CHECK(engine_start::remote_switch::open(second));
train.run(5.0);
CHECK_FALSE(second.Mains);
CHECK(running(first));
CHECK(running(third));
first.MainSwitch(false, first.MainSwitchRange());
train.run(5.0);
CHECK_FALSE(first.Mains);
CHECK(running(third));
CHECK_FALSE(engine_start::remote_switch::open(second)); // already stopped
}
TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's delay, with the vehicle ready") {
consist train;
train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0"), 1);
auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).mover()};
REQUIRE(second.InitialCtrlDelay == doctest::Approx(2.0));
engine_start::remote_switch switchb;
// without the battery the switch does nothing, however long it's held
hold(train, switchb, &second, 5.0);
train.run(5.0);
CHECK_FALSE(second.Mains);
CHECK_FALSE(second.dizel_startup);
prepare(train);
// let go too early
hold(train, switchb, &second, 1.0);
CHECK_FALSE(engine_start::remote_switch::is_running(second));
// the switch opening the circuit held along, the closing one does nothing
for (auto step = 0; step < steps(3.0); ++step) {
switchb.update(&second, true, true, dt, false);
train.step({}, dt);
}
CHECK_FALSE(engine_start::remote_switch::is_running(second));
// held long enough
hold(train, switchb, &second, 2.5);
CHECK(engine_start::remote_switch::is_running(second));
train.run(15.0);
CHECK(running(second));
}
TEST_CASE("engine start: a switch closing on release, as an electric locomotive's impulse switch, waits to be let go") {
consist train;
train.add(sn61(false), 1);
auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).mover()};
prepare(train);
engine_start::remote_switch switchb;
// held past the delay, the circuit stays open while the switch is held
for (auto step = 0; step < steps(2.0); ++step) {
switchb.update(&second, true, false, dt, true);
train.step({}, dt);
}
CHECK_FALSE(engine_start::remote_switch::is_running(second));
// and closes when let go
switchb.update(&second, false, false, dt, true);
CHECK(engine_start::remote_switch::is_running(second));
train.run(15.0);
REQUIRE(running(second));
// let go before the delay, it doesn't
CHECK(engine_start::remote_switch::open(second));
train.run(5.0);
REQUIRE_FALSE(engine_start::remote_switch::is_running(second));
hold(train, switchb, &second, 0.5, true);
CHECK_FALSE(engine_start::remote_switch::is_running(second));
}
TEST_CASE("engine start: an engine stopping on its own stops the others only when they started together") {
for (auto const joint : {true, false}) {
CAPTURE(joint);
consist train;
auto &first{train.add(sn61(joint), 1).mover()};
auto const &second{train.add(sn61(joint)).mover()};
prepare(train);
engine_start::remote_switch switchb;
first.MainSwitch(true, first.MainSwitchRange());
hold(train, switchb, engine_start::engine(first, first, 2), 2.0);
train.run(15.0);
REQUIRE(running(first));
REQUIRE(running(second));
// the first one's fuel cut off, its engine stops
first.FuelPump.is_disabled = true;
train.run(15.0);
CHECK_FALSE(first.Mains);
CHECK(first.enrot == 0.0);
// started on their own, the others keep running
CHECK(running(second) == (false == joint));
}
}
// a stopped engine stays stopped on its own: only an engine stopping while it ran tells the others, as a joint start's
// engines stop together; one stopped from another vehicle's switch, or not started at all, doesn't stop those running,
// whatever the flags of the vehicles in a mixed train
TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the others when it has spun down") {
consist train;
// the middle railcar keeps the joint start, as a .fiz without the key does. what a vehicle without the cab relays
// goes on away from the cab, so it's the third one that would stop
auto &first{train.add(sn61(false), 1).mover()};
auto &second{train.add(sn61()).mover()};
auto &third{train.add(sn61(false)).mover()};
prepare(train);
engine_start::remote_switch switchb;
engine_start::remote_switch switchc;
first.MainSwitch(true, first.MainSwitchRange());
hold(train, switchb, engine_start::engine(first, first, 2), 2.0);
hold(train, switchc, engine_start::engine(first, first, 3), 2.0);
train.run(15.0);
REQUIRE(running(first));
REQUIRE(running(second));
REQUIRE(running(third));
// mainb_off
CHECK(engine_start::remote_switch::open(second));
train.run(30.0);
CHECK_FALSE(second.Mains);
CHECK(second.enrot == 0.0);
CHECK(running(first));
CHECK(running(third));
}
TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop the one started from its switch") {
consist train;
// the cab's railcar keeps the joint start, its engine stopped
auto &first{train.add(sn61(), 1).mover()};
auto &second{train.add(sn61(false)).mover()};
prepare(train);
REQUIRE_FALSE(first.Mains);
// mainb_on
engine_start::remote_switch switchb;
hold(train, switchb, engine_start::engine(first, first, 2), 2.0);
train.run(15.0);
CHECK(running(second));
CHECK_FALSE(first.Mains);
CHECK(first.enrot == 0.0);
}

View File

@@ -0,0 +1,110 @@
#include "stdafx.h"
#include "doctest.h"
#include "utilities/framepacer.h"
// the main loop's frame limiter (fpslimit in eu07.ini, eu07/maszyna#416), driven with made-up clock readings
namespace
{
using namespace std::chrono_literals;
using clock_type = frame_pacer::clock;
clock_type::time_point const kStart{clock_type::time_point{} + 100s};
constexpr clock_type::duration kFrame{std::chrono::duration_cast<clock_type::duration>(std::chrono::duration<float>(1.f / 30.f))};
// runs frames that take Work each, with every wait overshooting by Oversleep; returns when the last of Frames ends
clock_type::time_point run_frames(frame_pacer &Pacer, int const Frames, clock_type::duration const Work, clock_type::duration const Oversleep)
{
auto now{kStart};
for (auto frame = 0; frame < Frames; ++frame)
{
now += Work;
if (auto const next{Pacer.next_frame(now, kFrame)})
{
CHECK(*next > now);
now = *next + Oversleep;
}
}
return now;
}
} // namespace
TEST_CASE("frame pacer: without a limit nothing waits")
{
frame_pacer pacer;
CHECK_FALSE(pacer.next_frame(kStart, clock_type::duration::zero()).has_value());
CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value());
}
TEST_CASE("frame pacer: a quick frame waits out the rest of the frame time")
{
frame_pacer pacer;
// the first frame only sets the cadence
CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
auto const next{pacer.next_frame(kStart + 5ms, kFrame)};
REQUIRE(next.has_value());
CHECK(*next == kStart + kFrame);
}
TEST_CASE("frame pacer: a slow frame doesn't wait")
{
frame_pacer pacer;
CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
CHECK_FALSE(pacer.next_frame(kStart + kFrame + 5ms, kFrame).has_value());
}
TEST_CASE("frame pacer: the frame rate holds the limit with fast frames")
{
frame_pacer pacer;
auto const end{run_frames(pacer, 301, 2ms, clock_type::duration::zero())};
// 300 paced frames after the first
CHECK(end == kStart + 2ms + 300 * kFrame);
}
TEST_CASE("frame pacer: a wait that overshoots is made up in the next frame")
{
// the windows timer wakes a sleeping thread up to ~15.6 ms late; sleeping off what is left of each frame
// then drops 30 fps to about 22. on a fixed cadence the frame rate still averages to the limit
frame_pacer pacer;
auto const end{run_frames(pacer, 301, 2ms, 12ms)};
auto const elapsed{std::chrono::duration<double>(end - kStart).count()};
CHECK(300.0 / elapsed == doctest::Approx(30.0).epsilon(0.01));
}
TEST_CASE("frame pacer: after a long frame the cadence starts anew instead of catching up")
{
frame_pacer pacer;
CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
// a hitch of half a second
auto const late{kStart + 500ms};
CHECK_FALSE(pacer.next_frame(late, kFrame).has_value());
// the next quick frame waits a whole frame time from there rather than running at once
auto const next{pacer.next_frame(late + 1ms, kFrame)};
REQUIRE(next.has_value());
CHECK(*next == late + kFrame);
}
TEST_CASE("frame pacer: turning the limit off and on again starts a new cadence")
{
frame_pacer pacer;
CHECK_FALSE(pacer.next_frame(kStart, kFrame).has_value());
CHECK_FALSE(pacer.next_frame(kStart + 1ms, clock_type::duration::zero()).has_value());
CHECK_FALSE(pacer.next_frame(kStart + 2s, kFrame).has_value());
auto const next{pacer.next_frame(kStart + 2s + 1ms, kFrame)};
REQUIRE(next.has_value());
CHECK(*next == kStart + 2s + kFrame);
}
TEST_CASE("frame pacer: the wait stays exact after days of system uptime")
{
// fpslimit 60 gives the frame time as float seconds; the old limiter handed the float rest of the frame
// to sleep_for, which adds it to steady_clock::now() in float nanoseconds. after 95 hours of uptime that
// rounds the wake-up time to steps of ~33 ms, and a 14 ms wait came out as no wait at all
frame_pacer pacer;
std::chrono::duration<float> const frametime{1.f / 60.f};
auto const uptime{clock_type::time_point{} + 95h};
CHECK_FALSE(pacer.next_frame(uptime, frametime).has_value());
auto const next{pacer.next_frame(uptime + 2ms, frametime)};
REQUIRE(next.has_value());
auto const wait{std::chrono::duration<double, std::milli>(*next - (uptime + 2ms)).count()};
CHECK(wait == doctest::Approx(1000.0 / 60.0 - 2.0).epsilon(0.001));
}

View File

@@ -0,0 +1,53 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle/gaugeduplicates.h"
// cab controls with more than one submodel (eu07/maszyna#527): a definition of a control in the .mmd marked
// "duplicate: yes" adds a copy of the control already defined in the cab, instead of replacing it. TGauge itself
// (3d models, sounds) is not part of the core library, the rule which decides it is
namespace {
// stand-ins for the 3d models of the cab
struct model {};
} // namespace
TEST_CASE("gauge duplicates: the values of the duplicate key which mark a duplicate") {
CHECK(gauge_duplicates::is_duplicate("yes"));
CHECK(gauge_duplicates::is_duplicate("true"));
CHECK(gauge_duplicates::is_duplicate("1"));
CHECK_FALSE(gauge_duplicates::is_duplicate("no"));
CHECK_FALSE(gauge_duplicates::is_duplicate("false"));
CHECK_FALSE(gauge_duplicates::is_duplicate("0"));
CHECK_FALSE(gauge_duplicates::is_duplicate(""));
}
TEST_CASE("gauge duplicates: a duplicate adds a copy to the control loaded from either model of the cab") {
model cab;
model lowpoly;
CHECK(gauge_duplicates::adds_copy<model>(true, &cab, &cab, &lowpoly));
CHECK(gauge_duplicates::adds_copy<model>(true, &lowpoly, &cab, &lowpoly));
// a cab without a low poly interior
CHECK(gauge_duplicates::adds_copy<model>(true, &cab, &cab, nullptr));
}
TEST_CASE("gauge duplicates: a definition not marked as a duplicate replaces the control, as before") {
model cab;
model lowpoly;
CHECK_FALSE(gauge_duplicates::adds_copy<model>(false, &cab, &cab, &lowpoly));
CHECK_FALSE(gauge_duplicates::adds_copy<model>(false, nullptr, &cab, &lowpoly));
}
TEST_CASE("gauge duplicates: with nothing loaded in this cab a duplicate is the control itself") {
model cab;
model lowpoly;
model previouscab;
// the control isn't defined before it
CHECK_FALSE(gauge_duplicates::adds_copy<model>(true, nullptr, &cab, &lowpoly));
CHECK_FALSE(gauge_duplicates::adds_copy<model>(true, nullptr, &cab, nullptr));
// the control is left over from the cab loaded before
CHECK_FALSE(gauge_duplicates::adds_copy<model>(true, &previouscab, &cab, &lowpoly));
CHECK_FALSE(gauge_duplicates::adds_copy<model>(true, &previouscab, &cab, nullptr));
}

View File

@@ -0,0 +1,130 @@
#include "stdafx.h"
#include "doctest.h"
#include "consist.h"
#include "utilities/parser.h"
#include "vehicle/gaugescale.h"
#include "vehicle/mainctrlact.h"
// the controller position marker of the diesel locomotives (MaSzyna-EU07/maszyna#74): the mainctrlact: gauge of
// the ST43 follows its controller, on a scale whose marks are not evenly spaced (scaletable:)
using test::consist;
using test::definition;
namespace {
gauge_scale::table read(std::string const &Text) {
cParser parser(Text, cParser::buffer_TEXT);
return gauge_scale::read(parser);
}
} // namespace
TEST_CASE("gauge scale: a table is read with or without commas, the brackets touching the numbers or not") {
for (auto const *text : {"[ 0 0, 1 0.5, 2 0.6 ]", "[0 0 1 0.5 2 0.6]", "[ 0 0,1 0.5,2 0.6]"}) {
CAPTURE(text);
auto const table{read(text)};
CHECK(table.closed);
CHECK_FALSE(table.block_end);
CHECK_FALSE(table.malformed);
REQUIRE(table.points.size() == 3);
CHECK(table.points[1].value == doctest::Approx(1.0));
CHECK(table.points[1].scaled == doctest::Approx(0.5));
}
}
TEST_CASE("gauge scale: the table leaves the rest of the gauge's block to be read") {
cParser parser("[ 0 0, 1 0.5 ] soundinc: x.wav }", cParser::buffer_TEXT);
CHECK(gauge_scale::read(parser).closed);
CHECK(parser.getToken<std::string>(true, "\n\r\t ,;") == "soundinc:");
}
TEST_CASE("gauge scale: a table without its closing bracket stops at the end of the block") {
auto const table{read("[ 0 0, 1 0.5 }")};
CHECK_FALSE(table.closed);
CHECK(table.block_end);
CHECK(table.points.size() == 2);
}
TEST_CASE("gauge scale: a value without what the gauge shows for it, or a word, makes a malformed table") {
CHECK(read("[ 0 0, 1 ]").malformed);
CHECK(read("[ 0 0, 1 x ]").malformed);
CHECK(read("[ 0 0, 1 x ]").points.size() == 1);
}
TEST_CASE("gauge scale: the points are put in the order of their values") {
auto const table{read("[ 2 0.6, 0 0, 1 0.5 ]")};
REQUIRE(table.points.size() == 3);
CHECK(table.points[0].value == doctest::Approx(0.0));
CHECK(table.points[2].value == doctest::Approx(2.0));
}
TEST_CASE("gauge scale: the gauge shows what the table gives, interpolated between its points") {
auto const table{read("[ 0 0, 1 -0.05, 2 -0.07, 4 -0.08 ]")};
CHECK(gauge_scale::interpolate(table.points, 0.f) == doctest::Approx(0.0));
CHECK(gauge_scale::interpolate(table.points, 1.f) == doctest::Approx(-0.05));
CHECK(gauge_scale::interpolate(table.points, 0.5f) == doctest::Approx(-0.025)); // a marker on its way
CHECK(gauge_scale::interpolate(table.points, 3.f) == doctest::Approx(-0.075));
CHECK(gauge_scale::interpolate(table.points, 4.f) == doctest::Approx(-0.08));
// past the ends the marker stays at them
CHECK(gauge_scale::interpolate(table.points, -1.f) == doctest::Approx(0.0));
CHECK(gauge_scale::interpolate(table.points, 9.f) == doctest::Approx(-0.08));
}
TEST_CASE("gauge scale: two points of the same value make a step") {
auto const table{read("[ 0 0, 1 0.1, 1 0.5, 2 0.6 ]")};
CHECK(gauge_scale::interpolate(table.points, 0.99f) == doctest::Approx(0.099));
CHECK(gauge_scale::interpolate(table.points, 1.f) == doctest::Approx(0.5));
CHECK(gauge_scale::interpolate(table.points, 1.5f) == doctest::Approx(0.55));
}
TEST_CASE("main ctrl act: the marker of a diesel locomotive with a scaletable: follows its controller (MaSzyna-EU07/maszyna#74)") {
// nothing sets the actual position of a diesel engine's controller, the marker stayed at 0
for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) {
CAPTURE(path);
consist train;
auto &locomotive{train.add(definition::fiz(path), 1).mover()};
REQUIRE((locomotive.EngineType == TEngineType::DieselElectric || locomotive.EngineType == TEngineType::DieselEngine));
REQUIRE(locomotive.EIMCtrlType == 0);
locomotive.MainCtrlPos = 5;
CHECK(locomotive.MainCtrlActualPos == 0);
CHECK(main_ctrl_act::position(locomotive, true) == doctest::Approx(5.0));
// one with a controller of the EIM kind keeps its actual position itself
locomotive.EIMCtrlType = 2;
CHECK(main_ctrl_act::position(locomotive, true) == doctest::Approx(0.0));
}
}
TEST_CASE("main ctrl act: the marker of a diesel locomotive without a scaletable: stays still, as before") {
// the shipped ST43 cabs define mainctrlact: with a linear scale nobody has seen working; it is not opted in
for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) {
CAPTURE(path);
consist train;
auto &locomotive{train.add(definition::fiz(path), 1).mover()};
REQUIRE(locomotive.EIMCtrlType == 0);
locomotive.MainCtrlPos = 5;
locomotive.ScndCtrlPos = 1;
for (auto const coupled : {false, true}) {
CAPTURE(coupled);
locomotive.CoupledCtrl = coupled;
CHECK(main_ctrl_act::position(locomotive, false) == doctest::Approx(0.0));
}
}
}
TEST_CASE("main ctrl act: the marker of an electric locomotive shows its actual position, as before") {
for (auto const scaletable : {false, true}) {
CAPTURE(scaletable);
consist train;
auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).mover()};
locomotive.MainCtrlPos = 10;
locomotive.MainCtrlActualPos = 3;
locomotive.ScndCtrlPos = 2;
locomotive.ScndCtrlActualPos = 1;
locomotive.CoupledCtrl = false;
CHECK(main_ctrl_act::position(locomotive, scaletable) == doctest::Approx(3.0));
locomotive.CoupledCtrl = true;
CHECK(main_ctrl_act::position(locomotive, scaletable) == doctest::Approx(4.0));
}
}

View File

@@ -0,0 +1,30 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle/holdcoillever.h"
// the lever of the line breaker's hold coil on the ET22 and the EP09 stays where it's put (eu07/maszyna#364), when the
// cab declares its main_off_bt control with "type: toggle"; otherwise main_off_bt is the push button it always was
TEST_CASE("hold coil lever: only a main_off_bt declared as a toggle switch is the bistable lever (eu07/maszyna#364)") {
CHECK(hold_coil_lever::is_bistable(true, true));
// declared as a push button
CHECK_FALSE(hold_coil_lever::is_bistable(true, false));
// no type given: a control defaults to the toggle type, which existing cabs relied on for the push button
CHECK_FALSE(hold_coil_lever::is_bistable(false, true));
}
TEST_CASE("hold coil lever: operated, it goes over to the other position and stays there") {
// on: the hold coil fed, the line breaker can close
CHECK_FALSE(hold_coil_lever::cuts_off(0.f));
auto const off{hold_coil_lever::operated(0.f)};
CHECK(off == doctest::Approx(1.f));
CHECK(hold_coil_lever::cuts_off(off));
// operated again it goes back on
auto const on{hold_coil_lever::operated(off)};
CHECK(on == doctest::Approx(0.f));
CHECK_FALSE(hold_coil_lever::cuts_off(on));
// caught on the way between the positions it goes to the far one
CHECK(hold_coil_lever::operated(0.3f) == doctest::Approx(1.f));
CHECK(hold_coil_lever::operated(0.7f) == doctest::Approx(0.f));
}

View File

@@ -0,0 +1,96 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
// the cab interior light set by the positions of the light preset selector: an optional third column of LightsList,
// 1 the cab light on, 2 dimmed, 0 off; a row without it leaves the cab light to its own switch (eu07/maszyna#529)
using test::definition;
using test::vehicle;
namespace {
auto const shunting{light::headlight_left | light::headlight_right};
} // namespace
TEST_CASE("lights preset cab light: a table without the column sets no position's cab light") {
vehicle wagon{definition::load("wagon")
.set("LightsList", "Size", 2)
.set("LightsList", "Default", 1)
.set("LightsList", "rows", {{0, 0}, {shunting, shunting}})};
REQUIRE(wagon->LightsPosNo == 2);
CHECK(wagon->Lights[end::front][1] == shunting);
CHECK_FALSE(wagon->LightsPresetCabLight(1).has_value());
CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value());
}
TEST_CASE("lights preset cab light: the third column turns the cab light off, on, or on dimmed") {
// off - shunting - shunting with the cab lit - shunting with the cab lit dimmed - shunting leaving the cab light
vehicle wagon{definition::load("wagon")
.set("LightsList", "Size", 5)
.set("LightsList", "Default", 1)
.set("LightsList", "rows", {{0, 0, 0}, {shunting, shunting}, {shunting, shunting, 1}, {shunting, shunting, 3}, {shunting, 0, -1}})};
REQUIRE(wagon->LightsPosNo == 5);
// the light columns read as before
CHECK(wagon->Lights[end::front][2] == shunting);
CHECK(wagon->Lights[end::rear][2] == shunting);
CHECK(wagon->Lights[end::rear][4] == 0);
auto const off{wagon->LightsPresetCabLight(1)};
REQUIRE(off.has_value());
CHECK_FALSE(off->light);
CHECK_FALSE(off->dim);
CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value());
auto const lit{wagon->LightsPresetCabLight(3)};
REQUIRE(lit.has_value());
CHECK(lit->light);
CHECK_FALSE(lit->dim);
auto const dimmed{wagon->LightsPresetCabLight(4)};
REQUIRE(dimmed.has_value());
CHECK(dimmed->light);
CHECK(dimmed->dim);
// a negative value is the same as no value
CHECK_FALSE(wagon->LightsPresetCabLight(5).has_value());
}
TEST_CASE("lights preset cab light: positions outside the table, and the lightsset custom one, set nothing") {
vehicle wagon{definition::load("wagon")
.set("LightsList", "Size", 1)
.set("LightsList", "Default", 1)
.set("LightsList", "rows", {{shunting, shunting, 1}})};
CHECK(wagon->LightsPresetCabLight(1).has_value());
CHECK_FALSE(wagon->LightsPresetCabLight(0).has_value());
CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value());
CHECK_FALSE(wagon->LightsPresetCabLight(18).has_value());
CHECK_FALSE(wagon->LightsPresetCabLight(19).has_value());
}
TEST_CASE("lights preset cab light: a stray note after the two columns is not read as the cab light") {
// some vehicles of the game carry rows like "38 38 / A"
auto text{definition::load("wagon")
.set("LightsList", "Size", 2)
.set("LightsList", "Default", 1)
.set("LightsList", "rows", {{0, 0}, {38, 38}})
.text()};
auto const list{text.find("LightsList")};
REQUIRE(list != std::string::npos);
auto const row{text.find("38", list)};
REQUIRE(row != std::string::npos);
auto const rowend{text.find('\n', row)};
REQUIRE(rowend != std::string::npos);
text.insert(rowend, " / A");
TMoverParameters wagon(0.0, "wagon", "test", 0);
REQUIRE(wagon.LoadFIZ_Text(text));
REQUIRE(wagon.LightsPosNo == 2);
CHECK(wagon.Lights[end::front][1] == 38);
CHECK(wagon.Lights[end::rear][1] == 38);
CHECK_FALSE(wagon.LightsPresetCabLight(2).has_value());
}

View File

@@ -0,0 +1,93 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle/lightsprogrammer.h"
// the lights the light preset selector (programmer) of the occupied cab gives the vehicles of the consist,
// TDynamicObject::SetLights(): the cab's front lights at the end the cab faces, its back lights at the other
// end, and no lights at an end with another vehicle coupled
namespace {
int const pc1{light::headlight_left | light::headlight_upper | light::headlight_right};
int const tailmarkers{light::redmarker_left | light::redmarker_right};
std::array<int, 2> const cablights{pc1, tailmarkers}; // Lights[end::front], Lights[end::rear]
// the lights at the vehicle's own end, placed the way TDynamicObject::RaLightsSet() places them
int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, end const Side) {
auto const headend{Direction > 0 ? end::front : end::rear};
return Side == headend ? Lights.head : Lights.rear;
}
struct setup {
int cab; // CabOccupied of the vehicle with the programmer
int direction; // its iDirection
std::array<bool, 2> coupled; // vehicle coupled at its end::front / end::rear
};
lights_programmer::consist_lights lights_for(setup const &Setup) {
// TDynamicObject::SetLights(): the cab faces the head of the consist when CabOccupied * DirectionGet() >= 0
auto const cabfacinghead{Setup.cab * (Setup.direction > 0 ? 1 : -1) >= 0};
return lights_programmer::vehicle_lights(cablights, cabfacinghead, Setup.direction, Setup.coupled);
}
} // namespace
TEST_CASE("lights programmer: a lone vehicle gets the cab's front lights ahead of the cab and its back lights behind it") {
for (auto const direction : {0, 1}) {
CAPTURE(direction);
// cab 1 faces end::front
auto const fromcab1{lights_for({1, direction, {false, false}})};
CHECK(lights_at(fromcab1, direction, end::front) == pc1);
CHECK(lights_at(fromcab1, direction, end::rear) == tailmarkers);
// cab -1 faces end::rear
auto const fromcab2{lights_for({-1, direction, {false, false}})};
CHECK(lights_at(fromcab2, direction, end::rear) == pc1);
CHECK(lights_at(fromcab2, direction, end::front) == tailmarkers);
}
}
TEST_CASE("lights programmer: the end with the train coupled goes dark, not the other one (eu07/maszyna#395)") {
// a locomotive driven from either cab, with the train coupled at either end, either way round in the consist.
// the end with the train goes dark, the free end shows the lights meant for it
for (auto const direction : {0, 1}) {
for (auto const cab : {1, -1}) {
for (auto const trainend : {end::front, end::rear}) {
CAPTURE(direction);
CAPTURE(cab);
CAPTURE(trainend);
std::array<bool, 2> coupled{false, false};
coupled[trainend] = true;
auto const freeend{trainend == end::front ? end::rear : end::front};
auto const cabfront{cab > 0 ? end::front : end::rear};
auto const lights{lights_for({cab, direction, coupled})};
CHECK(lights_at(lights, direction, trainend) == 0);
CHECK(lights_at(lights, direction, freeend) == (freeend == cabfront ? pc1 : tailmarkers));
}
}
}
}
TEST_CASE("lights programmer: 6Dg driven backwards from its second cab position pulls the train with its head lights lit (eu07/maszyna#395)") {
// the reported case: the train coupled behind the driver (end::front, which cab -1 has at its back), the
// locomotive running towards end::rear, the train in tow. the head lights stay lit, the end with the train goes dark;
// before the fix the couplings were looked up at the swapped ends and it was the other way round
auto const lights{lights_for({-1, 1, {true, false}})};
CHECK(lights_at(lights, 1, end::rear) == pc1);
CHECK(lights_at(lights, 1, end::front) == 0);
}
TEST_CASE("lights programmer: a vehicle coupled at both ends stays dark") {
for (auto const direction : {0, 1}) {
for (auto const cab : {1, -1}) {
CAPTURE(direction);
CAPTURE(cab);
auto const lights{lights_for({cab, direction, {true, true}})};
CHECK(lights.head == 0);
CHECK(lights.rear == 0);
}
}
}

View File

@@ -0,0 +1,114 @@
#include "stdafx.h"
#include "doctest.h"
#include "consist.h"
#include "drive.h"
#include "vehicle/linebreaker.h"
// the line breaker (WS) controls of the cab (eu07/maszyna#394)
using test::consist;
using test::definition;
namespace {
// the line breaker lever of the EP05 (main_sw), a single two-state lever, the way TTrain works it: the state
// the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close
struct lever {
TMoverParameters &mover;
int breaker{0}; // as TTrain::m_linebreakerstate: 0 open, 1 closed
bool on{false};
void press() {
switch (linebreaker::pressed(breaker, true, on)) {
case linebreaker::toggle::close:
on = true;
break;
case linebreaker::toggle::open:
on = false;
if (breaker == 1 && mover.MainSwitch(false)) {
breaker = 0;
}
break;
default:
break;
}
}
// TTrain::Update()
void update() {
if (breaker == 0 && mover.Mains) {
breaker = 1;
}
if (breaker == 1 && false == mover.Mains) {
breaker = 0;
}
if (on && breaker == 0 && mover.MainSwitchCheck()) {
breaker = mover.MainSwitch(true) ? 1 : 0;
}
}
};
} // namespace
TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens a closed one") {
using enum linebreaker::toggle;
for (auto const latching : {false, true}) {
CHECK(linebreaker::pressed(0, latching, false) == close);
CHECK(linebreaker::pressed(1, latching, true) == open);
CHECK(linebreaker::pressed(1, latching, false) == open);
// freshly closed, the cab finishes closing it first
CHECK(linebreaker::pressed(2, latching, true) == none);
}
// a lever left on over an open breaker goes off; push buttons have no position to keep
CHECK(linebreaker::pressed(0, true, true) == open);
CHECK(linebreaker::pressed(0, false, true) == close);
}
TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") {
consist train;
auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).mover()};
test::track const line{0.15, 0.0, test::catenary_3kv};
auto const driver{test::driving(train)};
REQUIRE(test::start_up(driver, line));
REQUIRE(ep05.Mains);
REQUIRE(ep05.ConverterFlag);
lever ws{ep05, 1, true};
// the converter overload relay knocks the line breaker out, as the cab does it when the converter is
// switched on together with the compressor; the lever stays on
ep05.ConvOvldFlag = true;
ep05.MainSwitch(false, range_t::local);
ws.update();
REQUIRE_FALSE(ep05.Mains);
REQUIRE(ws.breaker == 0);
CHECK(ws.on);
// with the relay tripped the breaker doesn't close
test::drive(driver, line, 5.0);
CHECK_FALSE(ep05.MainSwitchCheck());
// nothing holds the lever: it goes off, and on again, though the breaker stays open
ws.press();
CHECK_FALSE(ws.on);
ws.press();
CHECK(ws.on);
ws.update();
CHECK_FALSE(ep05.Mains);
ws.press();
CHECK_FALSE(ws.on);
// the relay reset, with the converter switched off, the lever put on closes the breaker again
ep05.ConverterSwitch(false, range_t::local);
test::drive(driver, line, 1.0);
CHECK(ep05.RelayReset(relay_t::primaryconverteroverload, range_t::local));
CHECK_FALSE(ep05.ConvOvldFlag);
ws.update();
CHECK_FALSE(ep05.Mains); // the lever is off
ws.press();
ws.update();
CHECK(ep05.Mains);
CHECK(ws.breaker == 1);
// and the next press opens it
ws.press();
CHECK_FALSE(ws.on);
CHECK_FALSE(ep05.Mains);
}

View File

@@ -0,0 +1,55 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
using test::definition;
using test::vehicle;
// the oil pump lamp of the cab (i-oilpump) shows OilPump.is_active: the pre-lubrication pump of 401Da, which works
// before the engine start and stops once the engine runs and makes the oil pressure itself (eu07/maszyna#546)
// NOTE: the test vehicle has no diesel engine, so the pump check is called the way dizel_Update() calls it
TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and stops once the engine runs") {
vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Manual")};
REQUIRE(loco->OilPump.start_type == start_t::manual);
loco->Power24vIsAvailable = true; // battery on
loco->OilPumpCheck(0.01);
CHECK_FALSE(loco->OilPump.is_active); // not switched on yet
loco->OilPump.is_enabled = true; // pump switch on: pre-lubrication
loco->OilPumpCheck(0.01);
CHECK(loco->OilPump.is_active);
loco->Mains = true; // engine started
loco->OilPumpCheck(0.01);
CHECK_FALSE(loco->OilPump.is_active);
}
TEST_CASE("oil pump: the pump started with the engine start procedure stops once the engine runs") {
vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Automatic")};
REQUIRE(loco->OilPump.start_type == start_t::automatic);
loco->Power24vIsAvailable = true;
loco->dizel_startup = true; // starter button pressed
loco->OilPumpCheck(0.01);
CHECK(loco->OilPump.is_active);
loco->dizel_startup = false; // start procedure done, the pump keeps working until the engine runs
loco->OilPumpCheck(0.01);
CHECK(loco->OilPump.is_active);
loco->Mains = true;
loco->OilPumpCheck(0.01);
CHECK_FALSE(loco->OilPump.is_active);
}
TEST_CASE("oil pump: without power the pump and its lamp stay off") {
vehicle loco{definition::load("cab_vehicle")};
loco->Power24vIsAvailable = false;
loco->Power110vIsAvailable = false;
loco->OilPump.is_enabled = true;
loco->OilPumpCheck(0.01);
CHECK_FALSE(loco->OilPump.is_active);
}

View File

@@ -26,3 +26,33 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") {
}
CHECK_FALSE(vehicle->RadioPowered());
}
// the cut-off in the radio's power supply (eu07/maszyna#438): a fuse, a desk lever or the switch on the radio's
// power supply, closed unless the driver opens it
TEST_CASE("radio: the radio fuse is closed by default") {
test::vehicle vehicle{test::definition::load("wagon")};
CHECK(vehicle->RadioFuse);
}
TEST_CASE("radio: an opened radio fuse cuts the radio off") {
test::vehicle vehicle{test::definition::load("wagon")};
vehicle->Radio = true;
vehicle->Power24vIsAvailable = true;
vehicle->RadioFuse = false;
CHECK_FALSE(vehicle->RadioPowered());
vehicle->RadioFuse = true;
CHECK(vehicle->RadioPowered());
}
TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") {
test::vehicle loco{test::definition::fiz("4e_v1/4e")};
loco->Battery = true;
loco->Radio = true;
REQUIRE(loco->RadiostopSwitch(true));
loco->SecuritySystemCheck(0.1);
CHECK(loco->RadioStopFlag);
loco->RadioFuse = false;
loco->SecuritySystemCheck(0.1);
CHECK_FALSE(loco->RadioStopFlag);
}

View File

@@ -0,0 +1,120 @@
#include "stdafx.h"
#include "doctest.h"
#include "scripting/scriptscreendrawing.h"
#include <algorithm>
#include <array>
#include <vector>
// the drawing the Lua screens get from the game: fonts read as scripts/led_util.py reads them, text and images
using script_screens::bitmap_font;
using script_screens::canvas;
using script_screens::rgb;
namespace {
// an RGBA image Width x Height, white, with the listed pixels set to the colour
std::vector<std::uint8_t> image(int const Width, int const Height, std::vector<std::pair<int, int>> const &Pixels,
std::array<std::uint8_t, 4> const Color = {0, 0, 0, 255}) {
std::vector<std::uint8_t> pixels(static_cast<std::size_t>(Width) * Height * 4, 255);
for (auto const &[x, y] : Pixels) {
std::copy(Color.begin(), Color.end(), pixels.begin() + (static_cast<std::ptrdiff_t>(y) * Width + x) * 4);
}
return pixels;
}
} // namespace
TEST_CASE("script screen drawing: UTF-8 text becomes code points, a stray byte stands for itself") {
CHECK(script_screens::decode_utf8("ab") == U"ab");
CHECK(script_screens::decode_utf8("\xc5\x81\xc3\xb3\xc5\xbc") == U"Łóż"); // Łóż
CHECK(script_screens::decode_utf8("a\xb3z") == U"a³z");
CHECK(script_screens::decode_utf8("\xe2\x82") == U"â\u0082");
}
TEST_CASE("script screen drawing: a font as led_util reads it, glyphs a column apart") {
// "a" 2 wide (x 0-1), "Ł" 1 wide (x 3), " " 1 wide (x 5)
auto const pixels{image(6, 2, {{0, 0}, {1, 1}, {3, 0}, {3, 1}})};
auto const font{bitmap_font::parse(pixels, 6, 2, "// comment\r\na2\r\n\xc5\x81" "1\r\n 1\r\n")};
REQUIRE(font.has_value());
CHECK(font->height() == 2);
auto const &a{font->find(U'a')};
REQUIRE(a.width() == 2);
CHECK(a.lit(0, 0));
CHECK_FALSE(a.lit(0, 1));
CHECK(a.lit(1, 1));
auto const &l{font->find(U'Ł')};
REQUIRE(l.width() == 1);
CHECK(l.lit(0, 0));
CHECK(l.lit(0, 1));
auto const &space{font->find(U' ')};
REQUIRE(space.width() == 1);
CHECK_FALSE(space.lit(0, 0));
// a character the font lacks: its first glyph
CHECK(font->find(U'q').width() == 2);
// led_util's get_str_len: a spacing column after every character
CHECK(font->text_width("a\xc5\x81", 1) == 5);
CHECK(font->text_width("", 1) == 0);
}
TEST_CASE("script screen drawing: a pixel is lit unless it is opaque white") {
auto pixels{image(3, 1, {{0, 0}})};
// transparent white: lit, as led_util compares the whole pixel with (255, 255, 255, 255)
pixels[1 * 4 + 3] = 0;
auto const sprite{bitmap_font::sprite(pixels, 3, 1)};
REQUIRE(sprite.width() == 3);
CHECK(sprite.lit(0, 0));
CHECK(sprite.lit(1, 0));
CHECK_FALSE(sprite.lit(2, 0));
}
TEST_CASE("script screen drawing: a description without glyphs, or one wider than its image, does no harm") {
auto const pixels{image(2, 1, {})};
CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "// only a comment\n").has_value());
CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "").has_value());
// the glyph runs past the image: the columns past its edge are unlit
auto const font{bitmap_font::parse(pixels, 2, 1, "//\nw5\n")};
REQUIRE(font.has_value());
CHECK(font->find(U'w').width() == 5);
CHECK_FALSE(font->find(U'w').lit(4, 0));
}
TEST_CASE("script screen drawing: text is drawn from x rightwards and returns where it ends") {
auto const pixels{image(4, 1, {{0, 0}, {1, 0}, {3, 0}})};
auto const font{bitmap_font::parse(pixels, 4, 1, "//\na2\nb1\n")};
REQUIRE(font.has_value());
canvas board{8, 1, rgb{0, 0, 0}};
auto const end{board.draw_text(*font, 1, 0, "ab", rgb{9, 8, 7}, 1)};
CHECK(end == 6);
CHECK(board.get(0, 0) == rgb{0, 0, 0});
CHECK(board.get(1, 0) == rgb{9, 8, 7});
CHECK(board.get(2, 0) == rgb{9, 8, 7});
CHECK(board.get(3, 0) == rgb{0, 0, 0});
CHECK(board.get(4, 0) == rgb{9, 8, 7});
// partly off the image: clipped
canvas narrow{2, 1, rgb{0, 0, 0}};
narrow.draw_text(*font, -1, 0, "ab", rgb{1, 1, 1}, 1);
CHECK(narrow.get(0, 0) == rgb{1, 1, 1});
}
TEST_CASE("script screen drawing: rectangles and images are clipped to the image") {
canvas board{3, 2, rgb{0, 0, 0}};
board.fill_rect(-5, 1, 100, 100, rgb{1, 2, 3});
CHECK(board.get(0, 0) == rgb{0, 0, 0});
CHECK(board.get(0, 1) == rgb{1, 2, 3});
CHECK(board.get(2, 1) == rgb{1, 2, 3});
CHECK(board.get(5, 5) == rgb{0, 0, 0});
canvas const stamp{2, 2, rgb{7, 7, 7}};
board.draw_image(stamp, 2, -1);
CHECK(board.get(2, 0) == rgb{7, 7, 7});
CHECK(board.get(1, 0) == rgb{0, 0, 0});
// every pixel opaque
CHECK(board.pixels()[3] == 255);
}

View File

@@ -0,0 +1,749 @@
#include "stdafx.h"
#include "doctest.h"
// the script screen host (scripting/scriptscreens.cpp) with the real runtimes: a script reads its input, draws an
// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped;
// a Lua script can't reach files, the system or precompiled code. the Lua cases need WITH_LUA, the WebAssembly ones
// WITH_WASM
#include "scripting/scriptscreens.h"
#include "input/command.h"
#include "interfaces/ITexture.h"
#include "utilities/Globals.h"
#include "utilities/dictionary.h"
#include <array>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <functional>
#include <span>
#include <string_view>
#include <thread>
#include <vector>
// the engine's command queue and command names, which the test build doesn't link: the commands the screens send
// are kept here instead
namespace {
std::vector<std::pair<command_data, std::uint32_t>> &sent_commands() {
static std::vector<std::pair<command_data, std::uint32_t>> commands;
return commands;
}
} // namespace
namespace simulation {
command_queue Commands; // NOSONAR the engine's extern global, input/command.h
std::unordered_map<std::string, user_command> const commandMap{{"cmdtest", user_command::aidriverenable}}; // NOSONAR the engine's extern global, input/command.h
} // namespace simulation
void command_queue::push(command_data const &Command, uint32_t const Recipient) { // NOSONAR signature from input/command.h
sent_commands().emplace_back(Command, Recipient);
}
namespace {
// a texture that keeps what was uploaded to it
struct recording_texture : ITexture {
bool create(bool) override { return true; }
int get_width() const override { return width; }
int get_height() const override { return height; }
size_t get_id() const override { return id; }
void release() override { /* nothing held */ }
void make_stub() override { /* nothing held */ }
std::string_view get_traits() const override { return ""; }
std::string_view get_name() const override { return "recording"; }
std::string_view get_type() const override { return "make:"; }
bool is_stub() const override { return false; }
bool get_has_alpha() const override { return true; }
bool get_is_ready() const override { return ready; }
void set_components_hint(int) override { /* not used */ }
void make_from_memory(size_t const Width, size_t const Height, const uint8_t *Data) override { update_from_memory(Width, Height, Data); }
void update_from_memory(size_t const Width, size_t const Height, const uint8_t *Data) override {
width = static_cast<int>(Width);
height = static_cast<int>(Height);
pixels.assign(Data, Data + Width * Height * 4);
++uploads;
}
bool ready{true};
size_t id{1};
int width{0};
int height{0};
int uploads{0};
std::vector<std::uint8_t> pixels;
};
// a folder of its own for the scripts of a test, removed with the object
class script_folder {
public:
explicit script_folder(std::string const &Name)
: m_folder{std::filesystem::temp_directory_path() / std::format("eu07_script_screen_test_{}", Name)} {
std::filesystem::remove_all(m_folder);
std::filesystem::create_directories(m_folder);
}
~script_folder() {
std::error_code error;
std::filesystem::remove_all(m_folder, error);
}
script_folder(script_folder const &) = delete;
script_folder &operator=(script_folder const &) = delete;
// writes the file, returns its path as the game names scripts
std::string write(std::string const &Name, std::span<std::uint8_t const> const Bytes) const {
auto const path{m_folder / Name};
std::filesystem::create_directories(path.parent_path());
std::ofstream file{path, std::ios::binary};
file.write(reinterpret_cast<char const *>(Bytes.data()), static_cast<std::streamsize>(Bytes.size()));
return path.generic_string();
}
std::string write(std::string const &Name, std::string_view const Text) const {
return write(Name, std::span{reinterpret_cast<std::uint8_t const *>(Text.data()), Text.size()});
}
private:
std::filesystem::path m_folder;
};
// runs frames until the condition holds, or gives up after a few seconds
bool run_until(script_screen_queue &Queue, std::function<bool()> const &Condition) {
auto const deadline{std::chrono::steady_clock::now() + std::chrono::seconds(20)};
while (std::chrono::steady_clock::now() < deadline) {
Queue.update();
if (Condition()) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
return false;
}
std::shared_ptr<dictionary_source> speed(double const Value) {
auto input{std::make_shared<dictionary_source>()};
input->insert("speed", Value);
return input;
}
script_screen_queue::screen_request request(script_language const Language, std::string const &Script, std::string const &Key, ITexture *Texture,
script_screen_kind const Kind = script_screen_kind::cab) {
return {.kind = Kind, .language = Language, .script = Script, .key = Key, .texture = Texture, .frames = 0};
}
// submits a refresh as soon as the screen is due
void refresh(script_screen_queue &Queue, std::shared_ptr<script_screen> const &Screen, std::shared_ptr<dictionary_source> Input, std::uint32_t const Vehicle) {
REQUIRE(run_until(Queue, [&Queue, &Screen] { return Queue.due(*Screen); }));
Queue.submit(Screen, std::move(Input), Vehicle);
}
} // namespace
TEST_CASE("script screens: a language that doesn't run gets no screens") {
script_screen_queue queue;
// not started
CHECK_FALSE(queue.runs(script_language::lua));
CHECK(queue.acquire(request(script_language::lua, "x.lua", "x", nullptr)) == nullptr);
}
TEST_CASE("script screens: the language of a script is told by its extension") {
CHECK(script_language_of("scripts/led_111a20.lua") == script_language::lua);
CHECK(script_language_of("dynamic/pkp/x/ekran.wasm") == script_language::wasm);
CHECK_FALSE(script_language_of("scripts/led_111a20").has_value());
}
#ifdef WITH_WASM
namespace {
// the modules, encoded by hand. "paint": a 2x2 screen in the colour 0xFF0000vv, vv being the input value
// "speed", which sends the command "cmdtest" with the parameters (vv, 7):
// (import "eu07" "get_float" (func $get_float (param i32 i32) (result f64)))
// (import "eu07" "command" (func $command (param i32 i32 i32 i32)))
// (memory (export "memory") 1)
// (data (i32.const 0) "speed") (data (i32.const 16) "cmdtest")
// (func (export "screen_width") (result i32) i32.const 2)
// (func (export "screen_height") (result i32) i32.const 2)
// (func (export "screen_render") (result i32) (local $v i32)
// (local.set $v (i32.trunc_f64_s (call $get_float (i32.const 0) (i32.const 5))))
// (i32.store (i32.const 1024) (i32.or (local.get $v) (i32.const 0xFF000000))) ... the same at 1028, 1032, 1036
// (call $command (i32.const 16) (i32.const 7) (local.get $v) (i32.const 7))
// (i32.const 1024))
constexpr std::array<std::uint8_t, 254> paint_module{
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x12, 0x03, 0x60, 0x02, 0x7f, 0x7f, 0x01,
0x7c, 0x60, 0x04, 0x7f, 0x7f, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x21, 0x02, 0x04,
0x65, 0x75, 0x30, 0x37, 0x09, 0x67, 0x65, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x00, 0x00,
0x04, 0x65, 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x01, 0x03,
0x04, 0x03, 0x02, 0x02, 0x02, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65,
0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69,
0x64, 0x74, 0x68, 0x00, 0x02, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69,
0x67, 0x68, 0x74, 0x00, 0x03, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e,
0x64, 0x65, 0x72, 0x00, 0x04, 0x0a, 0x5e, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41,
0x02, 0x0b, 0x52, 0x01, 0x01, 0x7f, 0x41, 0x00, 0x41, 0x05, 0x10, 0x00, 0xaa, 0x21, 0x00, 0x41,
0x80, 0x08, 0x20, 0x00, 0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x84, 0x08,
0x20, 0x00, 0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x88, 0x08, 0x20, 0x00,
0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x8c, 0x08, 0x20, 0x00, 0x41, 0x80,
0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x10, 0x41, 0x07, 0x20, 0x00, 0x41, 0x07, 0x10,
0x01, 0x41, 0x80, 0x08, 0x0b, 0x0b, 0x17, 0x02, 0x00, 0x41, 0x00, 0x0b, 0x05, 0x73, 0x70, 0x65,
0x65, 0x64, 0x00, 0x41, 0x10, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, 0x74};
// "spin": exports the same functions as "paint", but screen_render never returns: (loop $l (br $l))
constexpr std::array<std::uint8_t, 108> spin_module{
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f, 0x03,
0x04, 0x03, 0x00, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65,
0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69,
0x64, 0x74, 0x68, 0x00, 0x00, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69,
0x67, 0x68, 0x74, 0x00, 0x01, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e,
0x64, 0x65, 0x72, 0x00, 0x02, 0x0a, 0x15, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41,
0x02, 0x0b, 0x09, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x41, 0x00, 0x0b};
} // namespace
TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") {
sent_commands().clear();
script_folder const folder{"wasm_paint"};
auto const module{folder.write("paint.wasm", paint_module)};
script_screen_queue queue;
REQUIRE(queue.init());
REQUIRE(queue.runs(script_language::wasm));
recording_texture texture;
auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))};
REQUIRE(screen != nullptr);
// the same key, the same screen
CHECK(queue.acquire(request(script_language::wasm, module, "cab", &texture)) == screen);
refresh(queue, screen, speed(5.0), 42);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); }));
CHECK(texture.width == 2);
CHECK(texture.height == 2);
REQUIRE(texture.pixels.size() == 16);
std::array<std::uint8_t, 4> const expected{0x05, 0x00, 0x00, 0xFF};
for (std::size_t pixel = 0; pixel < 4; ++pixel) {
CAPTURE(pixel);
CHECK(std::equal(expected.begin(), expected.end(), texture.pixels.begin() + static_cast<std::ptrdiff_t>(pixel * 4)));
}
REQUIRE(sent_commands().size() == 1);
auto const &[command, recipient]{sent_commands().front()};
CHECK(command.command == user_command::aidriverenable);
CHECK(command.param1 == 5.0);
CHECK(command.param2 == 7.0);
CHECK(recipient == (static_cast<std::uint32_t>(command_target::vehicle) | 42u));
queue.exit();
}
TEST_CASE("wasm screens: the image goes up again when the texture is made anew, and waits while it isn't there") {
sent_commands().clear();
script_folder const folder{"wasm_reupload"};
auto const module{folder.write("paint.wasm", paint_module)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
texture.ready = false;
auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))};
refresh(queue, screen, speed(9.0), 1);
REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); }));
queue.update();
CHECK(texture.uploads == 0);
texture.ready = true;
queue.update();
CHECK(texture.uploads == 1);
queue.update();
CHECK(texture.uploads == 1);
// released and made again: a new gl texture
texture.id = 2;
queue.update();
CHECK(texture.uploads == 2);
queue.exit();
}
TEST_CASE("wasm screens: a screen outside the cab draws, but its commands are dropped") {
sent_commands().clear();
script_folder const folder{"wasm_sign"};
auto const module{folder.write("paint.wasm", paint_module)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::wasm, module, "sign", &texture, script_screen_kind::external))};
refresh(queue, screen, speed(3.0), 0);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
queue.update();
CHECK(sent_commands().empty());
queue.exit();
}
TEST_CASE("wasm screens: a screen stuck in a loop is stopped, and the others keep working") {
script_folder const folder{"wasm_spin"};
auto const spinning{folder.write("spin.wasm", spin_module)};
auto const painting{folder.write("paint.wasm", paint_module)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture stuck;
recording_texture working;
auto const first{queue.acquire(request(script_language::wasm, spinning, "spin", &stuck))};
auto const second{queue.acquire(request(script_language::wasm, painting, "paint", &working))};
refresh(queue, first, speed(1.0), 1);
refresh(queue, second, speed(2.0), 1);
REQUIRE(run_until(queue, [&working] { return working.uploads > 0; }));
CHECK(stuck.uploads == 0);
// the stuck screen ran first, into the instruction limit, and isn't due any more
CHECK_FALSE(queue.due(*first));
queue.exit();
}
TEST_CASE("wasm screens: the screens outlive the queue without harm") {
script_folder const folder{"wasm_outlive"};
auto const module{folder.write("paint.wasm", paint_module)};
std::shared_ptr<script_screen> screen;
recording_texture texture;
{
script_screen_queue queue;
REQUIRE(queue.init());
screen = queue.acquire(request(script_language::wasm, module, "cab", &texture));
refresh(queue, screen, speed(4.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
}
// the queue and the runtime are gone, the vehicle still holds its screen
CHECK(screen != nullptr);
screen.reset();
}
#endif
#ifdef WITH_LUA
#include "stb/stb_image.h"
#include "stb/stb_image_write.h"
namespace {
// the game's texture loader turns every image stb_image reads bottom row first (model/Texture.cpp); for the length of
// a test, the same here
class images_flipped_as_in_the_game {
public:
images_flipped_as_in_the_game() { stbi_set_flip_vertically_on_load(1); }
~images_flipped_as_in_the_game() { stbi_set_flip_vertically_on_load(0); }
images_flipped_as_in_the_game(images_flipped_as_in_the_game const &) = delete;
images_flipped_as_in_the_game &operator=(images_flipped_as_in_the_game const &) = delete;
};
// a 2x2 screen in the colour (speed, 0, 0), sending the command "cmdtest" with (speed, 7)
constexpr std::string_view paint_script{R"(
local screen = {}
function screen.render(state)
eu07.command("cmdtest", state.speed, 7)
return eu07.image(2, 2, { state.speed, 0, 0 })
end
return screen
)"};
// 1x2: a red row above a green one
constexpr std::string_view rows_script{R"(
return {
render = function(state)
local image = eu07.image(1, 2, { 0, 0, 0 })
image:set(0, 0, { 255, 0, 0 })
image:set(0, 1, { 0, 255, 0 })
return image
end
}
)"};
// 1x1, white when nothing of the world outside the sandbox is reachable, black otherwise
constexpr std::string_view sandbox_script{R"(
local reachable = io or os or ffi or debug or package or require or load or loadstring or dofile or loadfile or string.dump or jit
local escapes = eu07.read_file("../outside.txt") or eu07.read_file("/etc/hosts") or eu07.read_file("c:/windows/win.ini")
local inside = eu07.read_file("data/inside.txt")
local ok = not reachable and not escapes and inside == "inside"
return {
render = function(state)
return eu07.image(1, 1, ok and { 255, 255, 255 } or { 0, 0, 0 })
end
}
)"};
// never returns from render
constexpr std::string_view spin_script{R"(
return { render = function(state) while true do end end }
)"};
// draws once, then reports nothing new
constexpr std::string_view once_script{R"(
local drawn = false
return {
render = function(state)
if drawn then return nil end
drawn = true
return eu07.image(1, 1, { 1, 2, 3 })
end
}
)"};
// uses a helper script and a font next to it
constexpr std::string_view include_script{R"(
local helper = eu07.include("helper.lua")
local font = eu07.font("font/test")
return {
render = function(state)
local image = eu07.image(8, 2, { 0, 0, 0 })
local x = image:draw_text(font, 0, 0, helper.text, { 255, 0, 0 })
image:set(7, 1, { x, font:text_width("ab"), font:height() })
return image
end
}
)"};
constexpr std::string_view helper_script{R"(
return { text = "ab" }
)"};
// a font of two glyphs a column apart: "a" two columns wide, lit in its top row, "b" one column, lit in both rows.
// written as a .png by stb_image_write, the way the game's fonts are
std::vector<std::uint8_t> test_font_png() {
constexpr int width{4};
constexpr int height{2};
std::array<std::uint8_t, width * height * 4> pixels{};
pixels.fill(255);
auto const lit{[&pixels](int const X, int const Y) { pixels[(Y * width + X) * 4] = 0; }};
lit(0, 0);
lit(1, 0);
lit(3, 0);
lit(3, 1);
std::vector<std::uint8_t> result;
auto const append{[](void *Target, void *Data, int const Size) {
auto *bytes{static_cast<std::uint8_t const *>(Data)};
static_cast<std::vector<std::uint8_t> *>(Target)->insert(static_cast<std::vector<std::uint8_t> *>(Target)->end(), bytes, bytes + Size);
}};
stbi_write_png_to_func(append, &result, width, height, 4, pixels.data(), width * 4);
return result;
}
} // namespace
TEST_CASE("lua screens: a cab screen draws from its input and sends commands to its vehicle") {
sent_commands().clear();
script_folder const folder{"lua_paint"};
auto const script{folder.write("paint.lua", paint_script)};
script_screen_queue queue;
REQUIRE(queue.init());
REQUIRE(queue.runs(script_language::lua));
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "cab", &texture))};
REQUIRE(screen != nullptr);
refresh(queue, screen, speed(5.0), 42);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); }));
CHECK(texture.width == 2);
CHECK(texture.height == 2);
REQUIRE(texture.pixels.size() == 16);
CHECK(texture.pixels[0] == 5);
CHECK(texture.pixels[1] == 0);
CHECK(texture.pixels[3] == 255);
REQUIRE(sent_commands().size() == 1);
auto const &[command, recipient]{sent_commands().front()};
CHECK(command.command == user_command::aidriverenable);
CHECK(command.param1 == 5.0);
CHECK(command.param2 == 7.0);
CHECK(recipient == (static_cast<std::uint32_t>(command_target::vehicle) | 42u));
queue.exit();
}
TEST_CASE("lua screens: the texture gets the bottom row first, as from the python screens") {
script_folder const folder{"lua_rows"};
auto const script{folder.write("rows.lua", rows_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "rows", &texture))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
REQUIRE(texture.pixels.size() == 8);
// green, the bottom row, first
CHECK(texture.pixels[0] == 0);
CHECK(texture.pixels[1] == 255);
CHECK(texture.pixels[4] == 255);
CHECK(texture.pixels[5] == 0);
queue.exit();
}
TEST_CASE("lua screens: a script reaches no files outside its folder, nor the system, nor ffi") {
script_folder const folder{"lua_sandbox"};
folder.write("../outside.txt", std::string_view{"outside"});
folder.write("data/inside.txt", std::string_view{"inside"});
auto const script{folder.write("sandbox.lua", sandbox_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "sandbox", &texture))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
REQUIRE(texture.pixels.size() == 4);
CHECK(texture.pixels[0] == 255);
queue.exit();
std::filesystem::remove(std::filesystem::temp_directory_path() / "outside.txt");
}
TEST_CASE("lua screens: precompiled code isn't loaded") {
script_folder const folder{"lua_bytecode"};
// LuaJIT bytecode starts with ESC "LJ"
auto const script{folder.write("compiled.lua", std::string_view{"\x1bLJ\x02\x00 not a script"})};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "compiled", &texture))};
refresh(queue, screen, speed(0.0), 1);
// it fails to load, and isn't refreshed again: a screen that runs would be due again within a few frames
for (int frame = 0; frame < 40; ++frame) {
queue.update();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
CHECK_FALSE(queue.due(*screen));
CHECK(texture.uploads == 0);
queue.exit();
}
TEST_CASE("lua screens: a script stuck in a loop is stopped, and the others keep working") {
script_folder const folder{"lua_spin"};
auto const spinning{folder.write("spin.lua", spin_script)};
auto const painting{folder.write("paint.lua", paint_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture stuck;
recording_texture working;
auto const first{queue.acquire(request(script_language::lua, spinning, "spin", &stuck))};
auto const second{queue.acquire(request(script_language::lua, painting, "paint", &working))};
refresh(queue, first, speed(1.0), 1);
refresh(queue, second, speed(2.0), 1);
REQUIRE(run_until(queue, [&working] { return working.uploads > 0; }));
CHECK(stuck.uploads == 0);
CHECK_FALSE(queue.due(*first));
queue.exit();
}
TEST_CASE("lua screens: nil from render keeps the image there is") {
script_folder const folder{"lua_once"};
auto const script{folder.write("once.lua", once_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "once", &texture))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
refresh(queue, screen, speed(0.0), 1);
refresh(queue, screen, speed(0.0), 1);
for (int frame = 0; frame < 20; ++frame) {
queue.update();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
CHECK(texture.uploads == 1);
CHECK(texture.pixels[2] == 3);
queue.exit();
}
TEST_CASE("lua screens: a script includes another and reads a font of the python screens' format") {
script_folder const folder{"lua_include"};
auto const script{folder.write("include.lua", include_script)};
folder.write("helper.lua", helper_script);
folder.write("font/test.png", test_font_png());
folder.write("font/test.txt", std::string_view{"// a comment line\r\na2\r\nb1\r\n"});
// the fonts are read top row first all the same
images_flipped_as_in_the_game const flipped;
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "include", &texture))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
REQUIRE(texture.pixels.size() == 8 * 2 * 4);
// bottom row first: the top row of the image is the second row of the texture
auto const top{[&texture](int const X) { return texture.pixels[(8 + X) * 4]; }};
auto const bottom{[&texture](int const X) { return texture.pixels[X * 4]; }};
CHECK(top(0) == 255);
CHECK(top(1) == 255);
CHECK(top(2) == 0); // the spacing column
CHECK(top(3) == 255);
CHECK(bottom(0) == 0);
CHECK(bottom(3) == 255);
// the x after the text (2 + 1 + 1 + 1), its width and the font's height
CHECK(texture.pixels[7 * 4] == 5);
CHECK(texture.pixels[7 * 4 + 1] == 5);
CHECK(texture.pixels[7 * 4 + 2] == 2);
queue.exit();
}
namespace {
// 2x1, red and green, shown through led_post without the glow and a resize to 4x3
constexpr std::string_view posted_script{R"(
return {
render = function(state)
local image = eu07.image(2, 1, { 255, 0, 0 })
image:set(1, 0, { 0, 255, 0 })
return image:led_post(false):resize(4, 3)
end
}
)"};
// reads an image after led_post: its size, a pixel of the frame and one of a diode
constexpr std::string_view read_posted_script{R"(
return {
render = function(state)
local posted = eu07.image(2, 1, { 255, 255, 255 }):led_post(false)
local width, height = posted:width(), posted:height()
local frame = posted:get(0, 0)
local diode = posted:get(1, 1)
return eu07.image(1, 1, { width * 10 + height, frame, diode })
end
}
)"};
// a gpu that keeps what it was given, or one that can't do it
struct recording_processor : script_screens::post_processor {
bool apply(ITexture & /*Target*/, std::span<std::uint8_t const> const Pixels, int const Width, int const Height,
std::span<script_screens::post_step const> const Steps) override {
++calls;
pixels.assign(Pixels.begin(), Pixels.end());
width = Width;
height = Height;
steps.assign(Steps.begin(), Steps.end());
return works;
}
bool works{true};
int calls{0};
std::vector<std::uint8_t> pixels;
int width{0};
int height{0};
std::vector<script_screens::post_step> steps;
};
// what posted_script shows, done on the cpu, bottom row first
std::vector<std::uint8_t> posted_on_cpu() {
script_screens::post_step led;
led.type = script_screens::post_step::kind::led;
led.bloom = false;
script_screens::post_step resize;
resize.type = script_screens::post_step::kind::resize;
resize.width = 4;
resize.height = 3;
std::array const steps{led, resize};
script_screens::post_image image{{255, 0, 0, 255, 0, 255, 0, 255}, 2, 1};
REQUIRE(script_screens::apply_post(image, steps));
std::vector<std::uint8_t> result;
for (auto row = image.height - 1; row >= 0; --row) {
auto const first{image.pixels.begin() + static_cast<std::ptrdiff_t>(script_screens::image_size(image.width, row))};
result.insert(result.end(), first, first + image.width * 4);
}
return result;
}
} // namespace
TEST_CASE("lua screens: led_post and resize of the image shown go to the gpu, with the image as drawn") {
script_folder const folder{"lua_post_gpu"};
auto const script{folder.write("posted.lua", posted_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_processor gpu;
queue.set_post_processor(&gpu);
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "posted", &texture, script_screen_kind::external))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&gpu] { return gpu.calls > 0; }));
CHECK(texture.uploads == 0);
CHECK(gpu.width == 2);
CHECK(gpu.height == 1);
CHECK(gpu.pixels == std::vector<std::uint8_t>{255, 0, 0, 255, 0, 255, 0, 255});
REQUIRE(gpu.steps.size() == 2);
CHECK(gpu.steps[0].type == script_screens::post_step::kind::led);
CHECK_FALSE(gpu.steps[0].bloom);
CHECK(gpu.steps[1].type == script_screens::post_step::kind::resize);
CHECK(gpu.steps[1].width == 4);
CHECK(gpu.steps[1].height == 3);
queue.exit();
}
TEST_CASE("lua screens: without a gpu, led_post and resize run on the cpu") {
script_folder const folder{"lua_post_cpu"};
auto const script{folder.write("posted.lua", posted_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "posted", &texture, script_screen_kind::external))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
CHECK(texture.width == 4);
CHECK(texture.height == 3);
CHECK(texture.pixels == posted_on_cpu());
queue.exit();
}
TEST_CASE("lua screens: when the gpu can't do the post-processing, the cpu does it from then on") {
script_folder const folder{"lua_post_fallback"};
auto const script{folder.write("posted.lua", posted_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_processor gpu;
gpu.works = false;
queue.set_post_processor(&gpu);
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "posted", &texture, script_screen_kind::external))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
CHECK(gpu.calls == 1);
CHECK(texture.width == 4);
CHECK(texture.pixels == posted_on_cpu());
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 1; }));
CHECK(gpu.calls == 1);
CHECK(texture.pixels == posted_on_cpu());
queue.exit();
}
TEST_CASE("lua screens: an image read after led_post has its post-processing done first") {
script_folder const folder{"lua_post_read"};
auto const script{folder.write("read.lua", read_posted_script)};
script_screen_queue queue;
REQUIRE(queue.init());
recording_processor gpu;
queue.set_post_processor(&gpu);
recording_texture texture;
auto const screen{queue.acquire(request(script_language::lua, script, "read", &texture, script_screen_kind::external))};
refresh(queue, screen, speed(0.0), 1);
REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; }));
CHECK(gpu.calls == 0);
REQUIRE(texture.pixels.size() == 4);
CHECK(texture.pixels[0] == 64); // 6 x 4
CHECK(texture.pixels[1] == 0);
CHECK(texture.pixels[2] == 255);
queue.exit();
}
#endif

View File

@@ -0,0 +1,154 @@
#include "stdafx.h"
#include "doctest.h"
#include "scripting/scriptscreenkernels.h"
#include <array>
#include <span>
#include <vector>
// the image filters the script screens call through the host give the pixels of the Python screens: led_util's
// render_post() and Pillow's resize(..., Image.LANCZOS). the expected images were made by them (Pillow 12.2) from a
// 5x3 image of (x*53 + y*97, x*31 + y*17 + 100, x*7 + y*151 + 40) mod 256
namespace {
// RGB as Pillow gives it
constexpr std::array<std::uint8_t, 45> source{
0, 100, 40, 53, 131, 47, 106, 162, 54, 159, 193, 61, 212, 224, 68, 97, 117, 191, 150, 148, 198, 203, 179, 205,
0, 210, 212, 53, 241, 219, 194, 134, 86, 247, 165, 93, 44, 196, 100, 97, 227, 107, 150, 2, 114,
};
constexpr std::array<std::uint8_t, 288> posted{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 144, 77, 28, 122, 65, 99, 194, 97,
84, 164, 82, 158, 236, 108, 134, 200, 91, 205, 255, 114, 174, 229, 96, 241, 255, 109, 204, 238, 92, 0, 0, 0,
0, 0, 0, 28, 122, 65, 23, 100, 53, 84, 164, 82, 69, 135, 67, 134, 200, 91, 110, 165, 75, 174, 229, 96,
143, 189, 79, 204, 238, 92, 168, 196, 76, 0, 0, 0, 0, 0, 0, 144, 173, 231, 122, 147, 196, 215, 229, 255,
182, 194, 219, 255, 255, 255, 219, 232, 230, 67, 255, 255, 56, 255, 235, 101, 255, 255, 85, 255, 225, 0, 0, 0,
0, 0, 0, 122, 147, 196, 100, 121, 161, 182, 194, 219, 150, 160, 180, 219, 232, 230, 180, 191, 189, 56, 255, 235,
46, 213, 193, 85, 255, 225, 70, 212, 185, 0, 0, 0, 0, 0, 0, 234, 178, 126, 198, 151, 107, 255, 231, 148,
251, 196, 125, 106, 255, 159, 90, 230, 135, 139, 255, 165, 118, 248, 140, 177, 65, 158, 150, 55, 134, 0, 0, 0,
0, 0, 0, 198, 151, 107, 163, 124, 88, 251, 196, 125, 207, 161, 103, 90, 230, 135, 74, 189, 111, 118, 248, 140,
97, 204, 115, 150, 55, 134, 123, 45, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
constexpr std::array<std::uint8_t, 561> enlarged{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 12, 46, 26, 22, 90, 53, 18, 71, 41, 50, 102, 55, 58, 108, 58, 53, 98, 52,
88, 131, 65, 87, 128, 62, 84, 119, 58, 114, 144, 69, 102, 139, 63, 106, 133, 60, 136, 144, 67, 139, 144, 68,
56, 71, 29, 0, 0, 0, 0, 0, 0, 16, 85, 39, 25, 165, 76, 21, 130, 59, 80, 188, 84, 94, 198, 89,
86, 178, 78, 155, 246, 102, 150, 236, 97, 151, 221, 89, 232, 255, 112, 210, 255, 100, 213, 250, 94, 255, 255, 108,
255, 255, 107, 113, 129, 44, 0, 0, 0, 0, 0, 0, 19, 67, 38, 31, 130, 74, 25, 100, 57, 72, 148, 78,
83, 155, 82, 75, 137, 72, 128, 191, 92, 124, 181, 87, 119, 172, 81, 167, 225, 99, 146, 202, 89, 151, 197, 85,
200, 238, 97, 198, 235, 95, 79, 96, 39, 0, 0, 0, 0, 0, 0, 70, 90, 108, 135, 177, 217, 108, 140, 171,
172, 198, 208, 188, 211, 215, 167, 186, 192, 218, 235, 219, 227, 238, 214, 175, 222, 204, 95, 245, 222, 62, 245, 213,
89, 240, 209, 122, 244, 224, 123, 243, 224, 49, 124, 99, 0, 0, 0, 0, 0, 0, 74, 89, 130, 139, 174, 255,
110, 136, 201, 182, 194, 246, 197, 205, 253, 170, 182, 223, 244, 239, 255, 255, 234, 252, 186, 218, 236, 52, 255, 255,
15, 245, 249, 49, 244, 240, 72, 255, 255, 73, 255, 255, 29, 130, 113, 0, 0, 0, 0, 0, 0, 76, 82, 96,
147, 160, 188, 114, 123, 145, 166, 177, 183, 181, 187, 188, 163, 165, 163, 186, 224, 205, 188, 214, 191, 140, 200, 176,
80, 251, 215, 54, 228, 190, 75, 211, 179, 105, 219, 206, 106, 217, 204, 42, 87, 82, 0, 0, 0, 0, 0, 0,
124, 96, 69, 250, 189, 137, 195, 149, 108, 225, 207, 138, 250, 221, 143, 237, 195, 127, 134, 244, 156, 80, 245, 148,
103, 228, 139, 135, 248, 165, 120, 252, 150, 129, 193, 143, 175, 68, 160, 178, 59, 161, 72, 34, 66, 0, 0, 0,
0, 0, 0, 135, 101, 67, 255, 197, 133, 206, 153, 103, 255, 216, 134, 255, 228, 139, 247, 200, 122, 127, 255, 152,
67, 255, 144, 98, 237, 134, 147, 255, 162, 131, 255, 146, 138, 187, 138, 189, 48, 157, 190, 37, 156, 76, 26, 64,
0, 0, 0, 0, 0, 0, 57, 44, 32, 110, 85, 64, 84, 65, 48, 121, 94, 63, 140, 98, 65, 102, 86, 57,
60, 120, 72, 39, 112, 68, 46, 103, 62, 61, 134, 76, 52, 133, 68, 56, 82, 64, 78, 34, 74, 77, 29, 73,
31, 16, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
};
constexpr std::array<std::uint8_t, 105> reduced{
2, 22, 10, 14, 58, 25, 35, 70, 30, 53, 83, 33, 74, 90, 34, 95, 99, 36, 37, 40, 13, 17, 60, 41,
63, 155, 101, 115, 186, 110, 157, 217, 117, 161, 234, 120, 207, 255, 127, 81, 103, 47, 52, 64, 91, 142, 165, 218,
186, 193, 220, 217, 219, 227, 58, 229, 227, 70, 251, 241, 32, 101, 90, 92, 72, 57, 230, 184, 137, 233, 214, 144,
110, 238, 155, 114, 255, 157, 158, 131, 166, 64, 23, 60, 32, 24, 16, 84, 60, 38, 82, 70, 41, 27, 79, 44,
40, 90, 45, 56, 29, 47, 22, 2, 17,
};
constexpr std::array<std::uint8_t, 288> plain{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 40, 0, 85, 34, 53, 131, 47,
45, 111, 39, 106, 162, 54, 90, 137, 45, 159, 193, 61, 135, 164, 51, 212, 224, 68, 180, 190, 57, 0, 0, 0,
0, 0, 0, 0, 85, 34, 0, 70, 28, 45, 111, 39, 37, 91, 32, 90, 137, 45, 74, 113, 37, 135, 164, 51,
111, 135, 42, 180, 190, 57, 148, 156, 47, 0, 0, 0, 0, 0, 0, 97, 117, 191, 82, 99, 162, 150, 148, 198,
127, 125, 168, 203, 179, 205, 172, 152, 174, 0, 210, 212, 0, 178, 180, 53, 241, 219, 45, 204, 186, 0, 0, 0,
0, 0, 0, 82, 99, 162, 67, 81, 133, 127, 125, 168, 105, 103, 138, 172, 152, 174, 142, 125, 143, 0, 178, 180,
0, 147, 148, 45, 204, 186, 37, 168, 153, 0, 0, 0, 0, 0, 0, 194, 134, 86, 164, 113, 73, 247, 165, 93,
209, 140, 79, 44, 196, 100, 37, 166, 85, 97, 227, 107, 82, 192, 90, 150, 2, 114, 127, 1, 96, 0, 0, 0,
0, 0, 0, 164, 113, 73, 135, 93, 60, 209, 140, 79, 172, 115, 65, 37, 166, 85, 30, 137, 70, 82, 192, 90,
67, 158, 74, 127, 1, 96, 105, 1, 79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
std::vector<std::uint8_t> rgba(std::span<std::uint8_t const> const Rgb) {
std::vector<std::uint8_t> result;
for (std::size_t idx = 0; idx < Rgb.size(); idx += 3) {
result.insert(result.end(), {Rgb[idx], Rgb[idx + 1], Rgb[idx + 2], 255});
}
return result;
}
} // namespace
TEST_CASE("script screen kernels: led_post gives the pixels of led_util.render_post") {
auto const input{rgba(source)};
std::vector<std::uint8_t> output(script_screens::image_size(12, 8), 7);
REQUIRE(script_screens::led_post(input, 5, 3, output, true));
CHECK(output == rgba(posted));
REQUIRE(script_screens::led_post(input, 5, 3, output, false));
CHECK(output == rgba(plain));
}
TEST_CASE("script screen kernels: resize_lanczos gives the pixels of Pillow's resize with LANCZOS") {
auto const input{rgba(posted)};
std::vector<std::uint8_t> larger(script_screens::image_size(17, 11));
REQUIRE(script_screens::resize_lanczos(input, 12, 8, larger, 17, 11));
CHECK(larger == rgba(enlarged));
std::vector<std::uint8_t> smaller(script_screens::image_size(7, 5));
REQUIRE(script_screens::resize_lanczos(input, 12, 8, smaller, 7, 5));
CHECK(smaller == rgba(reduced));
}
TEST_CASE("script screen kernels: images that don't fit their buffers are refused") {
std::vector<std::uint8_t> const input(script_screens::image_size(5, 3));
std::vector<std::uint8_t> output(script_screens::image_size(12, 8) - 1);
CHECK_FALSE(script_screens::led_post(input, 5, 3, output, true));
CHECK_FALSE(script_screens::led_post(input, 0, 3, output, true));
CHECK_FALSE(script_screens::resize_lanczos(input, 5, 3, output, 12, 8));
CHECK_FALSE(script_screens::resize_lanczos(input, 6, 3, output, 2, 2));
}
TEST_CASE("script screen kernels: the post-processing steps of an image run one after another") {
script_screens::post_step led;
led.type = script_screens::post_step::kind::led;
led.bloom = true;
script_screens::post_step resize;
resize.type = script_screens::post_step::kind::resize;
resize.width = 17;
resize.height = 11;
std::array const steps{led, resize};
CHECK(script_screens::width_after(led, 5) == 12);
CHECK(script_screens::height_after(led, 3) == 8);
CHECK(script_screens::width_after(resize, 12) == 17);
CHECK(script_screens::height_after(resize, 8) == 11);
script_screens::post_image image{rgba(source), 5, 3};
REQUIRE(script_screens::apply_post(image, steps));
CHECK(image.width == 17);
CHECK(image.height == 11);
CHECK(image.pixels == rgba(enlarged));
// nothing to do, nothing done
script_screens::post_image unchanged{rgba(source), 5, 3};
REQUIRE(script_screens::apply_post(unchanged, {}));
CHECK(unchanged.pixels == rgba(source));
// a size the kernels refuse leaves the image as it was
script_screens::post_image tooshort{std::vector<std::uint8_t>(10), 5, 3};
CHECK_FALSE(script_screens::apply_post(tooshort, steps));
CHECK(tooshort.width == 5);
CHECK(tooshort.pixels.size() == 10);
}

View File

@@ -0,0 +1,103 @@
#include "stdafx.h"
#include "doctest.h"
#include "scripting/scriptscreenrules.h"
#include "utilities/parser.h"
// the parts of the script screens that don't need the runtime: the .mmd entries, the refresh schedule counted in
// frames and the files a screen may read
using script_screens::frame_schedule;
using script_screens::screen_config;
TEST_CASE("script screens: a cab screen entry with every key") {
cParser parser("{ ekran.wasm target: screen01 frames: 6 parameters: id=1&mode=full } next:", cParser::buffer_TEXT);
screen_config config;
config.deserialize(parser);
CHECK(config.script == "ekran.wasm");
CHECK(config.target == "screen01");
CHECK(config.frames == 6);
CHECK(config.parameters == "id=1&mode=full");
// the parser stops at the end of the block
CHECK(parser.getToken<std::string>() == "next:");
}
TEST_CASE("script screens: the optional keys keep their defaults, an unknown key is skipped with its value") {
cParser parser("{ tablica.wasm later: 12 instance: name background: tablica_off }", cParser::buffer_TEXT);
screen_config config;
config.deserialize(parser);
CHECK(config.script == "tablica.wasm");
CHECK(config.target == "none");
CHECK(config.frames == 0);
CHECK(config.parameters.empty());
CHECK(config.instancing == "name");
CHECK(config.background == "tablica_off");
}
TEST_CASE("script screens: the interval set in eu07.ini, or the screen's own when it is longer") {
CHECK(frame_schedule::effective_interval(4, 0) == 4);
CHECK(frame_schedule::effective_interval(4, 10) == 10);
CHECK(frame_schedule::effective_interval(4, 2) == 4);
// never less than every frame
CHECK(frame_schedule::effective_interval(0, 0) == 1);
CHECK(frame_schedule::effective_interval(-3, -1) == 1);
}
TEST_CASE("script screens: a screen is due once per interval") {
frame_schedule schedule{100, 3, 0};
CHECK(schedule.poll(100));
// asked again in the same frame (the vehicle drawn in more than one pass)
CHECK_FALSE(schedule.poll(100));
CHECK_FALSE(schedule.poll(101));
CHECK_FALSE(schedule.poll(102));
CHECK(schedule.poll(103));
CHECK_FALSE(schedule.poll(105));
CHECK(schedule.poll(106));
}
TEST_CASE("script screens: a screen out of sight for a while is due on the first frame it is asked again") {
frame_schedule schedule{0, 5, 0};
CHECK(schedule.poll(0));
CHECK(schedule.poll(42));
CHECK_FALSE(schedule.poll(46));
CHECK(schedule.poll(47));
}
TEST_CASE("script screens: the phase spreads the screens over the frames of an interval") {
auto const interval{30};
auto const phase{frame_schedule::phase("make:dynamic/pkp/ed72/tablica.wasm?$timetable=ed72-001", interval)};
CHECK(phase >= 0);
CHECK(phase < interval);
// the same name always gets the same phase
CHECK(phase == frame_schedule::phase("make:dynamic/pkp/ed72/tablica.wasm?$timetable=ed72-001", interval));
// a screen refreshed every frame has no phase
CHECK(frame_schedule::phase("anything", 1) == 0);
frame_schedule schedule{1000, interval, phase};
auto first{std::uint64_t{0}};
for (auto frame = std::uint64_t{1000}; frame < 1000 + interval; ++frame) {
if (schedule.poll(frame)) {
first = frame;
break;
}
}
CHECK(first == 1000 + static_cast<std::uint64_t>(phase));
}
TEST_CASE("script screens: a screen reads files only below its own folder") {
CHECK(script_screens::is_safe_relative_path("font.png"));
CHECK(script_screens::is_safe_relative_path("data/font.png"));
CHECK(script_screens::is_safe_relative_path("data\\font.png"));
CHECK(script_screens::is_safe_relative_path("data/..font.png"));
CHECK_FALSE(script_screens::is_safe_relative_path(""));
CHECK_FALSE(script_screens::is_safe_relative_path("../eu07.ini"));
CHECK_FALSE(script_screens::is_safe_relative_path("data/../../eu07.ini"));
CHECK_FALSE(script_screens::is_safe_relative_path("data\\..\\x"));
CHECK_FALSE(script_screens::is_safe_relative_path(".."));
CHECK_FALSE(script_screens::is_safe_relative_path("/etc/passwd"));
CHECK_FALSE(script_screens::is_safe_relative_path("\\windows"));
CHECK_FALSE(script_screens::is_safe_relative_path("c:/windows/win.ini"));
}

View File

@@ -2,6 +2,7 @@
#include "doctest.h"
#include "vehicle.h"
#include "drive.h"
#include "vehicle/smoke.h"
@@ -83,3 +84,78 @@ TEST_CASE("smoke: the pending particles never outgrow the room of the source") {
CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, 10.0) == rate.limit);
}
TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") {
auto vehicle{diesel()};
vehicle->dizel_spinup = true;
auto pending{source};
pending.pending = 5.f;
vehicle->dizel_FiringCountdown = 0.5;
CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f);
vehicle->dizel_FiringCountdown = 0.0;
CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f);
}
namespace {
// the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains)
bool start_engine(test::driven const &Driven, test::track const &Track) {
for (int second = 0; second < 120 && false == Driven.controlling.Mains; ++second) {
test::start_up(Driven, Track, 1.0);
}
return Driven.controlling.Mains;
}
} // namespace
TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDelay after the starter began (#523)") {
// a diesel with a mechanical transmission and a diesel-electric one
for (auto const *path : {"sm42_v1/6d1", "st44_v2/m62-1151"}) {
CAPTURE(path);
test::track const track{};
{
// SmokeDelay set in the .fiz of the locomotive
test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 2)};
REQUIRE(locomotive->dizel_SmokeDelay == doctest::Approx(2.0));
auto const driven{test::driving(locomotive)};
REQUIRE(start_engine(driven, track));
// the engine started less than a second ago: the starter still turns it
CHECK(locomotive->dizel_FiringCountdown > 0.5);
CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f);
// it has fired since
test::drive(driven, track, 3.0);
CHECK(locomotive->Mains);
CHECK(locomotive->dizel_FiringCountdown == 0.0);
CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
}
{
// a longer delay from the .fiz
test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 5)};
auto const driven{test::driving(locomotive)};
REQUIRE(start_engine(driven, track));
test::drive(driven, track, 3.0);
CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f);
test::drive(driven, track, 3.0);
CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
}
}
}
TEST_CASE("smoke: without SmokeDelay in its .fiz a diesel smokes as soon as the starter turns, as before (#523)") {
for (auto const *path : {"sm42_v1/6d1", "st44_v2/m62-1151"}) {
CAPTURE(path);
test::track const track{};
// a locomotive which has the delay, loaded first, doesn't hand it on to the next one: the value is the vehicle's own
test::vehicle delayed{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 3)};
REQUIRE(delayed->dizel_SmokeDelay == doctest::Approx(3.0));
test::vehicle locomotive{test::definition::fiz(path)};
REQUIRE(locomotive->dizel_SmokeDelay == 0.0);
CHECK(delayed->dizel_SmokeDelay == doctest::Approx(3.0));
auto const driven{test::driving(locomotive)};
REQUIRE(start_engine(driven, track));
CHECK(locomotive->dizel_FiringCountdown == 0.0);
CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f);
}
}

View File

@@ -0,0 +1,268 @@
#include "stdafx.h"
#include "doctest.h"
#include "simulation/simulationtestrules.h"
#include <array>
#include <exception>
#include <new>
#include <stdexcept>
#include <vector>
// the test mode of the simulator (eu07 --test, eu07/maszyna#541): its exit codes, command line and end conditions
namespace {
using simulation::test_result;
simulation::test_command_line parse(std::vector<char const *> Arguments)
{
Arguments.insert(Arguments.begin(), "eu07");
return simulation::parse_test_command_line(Arguments);
}
// a frame of the default 0.03 s
simulation::test_frame frame(bool const Atrest, std::optional<double> const Reported = std::nullopt, std::string_view const Reason = {})
{
return simulation::test_frame{0.03, Reported, Reason, Atrest};
}
// runs frames until the test ends or Seconds of simulation time go by
std::optional<simulation::test_verdict> run(simulation::test_progress &Progress, simulation::test_limits const &Limits, double const Seconds,
simulation::test_frame const &Frame)
{
while (Progress.time < Seconds)
{
if (auto verdict{simulation::evaluate_frame(Progress, Frame, Limits)})
return verdict;
}
return std::nullopt;
}
} // namespace
TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or aborted process")
{
std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error};
for (auto const result : results)
{
auto const code{static_cast<int>(result)};
CAPTURE(code);
CHECK(code != 1); // TerminateProcess, most programs' failure
CHECK(code != 3); // abort() on Windows
CHECK(code < 126); // shells, signals on Linux
CHECK(simulation::to_string(result) != "unknown");
}
// the codes are public: scripts and CI read them
CHECK(static_cast<int>(test_result::pass) == 0);
CHECK(static_cast<int>(test_result::fail) == 10);
CHECK(static_cast<int>(test_result::signal_passed_at_danger) == 11);
CHECK(static_cast<int>(test_result::timeout) == 12);
CHECK(static_cast<int>(test_result::standstill) == 13);
CHECK(static_cast<int>(test_result::error) == 14);
}
TEST_CASE("test mode: seconds on the command line are a number, not negative")
{
CHECK(simulation::parse_seconds("240").value_or(-1.0) == doctest::Approx(240.0));
CHECK(simulation::parse_seconds("0.5").value_or(-1.0) == doctest::Approx(0.5));
CHECK(simulation::parse_seconds("0").value_or(-1.0) == doctest::Approx(0.0));
CHECK_FALSE(simulation::parse_seconds("").has_value());
CHECK_FALSE(simulation::parse_seconds("-1").has_value());
CHECK_FALSE(simulation::parse_seconds("60s").has_value());
CHECK_FALSE(simulation::parse_seconds("abc").has_value());
CHECK_FALSE(simulation::parse_seconds("inf").has_value());
CHECK_FALSE(simulation::parse_seconds("nan").has_value());
}
TEST_CASE("test mode: the command line")
{
SUBCASE("without --test there is no test")
{
auto const commandline{parse({"-s", "td.scn", "-v", "ep07-424"})};
CHECK_FALSE(commandline.enabled);
CHECK(commandline.error.empty());
}
SUBCASE("--test and its limits, in any order")
{
auto const commandline{parse({"--test-wall-timeout", "900", "-s", "td.scn", "--test", "--test-timeout", "240"})};
CHECK(commandline.enabled);
CHECK(commandline.timeout.value_or(-1.0) == doctest::Approx(240.0));
CHECK(commandline.wall_timeout.value_or(-1.0) == doctest::Approx(900.0));
CHECK(commandline.error.empty());
}
SUBCASE("a limit not given stays unset")
{
auto const commandline{parse({"--test", "-s", "td.scn"})};
CHECK_FALSE(commandline.timeout.has_value());
CHECK_FALSE(commandline.wall_timeout.has_value());
}
SUBCASE("a limit which isn't a number is an error, not a limit turned off")
{
auto const commandline{parse({"--test", "-s", "td.scn", "--test-timeout", "4m"})};
CHECK(commandline.enabled);
CHECK_FALSE(commandline.timeout.has_value());
CHECK(commandline.error == "--test-timeout needs a number of seconds");
}
SUBCASE("a limit without its value is an error")
{
auto const commandline{parse({"--test", "-s", "td.scn", "--test-wall-timeout"})};
CHECK(commandline.error == "--test-wall-timeout needs a number of seconds");
}
SUBCASE("the first error is the one told")
{
auto const commandline{parse({"--test", "--test-timeout", "x", "--test-wall-timeout", "y"})};
CHECK(commandline.error == "--test-timeout needs a number of seconds");
}
SUBCASE("values of other options aren't taken for options")
{
auto const commandline{parse({"-s", "--test", "-ini", "--test-timeout", "-v", "--test-wall-timeout", "-seed", "--test"})};
CHECK_FALSE(commandline.enabled);
CHECK(commandline.error.empty());
}
SUBCASE("-edit takes no option for its scenery, which is optional")
{
// a scenery after -edit or none: the option after it is read either way
CHECK(parse({"-edit", "--test", "-s", "td.scn"}).enabled);
CHECK(parse({"-edit", "td.scn", "--test"}).enabled);
// -edit leaves -s alone, which takes --test for its scenery, as the simulator reads it
CHECK_FALSE(parse({"-edit", "-s", "--test"}).enabled);
}
}
TEST_CASE("test mode: the real time limit")
{
SUBCASE("given, it is the limit, 0 turns it off")
{
CHECK(simulation::wall_clock_limit(120.0, 3600.0) == doctest::Approx(120.0));
CHECK(simulation::wall_clock_limit(0.0, 3600.0) == doctest::Approx(0.0));
}
SUBCASE("not given, it is the simulation time limit and time for the loading")
{
CHECK(simulation::wall_clock_limit(std::nullopt, 240.0) == doctest::Approx(240.0 + simulation::wall_timeout_loading_allowance));
CHECK(simulation::wall_clock_limit(std::nullopt, 3600.0) == doctest::Approx(3600.0 + simulation::wall_timeout_loading_allowance));
}
SUBCASE("no simulation time limit, no real time limit unless given")
{
CHECK(simulation::wall_clock_limit(std::nullopt, 0.0) == doctest::Approx(0.0));
CHECK(simulation::wall_clock_limit(300.0, 0.0) == doctest::Approx(300.0));
}
}
TEST_CASE("test mode: the end conditions")
{
simulation::test_limits limits;
simulation::test_progress progress;
SUBCASE("nothing happens, nothing ends")
{
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value());
CHECK(progress.time == doctest::Approx(0.03));
CHECK(progress.resttime == doctest::Approx(0.0));
}
SUBCASE("a cell nobody wrote to says nothing")
{
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, -1.0), limits).has_value());
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 2.0), limits).has_value());
CHECK_FALSE(progress.passrequested);
}
SUBCASE("0 fails at once, with the text of the cell")
{
auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0, "wrong_track"), limits)};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::fail);
CHECK(verdict->reason == "__test.result set to 0 (wrong_track)");
}
SUBCASE("1 passes once the tested trains have stood for a second")
{
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value());
CHECK(progress.passrequested);
// still moving: the pass waits
CHECK_FALSE(run(progress, limits, 30.0, frame(false, 1.0)).has_value());
auto const stoppedat{progress.time};
auto const verdict{run(progress, limits, 60.0, frame(true, 1.0))};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::pass);
CHECK(progress.time - stoppedat == doctest::Approx(simulation::pass_settle_time).epsilon(0.05));
}
SUBCASE("the pass stays requested when the cell changes back")
{
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value());
auto const verdict{run(progress, limits, 60.0, frame(true, -1.0))};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::pass);
}
SUBCASE("1 with test.no_movement_before_pass no passes at once")
{
limits.no_movement_before_pass = false;
auto const verdict{simulation::evaluate_frame(progress, frame(false, 1.0, "reached_the_stop"), limits)};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::pass);
CHECK(verdict->reason == "__test.result set to 1 (reached_the_stop)");
}
SUBCASE("standing still without a result ends after test.standstill")
{
limits.standstill = 120.0;
auto const verdict{run(progress, limits, 1000.0, frame(true))};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::standstill);
CHECK(progress.time == doctest::Approx(120.0).epsilon(0.001));
}
SUBCASE("a move starts the standstill over")
{
limits.standstill = 120.0;
CHECK_FALSE(run(progress, limits, 100.0, frame(true)).has_value());
CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value());
CHECK(progress.resttime == doctest::Approx(0.0));
CHECK_FALSE(run(progress, limits, 200.0, frame(true)).has_value());
}
SUBCASE("test.pass_on_standstill makes the standstill a pass")
{
limits.standstill = 10.0;
limits.pass_on_standstill = true;
auto const verdict{run(progress, limits, 1000.0, frame(true))};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::pass);
}
SUBCASE("test.standstill 0 never ends the test")
{
limits.standstill = 0.0;
limits.timeout = 0.0;
CHECK_FALSE(run(progress, limits, 5000.0, frame(true)).has_value());
}
SUBCASE("no result by test.timeout")
{
limits.timeout = 240.0;
auto const verdict{run(progress, limits, 1000.0, frame(false))};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::timeout);
CHECK(verdict->reason == "no result after 240 s");
CHECK(progress.time == doctest::Approx(240.0).epsilon(0.001));
}
SUBCASE("a result in the last frame wins over the timeout")
{
limits.timeout = 0.03;
auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0), limits)};
REQUIRE(verdict.has_value());
CHECK(verdict->result == test_result::fail);
}
}
TEST_CASE("test mode: what ended a run the simulator didn't end")
{
SUBCASE("an exception says what it was")
{
CHECK(simulation::describe_exception(std::make_exception_ptr(std::runtime_error("no scenery"))) == "critical error: no scenery");
// e.g. std::stof on a token of a scenery which isn't a number
CHECK(simulation::describe_exception(std::make_exception_ptr(std::invalid_argument("stof"))) == "critical error: stof");
CHECK(simulation::describe_exception(std::make_exception_ptr(std::bad_alloc())).starts_with("critical error: "));
}
SUBCASE("something thrown which isn't a std::exception")
{
CHECK(simulation::describe_exception(std::make_exception_ptr(42)) == "critical error: an exception of unknown type");
}
SUBCASE("terminated without an exception")
{
CHECK(simulation::describe_exception(nullptr) == "the simulator was terminated");
}
}

View File

@@ -0,0 +1,115 @@
#include "stdafx.h"
#include "doctest.h"
#include "vehicle.h"
#include "drive.h"
#include <cmath>
// the universal controller (EIMCtrlType 3) setting its power demand in steps (UCList CtrlValStep), as the 6Dg does
// in steps of 5% (eu07/maszyna#412). the 214M railbus's controller: 3 lowers the power to 0, 4 holds it, 5 raises it
// to 1, at 0.15 a second after IniCDelay (1 s)
using test::definition;
using test::vehicle;
namespace {
constexpr int lower{3};
constexpr int hold{4};
constexpr int raise{5};
// the railbus started up, its brakes released and its direction set, its controller holding no power
void get_ready(vehicle &Railbus, test::track const &Track) {
auto driven{test::driving(Railbus)};
REQUIRE(test::start_up(driven, Track));
test::release_brakes(driven.cab);
for (int i = 0; i < 3 && Railbus->DirActive <= 0; ++i) {
Railbus->DirectionForward();
}
while (Railbus->MainCtrlPos < hold && Railbus->IncMainCtrl(1)) {
;
}
while (Railbus->MainCtrlPos > hold && Railbus->DecMainCtrl(1)) {
;
}
REQUIRE(Railbus->MainCtrlPos == hold);
Railbus.run(2.0, Track);
REQUIRE(Railbus->eimic == doctest::Approx(0.0));
}
void move_to(vehicle &Railbus, int const Position) {
while (Railbus->MainCtrlPos < Position && Railbus->IncMainCtrl(1)) {
;
}
while (Railbus->MainCtrlPos > Position && Railbus->DecMainCtrl(1)) {
;
}
REQUIRE(Railbus->MainCtrlPos == Position);
}
bool on_step(double const Value, double const Step) {
return std::abs(Value / Step - std::round(Value / Step)) < 1e-6;
}
} // namespace
TEST_CASE("controls: the universal controller with CtrlValStep sets its power in whole steps") {
test::track const line{0.15, 0.0};
vehicle railbus{definition::fiz("21xm_v1/214ma").set("UCList", "CtrlValStep", 0.05), 0.0, "test", 1};
REQUIRE(railbus->UniCtrlValStep == doctest::Approx(0.05));
get_ready(railbus, line);
// a tap on the raising position: one step at once, kept by the holding one
move_to(railbus, raise);
railbus.step(line);
CHECK(railbus->eimic == doctest::Approx(0.05));
move_to(railbus, hold);
railbus.run(2.0, line);
CHECK(railbus->eimic == doctest::Approx(0.05));
// held there: after the initial delay a step each third of a second (0.15 a second), never in between
move_to(railbus, raise);
for (int i = 0; i < 310; ++i) { // 3.1 s
railbus.step(line);
CAPTURE(i);
CHECK(on_step(railbus->eimic, 0.05));
}
// the first step at once, 1 s of the initial delay, then 2.1 s of 0.15 a second (6 steps)
CHECK(railbus->eimic == doctest::Approx(0.40));
move_to(railbus, hold);
railbus.run(2.0, line);
CHECK(railbus->eimic == doctest::Approx(0.40));
// up to the full power, and not past it
move_to(railbus, raise);
railbus.run(10.0, line);
CHECK(railbus->eimic == doctest::Approx(1.0));
// down the same way: a tap is one step, holding it goes on in steps down to nothing
move_to(railbus, lower);
railbus.step(line);
CHECK(railbus->eimic == doctest::Approx(0.95));
move_to(railbus, hold);
railbus.run(1.0, line);
CHECK(railbus->eimic == doctest::Approx(0.95));
move_to(railbus, lower);
for (int i = 0; i < 800; ++i) { // 8 s
railbus.step(line);
CAPTURE(i);
CHECK(on_step(railbus->eimic, 0.05));
}
CHECK(railbus->eimic == doctest::Approx(0.0));
}
TEST_CASE("controls: the universal controller without CtrlValStep sets its power continuously, as before") {
test::track const line{0.15, 0.0};
vehicle railbus{definition::fiz("21xm_v1/214ma"), 0.0, "test", 1};
REQUIRE(railbus->UniCtrlValStep == 0.0);
get_ready(railbus, line);
// a tap moves it by 0.01, held it goes on at 0.15 a second after the initial delay
move_to(railbus, raise);
railbus.step(line);
CHECK(railbus->eimic == doctest::Approx(0.01));
railbus.run(2.0 - 0.01, line);
CHECK(railbus->eimic == doctest::Approx(0.01 + 0.15).epsilon(0.05));
}