18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 21:45:16 +01:00

feat(event): putvalues Crew:<vehicle> puts an AI driver in a vehicle or takes it off (GE#510) (#422)

* test: scenario runs convert no models in the game dir

* feat(vehicle): rules of the crew command of putvalues events

Crew:<vehicle> <cab> <flags> (eu07/maszyna#510): reading the command,
what gets done in each state of the vehicle, and the state a train is
left in when the driver in charge of it is taken off. Core library,
with unit tests; nothing calls it yet.

* feat(event): putvalues Crew:<vehicle> puts an AI driver in a vehicle or takes it off

event <name> putvalues <delay> none 0 0 0 Crew:<vehicle> <cab> <flags> endevent
(eu07/maszyna#510): cab 1 or -1 gives the vehicle named an AI driver in
cab A or B, the way the scenery creates one, 0 takes the AI driver off
and leaves the train with the power off and the brake valve in the
emergency position. A vehicle with a user in it is left alone, with a
line in the log. The vehicle is named in the text, so the event needs
nothing to set it off. Without the command nothing changes.

* test: scenario checks on the driver and the speed of a vehicle in the black box

* test: scenario cases of the crew event on td.scn

A driver appears in cab A and in cab B of a standing locomotive and
leaves with it, a train on the run loses its driver and stops (EU07,
EN57, Vectron, SM42), a driver is replaced, and the commands which have
to be refused change nothing about a timetable run.

* feat(event): road vehicles take a driver from the crew command too

They have no driver's brake valve, which is what tells a cab in a rail
vehicle, and any of them is driven from its own seat.

* test: scenario case of the crew event on a car

stops_driverless holds until the vehicle gets a driver again, not only
to the end of the recording.

* fix(event): the crew command clears the driver from every vehicle in its charge

A coupler broken under force or in a collision parts the train without clearing
the owner of the vehicles parted from it. When the driver was taken off, these
kept a pointer to the deleted driver. All vehicles are now looked at, not only
the ones still coupled. The log tells how many vehicles the driver let go.

* test: scenario case of the crew event on a train parted by a broken coupler

A new black box check, parts, tells two vehicles came apart in the run.
The case parts an EN57-2000 unit by a hit at 100 km/h and takes its driver
off: the driver had the parted car in charge too, and lets it go.

* fix(event): one vehicle in the log line of the crew command
This commit is contained in:
jerrrrycho
2026-11-20 04:24:48 +01:00
committed by GitHub
parent b9737fe76d
commit 18143c2254
20 changed files with 1218 additions and 1 deletions

View File

@@ -126,6 +126,7 @@ set(SOURCES
"vehicle/Button.cpp"
"vehicle/Camera.cpp"
"vehicle/Driver.cpp"
"vehicle/crewchange.cpp"
"application/driverhints.cpp"
"vehicle/DynObj.cpp"
"EU07.cpp"
@@ -564,6 +565,7 @@ set(CORE_SOURCES
"vehicle/brakesetting.cpp"
"vehicle/drivingaid.cpp"
"vehicle/handover.cpp"
"vehicle/crew.cpp"
"vehicle/horn.cpp"
"vehicle/cameraviews.cpp"
"vehicle/linebreaker.cpp"

View File

@@ -265,6 +265,47 @@ pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the bl
locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its
hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s.
The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a
`putvalues` event, `Crew:<vehicle> <cab> <flags>`: cab 1 or -1 puts an AI driver in cab A or B of
the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are
set off by event launchers, at an hour or with a delay; `vars.trainsets` are the vehicles and
`vars.crew` the events of the case:
- `eu07_td_crew_add`: an EU07 standing cold with nobody in it gets a driver in cab A 20 s after
the start. A driver put in a standing vehicle waits for orders, as the one of a standing
trainset does, so `event0` of its track gives the order to go (`Shunt -1 0`), once: the driver
starts the locomotive and leaves through the exit signal, whose aspect makes it a train run.
`eu07_td_crew_add_rear` is the same with cab B: the locomotive leaves the other way, its rear
end leading (`moves`, from the black box).
- `eu07_td_crew_remove`: the EU07 of `eu07_td_timetable` loses its driver at 10:36, on the run at
59 km/h. It is left with the power off and the brake valve in the emergency position: it
stands 16 s and 168 m later and doesn't move in the 164 s to the end (`stops_driverless`; the
physicslog ends when the driver goes). `en57_td_crew_remove` (driven from the head car, the
motors in the middle one), `vectron_td_crew_remove` (induction motors and an integrated handle)
and `sm42_td_crew_remove` (diesel) are the same with other vehicles.
- `eu07_td_crew_swap`: the driver waiting at Stacja1 is taken off after 20 s, which leaves the
locomotive braked, and a new one put in 20 s later, who gets the order to go, releases the
brakes and leaves.
- `golf_td_crew_swap`: a car running along the road `d3` at 50 km/h loses its driver, which
leaves it with its own brake applied in full: it stands 3 s and 17 m later. A road vehicle has
no cab to tell by and takes a driver all the same: the new one, put in 40 s later, drives on
along the road, at up to 100 km/h, having no timetable to cap the speed as the first one had
(the trainset's `50`).
- `eu07_td_crew_refused`: the run of `eu07_td_timetable` with crew events which must be refused,
at the start and again on the run: a second driver for the locomotive, a driver for a coach
(no cab), a cab which is none of 1, -1, 0, a driver taken off a coach which has none, and a
vehicle the scenery lacks. Each leaves its line in the log and the train runs its timetable to
the stop at Przystanek as it does without them.
- `en57_td_crew_parted`: an EN57-2000 unit with an AI driver and no timetable stands on track 1,
another one with nobody in it runs into its rear at 100 km/h (`crashdamage yes`). The hit
breaks the coupler between the middle and the rear car (`parts`, at 2 s), which leaves the rear
car with the driver in charge of it. The driver taken off at 10:35 had all three cars in charge,
the parted one too, and none of them keeps it (the log line `the driver was in charge of 3
vehicles`; the cars still coupled to the head car are two).
A vehicle with a user in it is left alone by the command, which the test mode can't show: nobody
sits in a vehicle there.
`eu07_td_hauls_dead_vectron` is the timetable run with a dead locomotive in the train: behind the EU07 a
Vectron with nobody in it, coupled with the hook and the brake hose alone (the EU07's coupling `3`) and
prepared for hauling, the parameter `H` after its own coupling (`0.H`: the pullee mode of
@@ -360,10 +401,25 @@ the row instead, logged by builds from this branch on.
filled in as in the fragment, e.g. `{{vehicle}}_rb`. Fails when the two were coupled from the
start, came apart again, or the run left no black box. The black box is looked at once a
second, so the time given is that of the first look after the couplers caught.
- `parts` `vehicle`, `other`, optional `before`: the black box has the two vehicles, coupled to
each other, come apart (the coupler itself let go: broken, or uncoupled), by the time `before`
of the recording when given.
- `driver_changes` `vehicle`, `to`, optional `after`, `before`: the black box has the vehicle get
the driver `to` (`none`, `ai` or `user`) at a time of the recording between the two, having had
another one before, and keep it to the end.
- `stops_driverless` `vehicle`, `min_speed`, `within`, optional `stop_speed` (0.5), `max_creep`
(1 m), `hold` (60 s): the black box has the vehicle lose its driver at `min_speed` or faster,
stand `within` seconds later and stay within `max_creep` of where it stopped for the rest of
the recording, or until it gets a driver again, at least `hold` seconds. The physicslog can't
tell: the driver writes it, so it ends when the driver goes.
- `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the
vehicle reach `min_speed` with that end leading (the physicslog speed has no direction).
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`. Checks on the log go in `LOG_CHECKS` and get the
text of `log.txt` instead of the rows. Checks on the black box (`blackbox_doc.md` in the root of
the repo; the simulator writes it along with the physicslogs) go in `BLACKBOX_CHECKS` and get
what `read_blackbox()` read of it: the names of the vehicles and the coupling records. A check
what `read_blackbox()` read of it: the names of the vehicles, the coupling records, and the
states of each vehicle from the `vehicles` records (position, speed, driver; a vehicle is listed
when it moved, changed speed or got another driver, and all of them every 60 s). A check
on another kind of record has to add it there.

View File

@@ -0,0 +1,34 @@
{
"description": "Crew event on a train parted by a broken coupler (eu07/maszyna#510, review of #422): an EN57-2000 unit with an AI driver and no timetable stands on track 1 of Stacja1 on td.scn, and another one with nobody in it runs into its rear at 100 km/h. The hit breaks the coupler between the middle and the rear car of the standing unit (TMoverParameters::damage_coupler()), which parts the unit and leaves the rear car with the driver in charge of it, as uncoupling doesn't. At 10:35 a putvalues event, Crew:<vehicle> 0 0, takes the driver off: all three vehicles of the unit had it in charge, the parted ones too, and none of them keeps it.",
"base_scenery": "td.scn",
"ini": ["crashdamage yes"],
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset none tdo_n1734 0.0 0.0",
"node -1 0 {{vehicle}} dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 headdriver 255 0 enddynamic",
"node -1 0 {{vehicle}}_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic",
"node -1 0 {{vehicle}}_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic",
"endtrainset",
"trainset none tdo_n1725 0.0 100",
"node -1 0 {{vehicle}}_hit_ra dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 nobody 255 0 enddynamic",
"node -1 0 {{vehicle}}_hit_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic",
"node -1 0 {{vehicle}}_hit_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1035 autotest_crew_off end"
]
},
"duration": 120,
"timeout": 600,
"checks": [
{ "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ broke a coupler" },
{ "type": "parts", "vehicle": "{{vehicle}}_s", "other": "{{vehicle}}_rb", "before": 30 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the AI driver leaves" },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the driver was in charge of 3 vehicles" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 50, "before": 70 }
]
}

View File

@@ -0,0 +1,29 @@
{
"description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an EN57 unit of three cars, driven from its head car while the motors are in the middle one, which loses its AI driver on the run at 10:36, stops and stays where it stopped.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic",
"node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic",
"node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end"
]
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_remove\\] the AI driver leaves" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 },
{ "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,31 @@
{
"description": "Crew event, a driver appears (eu07/maszyna#510): an EU07 stands cold on track 1 of Stacja1 on td.scn with nobody in it. 20 s after the start a putvalues event, Crew:<vehicle> 1 0, puts an AI driver in its cab A; the scenery then gives the driver the order to go (Shunt -1 0 from event0 of the track), and the driver starts the locomotive and leaves through the exit signal.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset none tdo_n1734 0.0 0.0",
"node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent",
"event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent",
"node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end"
]
},
"track_events": {
"tdo_n1734": "event0 autotest_wake"
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add\\] an AI driver takes cab A" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 },
{ "type": "starts", "min_speed": 20, "within": 240 },
{ "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,33 @@
{
"description": "Crew event, a driver appears in cab B (eu07/maszyna#510): as eu07_td_crew_add, with Crew:<vehicle> -1 0. The driver takes the rear cab, so the order to go sends the locomotive the other way, its rear end leading.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset none tdo_n1734 0.0 0.0",
"node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} -1 0 endevent",
"event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent",
"node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end"
]
},
"track_events": {
"tdo_n1734": "event0 autotest_wake"
},
"test_config": [
"test.fail_if_stop_overran no"
],
"duration": 200,
"timeout": 600,
"checks": [
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add_rear\\] an AI driver takes cab B" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 },
{ "type": "moves", "vehicle": "{{vehicle}}", "direction": "rear", "min_speed": 5 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,40 @@
{
"description": "Crew events which must change nothing (eu07/maszyna#510): the run of eu07_td_timetable, with a coach standing on track 2, and crew events set off at the start and again at 10:36, on the run: a second driver for the locomotive (it has one), a driver for the coach (no cab), a cab which is none of 1, -1, 0, a driver taken off the coach (it has none) and a vehicle the scenery lacks. Each is refused in the log and the train runs its timetable to the stop at Przystanek.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic",
"endtrainset",
"trainset none tor2k 30.0 0.0",
"node -1 0 {{vehicle}}_coach dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_second putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent",
"event autotest_crew_coach putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 1 0 endevent",
"event autotest_crew_cab putvalues 0 none 0 0 0 Crew:{{vehicle}} 2 0 endevent",
"event autotest_crew_nobody putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 0 0 endevent",
"event autotest_crew_unknown putvalues 0 none 0 0 0 Crew:autotest_no_such_vehicle 0 0 endevent",
"event autotest_crew_all multiple 0 none autotest_crew_second autotest_crew_coach autotest_crew_cab autotest_crew_nobody autotest_crew_unknown endevent",
"node -1 0 autotest_crew_launcher1 eventlauncher 0 0 0 -1 none 1034 autotest_crew_all end",
"node -1 0 autotest_crew_launcher2 eventlauncher 0 0 0 -1 none 1036 autotest_crew_all end"
]
},
"duration": 240,
"timeout": 600,
"checks": [
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
{ "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the vehicle has a driver already" },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] refused, the vehicle has no cab" },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the cab has to be 1, -1 or 0" },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] no driver to take off" },
{ "type": "log_contains", "pattern": "PutValues - \\[Crew:autotest_no_such_vehicle\\]" },
{ "type": "log_lacks", "pattern": "Crew: .* (takes cab|leaves)" }
]
}

View File

@@ -0,0 +1,27 @@
{
"description": "Crew event, the driver disappears (eu07/maszyna#510): an EU07 with an AI driver leaves Stacja1 on td.scn on the td/rozklad timetable at 10:35. At 10:36, on the run, a putvalues event, Crew:<vehicle> 0 0, takes the driver off: the locomotive is left with the power off and the brake valve in the emergency position, stops and stays where it stopped.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end"
]
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_remove\\] the AI driver leaves" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 },
{ "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,34 @@
{
"description": "Crew events, the driver is replaced (eu07/maszyna#510): an EU07 with an AI driver waits on track 1 of Stacja1 on td.scn. 20 s after the start Crew:<vehicle> 0 0 takes the driver off, which leaves the locomotive braked; 20 s later Crew:<vehicle> 1 0 puts a new one in cab A, who gets the order to go (Shunt -1 0 from event0 of the track), releases the brakes and leaves through the exit signal.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end",
"event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent",
"event autotest_crew_on multiple 40 none autotest_crew_put autotest_crew_waits endevent",
"node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end"
]
},
"track_events": {
"tdo_n1734": "event0 autotest_wake"
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] the AI driver leaves" },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] an AI driver takes cab A" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 35, "before": 50 },
{ "type": "starts", "min_speed": 20, "within": 200 },
{ "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,30 @@
{
"description": "Crew events on a road vehicle (eu07/maszyna#510): a car with an AI driver runs along the road d3 of td.scn, at 50 km/h, the top speed its trainset gives it. 20 s after the start Crew:<vehicle> 0 0 takes the driver off: the car is left with its own brake applied in full, stops and stands. 40 s later Crew:<vehicle> 1 0 puts a driver in again (a road vehicle has no cab to tell by, and takes one all the same), who drives on along the road, with no timetable to cap the speed.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset 50 d3 0.0 30",
"node -1 0 {{vehicle}} dynamic road\\golf none golf 0 headdriver 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end",
"event autotest_crew_on putvalues 60 none 0 0 0 Crew:{{vehicle}} 1 0 endevent",
"node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end"
]
},
"duration": 120,
"timeout": 600,
"checks": [
{ "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] the AI driver leaves" },
{ "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 10, "within": 30, "hold": 30 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] an AI driver takes cab A" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 55, "before": 70 },
{ "type": "starts", "min_speed": 20, "within": 60 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,27 @@
{
"description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an SM42 diesel shunter which loses its AI driver on the run at 10:36, stops and stays where it stopped.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end"
]
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_sm42_td_crew_remove\\] the AI driver leaves" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 },
{ "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -0,0 +1,22 @@
// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
// the vehicles of the case (vars.trainsets), the lead one on track 1 of Stacja1 (tdo_n1734), where td.scn keeps
// its timetable train, and the crew events of the case (vars.crew, eu07/maszyna#510): a putvalues event with
// "Crew:<vehicle> <cab> <flags>" puts an AI driver in cab A (1) or cab B (-1) of the vehicle named, or takes its
// AI driver off (0). the vehicle is named in the text, so the events run from event launchers, with no vehicle
// setting them off.
{{trainsets}}
// the way out of track 1, see td_timetable.scn
node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end
{{crew}}
// a driver put in a standing vehicle waits for orders, as the driver of a standing trainset does, and the scenery
// has to give them. event0 of the track the locomotive stands on (the track_events of the case) runs while a
// vehicle with a driver in charge stands there; once the cell says a new driver waits (autotest_crew_waits, run
// along with the crew event), it gives the order to go, Shunt -1 0, one time.
node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell
event autotest_crew_waits UpdateValues 0 autotest_ordered * 1 * endevent
event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 1 * endevent
event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent
event autotest_order_given UpdateValues 0 autotest_ordered * 2 * endevent

View File

@@ -0,0 +1,27 @@
{
"description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with a Vectron (induction motors, an integrated power and brake handle) which loses its AI driver on the run at 10:36, stops and stays where it stopped.",
"base_scenery": "td.scn",
"time": "10:34",
"fragment": "td_crew.scn",
"vars": {
"trainsets": [
"trainset td/rozklad tdo_n1734 0.0 0.1",
"node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic",
"endtrainset"
],
"crew": [
"event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent",
"node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end"
]
},
"duration": 300,
"timeout": 600,
"checks": [
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "log_contains", "pattern": "Crew: \\[autotest_vectron_td_crew_remove\\] the AI driver leaves" },
{ "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 },
{ "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 },
{ "type": "log_lacks", "pattern": "derailed" },
{ "type": "log_lacks", "pattern": "collided" }
]
}

View File

@@ -29,6 +29,7 @@ from __future__ import annotations
import argparse
import json
import os
import math
import re
import shutil
import struct
@@ -77,12 +78,14 @@ width 1280
height 720
inactivepause no
soundenabled no
convertmodels 0
physicslog {physicslog}
multiplelogs yes
timespeed {timespeed}
"""
# multiplelogs: log and errors go to logs/log (<scenery>) <date>.txt instead of the shared
# log.txt, so runs of different cases can go in parallel
# convertmodels 0: a test run writes no converted models (.e3d) into the game dir
# ---------------------------------------------------------------- scenery
@@ -241,8 +244,10 @@ def read_text(path: Path | None) -> str:
BLACKBOX_MAGIC = b"EU07BBX\0"
BLACKBOX_HEADER = 12 # the magic, the version of the format, two bytes reserved
BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name
BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver
BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed
COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself
BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state
@dataclass
@@ -258,10 +263,21 @@ class Coupling:
previous_other: int
@dataclass
class VehicleState:
"""A vehicle in a `vehicles` record: where it is and who drives it from `time` on, until its next one."""
time: float
position: tuple[float, float, float]
speed: float # km/h, positive along its front
driver: int # 0 none, 1 a user, 2 the AI
@dataclass
class Blackbox:
vehicles: dict[int, str] = field(default_factory=dict) # names by number
couplings: list[Coupling] = field(default_factory=list) # in the order written
states: dict[int, list[VehicleState]] = field(default_factory=dict) # of each vehicle by number, in time order
end_time: float = 0.0 # of the last `vehicles` record
def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None:
@@ -303,6 +319,13 @@ def read_blackbox(path: Path | None) -> Blackbox | None:
if byte < 0x80:
break
box.vehicles[number] = content[start: start + size].decode("utf-8", errors="replace")
elif kind == BLACKBOX_VEHICLES:
# the time, a keyframe mark, the count, then 25 bytes a vehicle: number, position, heading, speed, driver
when, _, count = struct.unpack_from("<dBI", content)
box.end_time = when
for i in range(count):
number, x, y, z, _, speed, driver = struct.unpack_from("<I3fffB", content, 13 + 25 * i)
box.states.setdefault(number, []).append(VehicleState(when, (x, y, z), speed, driver))
elif kind == BLACKBOX_COUPLING:
# the position of the coupler follows
box.couplings.append(Coupling(*struct.unpack_from("<dIBIBBBI", content)))
@@ -616,9 +639,113 @@ def check_couples(box, vehicle, other):
f"{ends[c.other_side]} one of {box.vehicles[c.other]}, coupling 0x{c.flags:02X}")
def check_parts(box, vehicle, other, before=None):
"""The two vehicles, coupled to each other, come apart in the run: a coupler broken, or uncoupled."""
numbers = {name.lower(): number for number, name in box.vehicles.items()}
unknown = [name for name in (vehicle, other) if name.lower() not in numbers]
if unknown:
return False, f"the black box has no vehicle {' nor '.join(unknown)}"
pair = {numbers[vehicle.lower()], numbers[other.lower()]}
# the record of the coupler which let go: coupled to the other vehicle before, the coupler itself no more
c = next((c for c in box.couplings if {c.vehicle, c.previous_other} == pair
and c.previous_flags & COUPLING_COUPLER and not c.flags & COUPLING_COUPLER), None)
if c is None:
return False, f"none of the {len(box.couplings)} coupling record(s) of the black box parts {vehicle} and {other}"
if before is not None and c.time > before:
return False, f"{vehicle} and {other} came apart at t={c.time:.1f}s, after {before:g}s"
ends = ("front", "rear")
return True, (f"at t={c.time:.1f}s the {ends[c.side]} coupler of {box.vehicles[c.vehicle]} let go of "
f"{box.vehicles[c.previous_other]}, coupling 0x{c.previous_flags:02X} before")
def _vehicle_states(box, vehicle):
"""The states of the vehicle named, or None and why not."""
numbers = {name.lower(): number for number, name in box.vehicles.items()}
number = numbers.get(vehicle.lower())
if number is None:
return None, f"the black box has no vehicle {vehicle}"
states = box.states.get(number)
if not states:
return None, f"the black box has no state of {vehicle}"
return states, ""
def _driver_change(states, to):
"""The first state with the driver `to` after one with another driver; None when there is none."""
return next((now for before, now in zip(states, states[1:]) if now.driver == to and before.driver != to), None)
def check_driver_changes(box, vehicle, to, after=0.0, before=None):
"""The vehicle gets the driver `to` (none, ai, user) between the times given, and keeps it to the end."""
states, why = _vehicle_states(box, vehicle)
if states is None:
return False, why
wanted = BLACKBOX_DRIVERS[to]
names = {number: name for name, number in BLACKBOX_DRIVERS.items()}
change = _driver_change(states, wanted)
if change is None:
return False, f"{vehicle} starts with driver {names.get(states[0].driver)} and never changes to {to}"
if change.time < after or (before is not None and change.time > before):
return False, f"{vehicle} got driver {to} at t={change.time:.1f}s, outside {after:g}..{before if before is not None else 'end'}"
later = next((s for s in states if s.time > change.time and s.driver != wanted), None)
if later is not None:
return False, f"{vehicle} got driver {to} at t={change.time:.1f}s but {names.get(later.driver)} at t={later.time:.1f}s"
return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)"
def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0):
"""The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it
stopped, to the end of the recording or until it gets a driver again."""
states, why = _vehicle_states(box, vehicle)
if states is None:
return False, why
left = _driver_change(states, BLACKBOX_DRIVERS["none"])
if left is None:
return False, f"{vehicle} never loses its driver"
if abs(left.speed) < min_speed:
return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, below {min_speed}"
after = [s for s in states if s.time >= left.time]
stop = next((s for s in after if abs(s.speed) <= stop_speed), None)
if stop is None or stop.time - left.time > within:
took = "never" if stop is None else f"after {stop.time - left.time:.0f}s"
return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h and stood {took} (limit {within}s)"
# left alone until the recording ends, or a driver comes again
crewed = next((s for s in after if s.time > stop.time and s.driver != BLACKBOX_DRIVERS["none"]), None)
until = crewed.time if crewed else box.end_time
alone = "until a driver came" if crewed else "to the end"
if until - stop.time < hold:
return False, f"{vehicle} stood at t={stop.time:.1f}s, with no driver for {until - stop.time:.0f}s more {alone} (hold {hold}s)"
# a standing vehicle is listed again only in the keyframes, or when it moves
standing = [s for s in after if stop.time <= s.time <= until]
fastest = max(abs(s.speed) for s in standing)
creep = max(math.dist(s.position, stop.position) for s in standing)
if fastest > stop_speed or creep > max_creep:
return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver"
way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time)
return True, (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s "
f"and {way:.0f} m later, moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}")
def check_moves(box, vehicle, min_speed, direction="front"):
"""The vehicle reaches `min_speed` with its front end leading, or its rear one (the physicslog has no direction)."""
states, why = _vehicle_states(box, vehicle)
if states is None:
return False, why
sign = {"front": 1.0, "rear": -1.0}[direction]
fastest = max(states, key=lambda s: sign * s.speed)
if sign * fastest.speed < min_speed:
return False, f"{vehicle} never reaches {min_speed} km/h {direction} end leading, at most {sign * fastest.speed:.1f}"
first = next(s for s in states if sign * s.speed >= min_speed)
return True, f"{vehicle} runs {direction} end leading: {min_speed} km/h at t={first.time:.1f}s, up to {sign * fastest.speed:.1f} km/h"
# checks on the black box of the run rather than on the physicslog rows
BLACKBOX_CHECKS = {
"couples": check_couples,
"parts": check_parts,
"driver_changes": check_driver_changes,
"stops_driverless": check_stops_driverless,
"moves": check_moves,
}

313
tests/unit/test_crew.cpp Normal file
View File

@@ -0,0 +1,313 @@
#include "stdafx.h"
#include "doctest.h"
#include "consist.h"
#include "drive.h"
#include "McZapkie/hamulce.h"
#include "vehicle/crew.h"
// a driver put in a vehicle or taken off it by a "Crew:<vehicle>" putvalues event (eu07/maszyna#510): reading the
// command, what gets done about it in each state of the vehicle, and the state a train is left in when the driver
// in charge of it is taken off. the game's side (finding the vehicle, creating and deleting the driver) is run by
// the scenario cases, tests/scenarios/cases/*crew*
using test::consist;
using test::definition;
using test::track;
using test::vehicle;
namespace {
track const line{0.15, 0.0, test::catenary_3kv};
// the train started up by its driver, brakes released, then under power for Seconds: a notch a second up to the
// given position of the main controller
void get_under_way(consist &Train, int const Position, double const Seconds) {
auto driver{test::driving(Train)};
REQUIRE(test::start_up(driver, line));
test::release_brakes(driver.cab);
for (int i = 0; i < 3 && driver.cab.DirActive <= 0; ++i) {
driver.cab.DirectionForward();
}
test::drive(driver, line, 20.0);
driver.controlling.IncMainCtrl(1);
for (int i = 0; i < 90 && false == driver.controlling.StLinFlag; ++i) {
test::drive(driver, line, 1.0);
}
for (int i = 0; i < 60 && driver.controlling.MainCtrlPos < Position; ++i) {
driver.controlling.IncMainCtrl(1);
test::drive(driver, line, 1.0);
}
test::drive(driver, line, Seconds);
}
// seconds until the train stands, up to Limit. nobody attends to it: the driver is gone
double seconds_to_stop(consist &Train, double const Limit) {
auto seconds{0.0};
while (seconds < Limit && std::abs(Train[0].speed()) > 0.01) {
Train.run(1.0, line);
seconds += 1.0;
}
return seconds;
}
crew::vehicle_state const empty_locomotive{.has_cab = true};
crew::vehicle_state const ai_driven{.has_cab = true, .has_driver = true, .driver_is_ai = true};
} // namespace
TEST_CASE("crew: the command is told by its prefix, in this case only") {
CHECK(crew::is_command("Crew:EP07-424"));
CHECK(crew::is_command("Crew:"));
CHECK_FALSE(crew::is_command("crew:ep07-424"));
CHECK_FALSE(crew::is_command("CREW:EP07-424"));
CHECK_FALSE(crew::is_command("Crew"));
CHECK_FALSE(crew::is_command("Timetable:Crew:1"));
CHECK_FALSE(crew::is_command("SetVelocity"));
CHECK_FALSE(crew::is_command(""));
}
TEST_CASE("crew: the vehicle is named in the text, as the scenery keeps its names") {
// the examples of the issue: Shift+4 a crew in cab A, Shift+5 in cab B, Shift+6 the crew off
auto const front{crew::parse("Crew:EP07-424", 1.0, 0.0)};
CHECK(front.vehicle == "ep07-424");
CHECK(front.cab_valid);
CHECK(front.cab == 1);
CHECK(front.flags == 0);
auto const rear{crew::parse("Crew:EP07-424", -1.0, 0.0)};
CHECK(rear.cab_valid);
CHECK(rear.cab == -1);
auto const off{crew::parse("Crew:EP07-424", 0.0, 0.0)};
CHECK(off.cab_valid);
CHECK(off.cab == 0);
SUBCASE("only the ASCII letters are folded, as the scenery parser folds them") {
// "Ś" of windows-1250 (0x8C) and the two bytes of "Ł" in UTF-8 stay as they are
std::string const name{"SM42-\x8C\xC5\x81" "A"};
CHECK(crew::parse("Crew:" + name, 1.0, 0.0).vehicle == "sm42-\x8C\xC5\x81" "a");
}
SUBCASE("no name: the vehicle which set the event off") {
auto const activator{crew::parse("Crew:", 1.0, 0.0)};
CHECK(activator.vehicle.empty());
CHECK(activator.cab_valid);
}
SUBCASE("a name with a colon in it is kept whole") {
CHECK(crew::parse("Crew:a:b", 1.0, 0.0).vehicle == "a:b");
}
SUBCASE("the second value is kept for later, nothing reads it yet") {
CHECK(crew::parse("Crew:x", 0.0, 1.0).flags == 1);
CHECK(crew::parse("Crew:x", 0.0, 3.0).flags == 3);
}
}
TEST_CASE("crew: a cab other than 1, -1 or 0 is not guessed at") {
for (auto const cab : {2.0, -2.0, 0.5, -0.5, 1.5, 100.0}) {
CAPTURE(cab);
auto const request{crew::parse("Crew:ep07-424", cab, 0.0)};
CHECK_FALSE(request.cab_valid);
CHECK(crew::decide(request, empty_locomotive) == crew::action::refuse_cab);
CHECK(crew::decide(request, ai_driven) == crew::action::refuse_cab);
}
}
TEST_CASE("crew: text which is not the command asks for nothing") {
auto const request{crew::parse("SetVelocity", 1.0, 0.0)};
CHECK(request.vehicle.empty());
CHECK_FALSE(request.cab_valid);
CHECK_FALSE(crew::changes_crew(crew::decide(request, empty_locomotive)));
}
TEST_CASE("crew: a vehicle without a driver gets an AI one in the cab asked for") {
CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), empty_locomotive) == crew::action::add_front);
CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), empty_locomotive) == crew::action::add_rear);
}
TEST_CASE("crew: no second driver in a vehicle, and none in a vehicle without a cab") {
CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), ai_driven) == crew::action::refuse_crewed);
CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), ai_driven) == crew::action::refuse_crewed);
// a wagon, or a car of a unit without a cab
CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), crew::vehicle_state{}) == crew::action::refuse_no_cab);
}
TEST_CASE("crew: no second driver in charge of a consist") {
auto const second{crew::vehicle_state{.has_cab = true, .consist_driven = true}};
CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), second) == crew::action::refuse_consist_driven);
CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), second) == crew::action::refuse_consist_driven);
}
TEST_CASE("crew: the AI driver is taken off, in charge of the consist or not") {
CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), ai_driven) == crew::action::remove);
auto helper{ai_driven};
helper.consist_driven = true;
CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), helper) == crew::action::remove);
// AI drivers ride vehicles without a cab of their own too (a car of a unit set as driven in the scenery)
auto const nocab{crew::vehicle_state{.has_driver = true, .driver_is_ai = true}};
CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), nocab) == crew::action::remove);
}
TEST_CASE("crew: taking the driver off a vehicle which has none does nothing") {
auto const decision{crew::decide(crew::parse("Crew:x", 0.0, 0.0), empty_locomotive)};
CHECK(decision == crew::action::nothing);
CHECK_FALSE(crew::changes_crew(decision));
}
TEST_CASE("crew: a vehicle with a user in it is left alone") {
// the user drives; the user sits in the cab while the autopilot drives; the user sits in a vehicle whose
// controller is the AI's (a cab of the game bound to the vehicle is what counts)
auto const driving{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false, .occupied = true}};
auto const autopilot{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = true, .occupied = true}};
auto const human{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false}};
for (auto const &state : {driving, autopilot, human}) {
for (auto const cab : {1.0, -1.0, 0.0}) {
CAPTURE(cab);
auto const decision{crew::decide(crew::parse("Crew:x", cab, 0.0), state)};
CHECK(decision == crew::action::refuse_user);
CHECK_FALSE(crew::changes_crew(decision));
}
}
}
TEST_CASE("crew: only adding and removing change the crew, and every outcome has its words for the log") {
using enum crew::action;
for (auto const action : {add_front, add_rear, remove}) {
CHECK(crew::changes_crew(action));
CHECK_FALSE(crew::describe(action).empty());
}
for (auto const action : {nothing, refuse_cab, refuse_user, refuse_crewed, refuse_no_cab, refuse_consist_driven}) {
CHECK_FALSE(crew::changes_crew(action));
CHECK_FALSE(crew::describe(action).empty());
}
// the scenario cases look for these in the log
CHECK(crew::describe(add_front) == "an AI driver takes cab A");
CHECK(crew::describe(add_rear) == "an AI driver takes cab B");
CHECK(crew::describe(remove) == "the AI driver leaves");
CHECK(crew::describe(refuse_user).starts_with("refused"));
}
TEST_CASE("crew: a locomotive under power left by its driver stops and stays braked") {
test::reseed_random();
consist train;
train.add(definition::fiz("4e_v1/4e"), 1);
get_under_way(train, 20, 30.0);
auto &eu07{train[0].mover()};
REQUIRE(train[0].speed() > 20.0);
REQUIRE(eu07.MainCtrlPos > 0);
REQUIRE(eu07.Mains);
crew::secure(eu07, eu07);
CHECK(eu07.MainCtrlPos == eu07.MainCtrlNoPowerPos());
CHECK(eu07.ScndCtrlPos == 0);
CHECK(eu07.BrakeCtrlPos == static_cast<int>(eu07.Handle->GetPos(bh_EB)));
CHECK(eu07.CabActive == 0);
CHECK(eu07.CabOccupied == 0);
CHECK_FALSE(eu07.CabMaster);
auto const stoppedafter{seconds_to_stop(train, 120.0)};
CAPTURE(stoppedafter);
CHECK(std::abs(train[0].speed()) <= 0.01);
CHECK(eu07.PipePress < 1.0); // vented by the emergency position
CHECK(eu07.BrakePress > 2.0);
// it keeps standing, also on a slope, with the engine as the driver left it
train.run(120.0, track{0.15, 0.02, test::catenary_3kv});
CHECK(std::abs(train[0].speed()) <= 0.01);
CHECK(eu07.Mains);
CHECK(eu07.Im == doctest::Approx(0.0));
}
TEST_CASE("crew: what the AI held is let go when the driver leaves") {
test::reseed_random();
vehicle cab{definition::load("cab_vehicle")};
cab->DirActive = 1;
cab->WarningSignal = 1;
cab->signal_departure(true);
cab->Sandbox(true);
REQUIRE(cab->DepartureSignal);
REQUIRE(cab->SandDose);
crew::secure(cab.mover(), cab.mover());
CHECK(cab->WarningSignal == 0);
CHECK_FALSE(cab->DepartureSignal);
CHECK_FALSE(cab->SandDose);
}
TEST_CASE("crew: a train left by its driver is braked through the whole of it") {
test::reseed_random();
consist train;
train.add(definition::fiz("4e_v1/4e"), 1);
train.add(definition::fiz("11xa_v2/93a"));
train.add(definition::fiz("11xa_v2/93a"));
get_under_way(train, 20, 40.0);
auto &eu07{train[0].mover()};
auto &last{train[2].mover()};
REQUIRE(train[0].speed() > 15.0);
REQUIRE(last.BrakePress < 0.1);
crew::secure(eu07, eu07);
auto const stoppedafter{seconds_to_stop(train, 180.0)};
CAPTURE(stoppedafter);
CHECK(std::abs(train[0].speed()) <= 0.01);
CHECK(std::abs(train[2].speed()) <= 0.01);
CHECK(last.PipePress < 1.0);
CHECK(last.BrakePress > 1.0);
}
TEST_CASE("crew: a standing locomotive left by its driver is braked too") {
test::reseed_random();
consist train;
train.add(definition::fiz("4e_v1/4e"), 1);
auto driver{test::driving(train)};
REQUIRE(test::start_up(driver, line));
test::release_brakes(driver.cab);
auto &eu07{train[0].mover()};
// the cylinders of a locomotive started up cold take their time to empty
for (int i = 0; i < 180 && eu07.BrakePress >= 0.1; ++i) {
test::drive(driver, line, 1.0);
}
REQUIRE(eu07.BrakePress < 0.1);
crew::secure(eu07, eu07);
// on a slope it would roll away with the brakes off
train.run(120.0, track{0.15, 0.02, test::catenary_3kv});
CHECK(eu07.BrakePress > 2.0);
CHECK(std::abs(train[0].speed()) <= 0.01);
}
TEST_CASE("crew: the power an integrated handle asked for goes when the driver leaves") {
test::reseed_random();
// the handle's demand (eimic) is worked out only while a driver is in charge of the vehicle; left as it
// was, the unit would go on pulling with nobody in it
vehicle impuls{definition::fiz("impuls_v1/31we-a_pr"), 60.0, "impuls", 1};
impuls->CabActivisation();
impuls->MainCtrlPos = impuls->MainCtrlPosNo;
impuls->eimic = 0.8;
impuls->eimic_real = 0.8;
crew::secure(impuls.mover(), impuls.mover());
CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos());
CHECK(impuls->eimic == 0.0);
CHECK(impuls->eimic_real == 0.0);
CHECK(impuls->BrakeCtrlPos == static_cast<int>(impuls->Handle->GetPos(bh_EB)));
CHECK(impuls->CabOccupied == 0);
}
TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver stops it with") {
test::reseed_random();
vehicle bus{definition::fiz("road/man/nl293"), 40.0, "bus", 1};
REQUIRE(bus->BrakeSystem == TBrakeSystem::Individual);
REQUIRE(bus->LocalBrakePosA == 0.0);
bus->CabActivisation();
crew::secure(bus.mover(), bus.mover());
CHECK(bus->LocalBrakePosA == 1.0);
CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos());
bus.run(60.0, track{0.6, 0.0, 0.0, 2});
CHECK(std::abs(bus.speed()) <= 0.01);
}

134
vehicle/crew.cpp Normal file
View File

@@ -0,0 +1,134 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "vehicle/crew.h"
#include "McZapkie/MOVER.h"
#include "vehicle/handover.h"
namespace crew {
namespace {
// the scenery parser folds the ASCII letters of the names only, and so does this
char lower_ascii(char const Character) {
return Character >= 'A' && Character <= 'Z' ? static_cast<char>(Character - 'A' + 'a') : Character;
}
// the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so
void cut_power(TMoverParameters &Vehicle) {
Vehicle.MainCtrlPos = Vehicle.MainCtrlNoPowerPos();
Vehicle.ScndCtrlPos = 0;
// what the integrated handle and the cruise control asked for last stays in force until somebody drives
Vehicle.eimic = 0.0;
Vehicle.eimic_real = 0.0;
Vehicle.SpeedCtrlValue = 0.0;
Vehicle.SpeedCtrlUnit.IsActive = false;
Vehicle.SendCtrlToNext("MainCtrl", Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive);
Vehicle.SendCtrlToNext("ScndCtrl", Vehicle.ScndCtrlPos, Vehicle.CabActive);
Vehicle.SendCtrlToNext("EIMIC", 0.0, Vehicle.CabActive);
}
} // namespace
bool is_command(std::string_view const Text) {
return Text.starts_with(command_prefix);
}
request parse(std::string_view const Text, double const Cab, double const Flags) {
request result;
if (false == is_command(Text)) {
return result;
}
result.vehicle = Text.substr(command_prefix.size());
std::ranges::transform(result.vehicle, result.vehicle.begin(), lower_ascii);
result.cab_valid = Cab == 1.0 || Cab == -1.0 || Cab == 0.0;
if (result.cab_valid) {
result.cab = static_cast<int>(Cab);
}
result.flags = static_cast<int>(std::clamp(Flags, -65535.0, 65535.0));
return result;
}
action decide(request const &Request, vehicle_state const &State) {
using enum action;
if (false == Request.cab_valid) {
return refuse_cab;
}
if (State.occupied || (State.has_driver && false == State.driver_is_ai)) {
return refuse_user;
}
if (Request.cab == 0) {
return State.has_driver ? remove : nothing;
}
if (State.has_driver) {
return refuse_crewed;
}
if (false == State.has_cab) {
return refuse_no_cab;
}
if (State.consist_driven) {
return refuse_consist_driven;
}
return Request.cab > 0 ? add_front : add_rear;
}
bool changes_crew(action const Action) {
return Action == action::add_front || Action == action::add_rear || Action == action::remove;
}
std::string_view describe(action const Action) {
using enum action;
switch (Action) {
case add_front:
return "an AI driver takes cab A";
case add_rear:
return "an AI driver takes cab B";
case remove:
return "the AI driver leaves";
case nothing:
return "no driver to take off";
case refuse_cab:
return "refused, the cab has to be 1, -1 or 0";
case refuse_user:
return "refused, a user is in the vehicle";
case refuse_crewed:
return "refused, the vehicle has a driver already";
case refuse_no_cab:
return "refused, the vehicle has no cab";
case refuse_consist_driven:
return "refused, the consist has a driver in charge in another vehicle";
default:
return "";
}
}
void secure(TMoverParameters &Occupied, TMoverParameters &Controlling) {
handover::release_ai_controls(Occupied, Controlling);
cut_power(Controlling);
if (&Occupied != &Controlling) {
cut_power(Occupied);
}
// the emergency position vents the brake pipe whatever the brake mode, and with nobody in the cab too
Occupied.BrakeLevelSet(Occupied.Handle->GetPos(bh_EB));
// a vehicle with no train brake (a car, a draisine) gets the brake its driver stops it with, in full
if (Occupied.BrakeSystem == TBrakeSystem::Individual) {
if (Occupied.LocalBrake == TLocalBrake::ManualBrake) {
Occupied.IncManualBrakeLevel(ManualBrakePosNo);
}
else {
Occupied.IncLocalBrakeLevel(LocalBrakePosNo);
}
}
Occupied.CabDeactivisation();
Occupied.CabOccupied = 0;
}
} // namespace crew

82
vehicle/crew.h Normal file
View File

@@ -0,0 +1,82 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <string>
#include <string_view>
class TMoverParameters;
// a driver put in a vehicle, or taken off it, while the scenario runs (eu07/maszyna#510): the command of a
// putvalues event
// event <name> putvalues <delay> none 0 0 0 Crew:<vehicle> <cab> <flags> endevent
// with the name of the vehicle in the text, so the event works whatever sets it off (a key, an event
// launcher), the cab in the first value: 1 an AI driver in cab A, -1 in cab B, 0 nobody, and the second value
// reserved (0). "Crew:" with no name is for the vehicle which set the event off.
// here are the parts which need no vehicle of the game: reading the command, deciding what to do about it,
// and the state a train is left in when its driver goes. the game's side of it is in crewchange.h
namespace crew {
// what the text of the command starts with, in this very case (the commands of the events are case sensitive)
inline constexpr std::string_view command_prefix{"Crew:"};
// whether the text of a putvalues event is the crew command
bool is_command(std::string_view Text);
// the command as the event gives it
struct request {
std::string vehicle; // as the scenery keeps the names, in lower case; empty: the vehicle which set the event off
int cab{0}; // 1 a driver in cab A (the front one), -1 in cab B, 0 nobody
bool cab_valid{false}; // the value was one of the three
int flags{0}; // reserved, nothing reads it yet
};
// reads the command from the text of the event and its two values
request parse(std::string_view Text, double Cab, double Flags);
// what the command finds in the vehicle
struct vehicle_state {
bool has_cab{false}; // the type of the vehicle has a driver's cab; a road vehicle or a boat counts as having one
bool has_driver{false};
bool driver_is_ai{false}; // the driver it has is the AI, not a user
bool occupied{false}; // a user sits in the vehicle, whoever drives it
bool consist_driven{false}; // another vehicle of the consist has the driver in charge of it
};
enum class action {
add_front, // an AI driver goes into cab A
add_rear, // an AI driver goes into cab B
remove, // the AI driver is taken off
nothing, // asked to take the driver off a vehicle which has none
refuse_cab, // the cab asked for is none of 1, -1, 0
refuse_user, // a user is in the vehicle, or drives it
refuse_crewed, // asked for a driver where there is one already
refuse_no_cab, // asked for a driver in a vehicle with no cab
refuse_consist_driven // asked for a driver in a consist which another vehicle's driver is in charge of
};
// what to do about the command. a user in the vehicle is never touched: neither replaced nor left without
// the driver the cab of the game works with
action decide(request const &Request, vehicle_state const &State);
// whether the action changes anything
bool changes_crew(action Action);
// the action in words, for the log
std::string_view describe(action Action);
// the state a train is left in when the driver in charge of it goes: what the AI held is let go (as when it
// hands over to a user, see handover.h), the power is off, the driver's brake valve is in the emergency position,
// so a train on the move stops and stays braked, and the cab is neither active nor occupied. the engine, the
// pantographs and the lights stay as they were. Occupied is the vehicle of the driver, Controlling the one whose
// motors it drove (the AI's mvOccupied and mvControlling; the same one in a locomotive)
void secure(TMoverParameters &Occupied, TMoverParameters &Controlling);
} // namespace crew

138
vehicle/crewchange.cpp Normal file
View File

@@ -0,0 +1,138 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "vehicle/crewchange.h"
#include "simulation/simulation.h"
#include "utilities/Logs.h"
#include "vehicle/Driver.h"
#include "vehicle/DynObj.h"
#include "vehicle/Train.h"
#include "vehicle/handover.h"
namespace crew {
namespace {
// TMoverParameters::CategoryFlag of the rail vehicles
constexpr int rail_category{1};
// more vehicles than a consist has, for a walk along one whose couplers form a loop
constexpr int consist_walk_limit{300};
// calls the function for each vehicle of the consist, from one end of it to the other. goes by the couplers
// alone, as the driver's own check of the consist does, so it works for a consist nobody has put in order
template <typename Function_>
void for_each_in_consist(TDynamicObject &Vehicle, Function_ const Function) {
auto side{static_cast<int>(end::front)};
auto *vehicle{Vehicle.FirstFind(side)};
side = 1 - side;
auto count{0};
while (vehicle != nullptr && count < consist_walk_limit) {
Function(*vehicle);
vehicle = vehicle->Neighbour(side);
++count;
}
}
// whether another vehicle of the consist has the driver in charge of it
bool is_consist_driven(TDynamicObject &Vehicle) {
auto driven{false};
for_each_in_consist(Vehicle, [&Vehicle, &driven](TDynamicObject const &Other) {
if (&Other != &Vehicle && Other.Mechanik != nullptr && Other.Mechanik->primary()) {
driven = true;
}
});
return driven;
}
vehicle_state state_of(TDynamicObject &Vehicle) {
vehicle_state state;
// a rail vehicle has a cab when it has the driver's brake valve. the others (cars, boats) have no such valve
// to tell by, and each of them is driven from its own seat
state.has_cab = Vehicle.MoverParameters->HasDriverCab() || Vehicle.MoverParameters->CategoryFlag != rail_category;
state.has_driver = Vehicle.Mechanik != nullptr;
state.driver_is_ai = state.has_driver && Vehicle.Mechanik->AIControllFlag;
// a cab of the game is bound to the vehicle: the user's own, or another user's in a network game. the cab
// reads the driver of its vehicle all the time, so that driver stays
state.occupied = simulation::Trains.find(Vehicle.name()) != nullptr;
state.consist_driven = is_consist_driven(Vehicle);
return state;
}
// an AI driver for the vehicle, as the scenery gives one to a vehicle of its own outside a trainset: in charge of
// the consist, with no timetable, waiting for orders when the vehicle stands and driving on when it rolls
void add_driver(TDynamicObject &Vehicle, int const Cab) {
Vehicle.MoverParameters->CabOccupied = Cab;
Vehicle.Controller = AIdriver;
Vehicle.create_controller(Cab > 0 ? "1" : "2", false);
}
// takes the AI driver off. nothing but the vehicle and the vehicles the driver is in charge of points at a driver
// (the panels, the events, the network and the black box read it from a vehicle each time), so these are cleared
// and the driver deleted. the vehicles in its charge are looked for among all vehicles, not along the couplers:
// a coupler broken under force or in a collision (TMoverParameters::damage_coupler()) parts the train and leaves
// the vehicles parted from it in the driver's charge, as uncoupling (TDynamicObject::Dettach()) doesn't
void remove_driver(TDynamicObject &Vehicle) {
auto *driver{Vehicle.Mechanik};
auto &occupied{*Vehicle.MoverParameters};
auto &controlling{*Vehicle.FindPowered()->MoverParameters};
if (driver->primary()) {
// the train this driver was in charge of stops and stays braked
secure(occupied, controlling);
}
else {
// somebody else drives the train, so only what this one held is let go
handover::release_ai_controls(occupied, controlling);
occupied.CabOccupied = 0;
}
Vehicle.Mechanik = nullptr;
auto released{0};
for (auto *other : simulation::Vehicles.sequence()) {
if (other->ctOwner == driver) {
other->ctOwner = nullptr;
++released;
}
}
WriteLog("Crew: [" + Vehicle.name() + "] the driver was in charge of " + std::to_string(released) + (released == 1 ? " vehicle" : " vehicles"));
delete driver;
}
} // namespace
void change(request const &Request, TDynamicObject const *Activator) {
std::string const name{Request.vehicle.empty() && Activator != nullptr ? Activator->name() : Request.vehicle};
if (name.empty()) {
ErrorLog("Bad event: \"" + std::string{command_prefix} + "\" names no vehicle and no vehicle set the event off");
return;
}
auto *vehicle{simulation::Vehicles.find(name)};
if (vehicle == nullptr || false == vehicle->bEnabled) {
ErrorLog("Bad event: \"" + std::string{command_prefix} + name + "\" can't find the vehicle");
return;
}
if (Request.flags != 0) {
WriteLog("Crew: [" + name + "] flags " + std::to_string(Request.flags) + " ignored, none is defined yet");
}
auto const decision{decide(Request, state_of(*vehicle))};
WriteLog("Crew: [" + name + "] " + std::string{describe(decision)});
switch (decision) {
case action::add_front:
case action::add_rear:
add_driver(*vehicle, Request.cab);
break;
case action::remove:
remove_driver(*vehicle);
break;
default:
break;
}
}
} // namespace crew

24
vehicle/crewchange.h Normal file
View File

@@ -0,0 +1,24 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "vehicle/crew.h"
class TDynamicObject;
namespace crew {
// carries out the crew command of an event (see crew.h) on the vehicle it names, or on Activator, the vehicle
// which set the event off, when it names none: puts an AI driver in, the way the scenery does for a vehicle of
// its own with a driver, or takes the AI driver off and leaves the train secured. whatever it does or refuses
// goes to the log. called from the event queue, between the updates of the vehicles
void change(request const &Request, TDynamicObject const *Activator);
} // namespace crew

View File

@@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/.
#include "model/AnimModel.h"
#include "vehicle/DynObj.h"
#include "vehicle/Driver.h"
#include "vehicle/crewchange.h"
#include "rendering/renderer.h"
#include "utilities/Timer.h"
#include "utilities/Logs.h"
@@ -782,6 +783,12 @@ putvalues_event::run_() {
+ to_string( m_input.data_value_1, 2 ) + "] ["
+ to_string( m_input.data_value_2, 2 ) + "]" );
if( crew::is_command( m_input.data_text ) ) {
// a driver for the vehicle named in the command, or none (eu07/maszyna#510). not a command for a driver or
// a vehicle to take, and it works with nothing setting the event off too (a key, an event launcher)
crew::change( crew::parse( m_input.data_text, m_input.data_value_1, m_input.data_value_2 ), m_activator );
return;
}
if( m_activator == nullptr ) { return; }
// zamiana, bo fizyka ma inaczej niż sceneria
// NOTE: y & z swap, negative x